0% found this document useful (0 votes)
2 views

Complete Java Fundamentals

Uploaded by

Amarsingh Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Complete Java Fundamentals

Uploaded by

Amarsingh Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

GenieAshwani

Introduction to Java Programming

Why Do We Need Programming Languages?

• Communication with Computers: Programming languages allow humans to


communicate instructions to computers in a way they can understand.

Java History

Home: SUN Mc Systems (Oracle Corporation)

Author: James Gosling

Objective: To prepare simple electronic consumer goods.

Project: Green

First Version: JDK 1.0 (1996, Jan-23rd)

Used Version: Some org JDK5.0, Some other JAVA 6, JAVA 7

Latest Version: JAVA7, JAVA8, This April – JAVA 9

Type of Software: Open-Source Software

Differences between Java and Others

C and C++ are static programming languages but JAVA is dynamic programming
language

• If any programming language allows memory allocation for primitive data types
at compilation time [Static Time] then that programming language is called as
Static Programming language.
GenieAshwani

EX: C and C++.

• In C and C++ applications, memory will be allocated for primitive data types at
compilation time only, not at runtime.
• If any programming language allows memory allocation for primitive data types
at runtime, not at compilation time then that programming language is called as
Dynamic Programming Language.

EX: JAVA

• In java applications, memory will be allocated for primitive data types at runtime
only, not at compilation time.
• Note: In Java applications, memory will be allocated for primitive data types at
the time of creating objects only, in java applications, objects are created at
runtime only

Pre-Processor is required in C and C++, but Pre-Processor is not required in Java:

In case of C and C++, the complete predefined library is provided in the form of
header files

If we want to use predefined library in C and C++ applications, we have to include


header files in C and C++ applications, for this, we have to use #include<> statement.

EX:

• #include<stdio.h>
• #include<conio.h>
• #include<math.h>

If we compile C and C++ applications then Pre-Processor will perform the following
actions.

1) Pre-Processor will recognize all #include<> statement


2) Pre-Processor will take all the specified header files from #include<>
statements.
3) If the specified header files are existed then Pre-Processor will load the specified
header files to the memory, this type of loading predefined library at compilation
time is called as "Static Loading"
GenieAshwani

In java, the complete predefined library is provided in the form of classes and interfaces
in packages

EX:

• java.io
• java.util
• java.sql

If we want to use predefined library in java applications then we have to include


packages in java application, for this we have to use "import" statements

EX:

• import java.io.*;
• import java.util.*;
• import java.sql.*;

While executing java program, when JVM[Java Virtual Machine] encounter any class or
interface from the specified package then only JVM will load the required classes and
interfaces to the memory at runtime, loading predefined library at runtime is called as
"Dynamic Loading".
GenieAshwani

3. C and C++ are platform dependent programming languages, but JAVA is platform
independent programming language.

If any PL allows its applications to perform compilation and execution on the same
Operating System then that PL is called as Platform Dependent PL.
GenieAshwani

If any PL allows its applications to perform Compilation is on one OS and execution is


on another OS then that PL is called as Platform independent PL.

Platform Dependent vs. Platform Independent

Platform Dependent: A programming language that allows its applications to be


compiled and executed on the same operating system (e.g., C with .exe files).

Platform Independent: Java, with its .class files containing bytecode, can be executed
on any operating system.

What are the differences between .exe file and .class file?
GenieAshwani

Setting Up Java Enviroment

• Download Java 17: Oracle JDK 17 Archive


• Set Path: Ensure Java is properly installed by setting the system path.
• Verify Installation: Run java --version in the command prompt.

Writing Java Code

You can use various text editors like Notepad, Notepad++, EditPlus, or an IDE like
IntelliJ.

Java program Structure

1. package statement

2. import statement [A--->B]

3. class declaration

4. Methods

5. variable
GenieAshwani

Package Statement (Optional)

• What It Is: A way to group related classes and organize your code.
• Why It's Used: Helps avoid name conflicts and makes the code more
manageable.
• Example: package my package;
• Note: Your program can work without it.

Import Statements

• What It Is: Allows you to use classes from other packages.


• Why It's Used: Saves time by reusing code from the Java library or other
sources.
• Example: import java.util.Scanner;
• Note: Think of it as bringing in tools from a toolbox to use in your program.

Class Declaration

• What It Is: Defines a new class.


• Why It's Used: All Java code must be inside a class.
• Note: If The class is public then name of file should match the class name.

Example
GenieAshwani

Methods

• What It Is: Blocks of code that perform specific tasks.


• Why It's Used: Helps to organize code into reusable chunks.
• Note: The main method is the entry point of any Java program

Variables:

• Variables are used to hold/share the data during the program execution
• We need to specify type of the variable to store the data
• To specify type of data we will use 'data types'

Translators in Programming

1. Interpreter: Translates code line-by-line.


2. Compiler: Translates entire code at once.
3. Assembler: Converts assembly language to machine code.

Class And Object:

Class is a blueprint or template for creating objects.

Example: Think of a class as the blueprint of a house. The blueprint itself isn't a house,
but it details the design and features of the house.

Object An instance of a class.

Example: An object is like a real house made from the blueprint. Each house can look
the same but is a separate, physical thing.
GenieAshwani

Data Type

Range:
GenieAshwani

JDK, JRE, and JVM

JDK (Java Development Kit)

• Role: It's the tool for making Java programs.


o How It Works: The JDK includes a compiler to turn your Java code into a
format the computer can understand (bytecode).
• It also includes the JRE to test and run the programs you make.

JRE (Java Runtime Environment)

• Role: It's the setup needed to run Java programs.


o How It Works: The JRE includes libraries and components that help your
Java programs run.
• It includes the JVM, which is the part that actually runs your programs.

JVM (Java Virtual Machine)

• Role: It's the part that runs Java programs.


o How It Works: The JVM reads the bytecode (compiled Java code) and
translates it into machine code that your computer can execute.

How They Work Together:

JDK: You use it to write and compile Java programs.

JRE: Provides the environment and libraries needed to run Java programs.

JVM: Runs the bytecode produced by the JDK, turning it into machine code your
computer can understand.
GenieAshwani

Java Identifiers

Identifiers are the names given to class, variable, method, interface.

Rules for naming Identifiers:

1. valid char : lower case , Upper case, digit, _, $

2. Start with : letter,_, $. it cannot start with digit

3. case Sensitivity : car, CAR , cAR, Car

4. Reserved Keyword’s: (int, for, if, class) cannot be used

Convention For Naming Identifiers (best for Identifiers):

1. CamelCase: for classes, method and variable eg: carName, cityName

2. Meaningful : String cityName = "10202" ,cityName="Agra"

Eg: Identifiers

age ----------> valid

_marks --------> valid

$value --------> valid

8marks ----------> invalid

class -----------> invalid

my-name ---------> invalid

@cityName -------> invalid

calCulater ------> valid


GenieAshwani

How to run java code


CHAPTER 2
Operators
- Arithmetic
- Relational
- Logical
- Assignment
- New
- Dot (.) Operator
Control Statements
- Conditional Statements
- Looping Statements
- Transfer Statements

Operators
-> Operator is a symbol which tells to the compiler to perform some
operation.
-> Java provides a rich set of operators do deal with various types of
operations.
-> Sometimes we need to perform arithmetic operations then we use plus
(+) operator for
addition, multiply (*) for multiplication etc.
-> Operators are always essential part of any programming language.
-> Java operators can be divided into following categories:
• Arithmetic operators
• Relation operators
• Logical operators
• Assignment operators
• Conditional operators
• Misc. operators

Arithmetic operators
Arithmetic operators are used to perform arithmetic operations like:
addition, subtraction etc and helpful to solve mathematical expressions.
The below table contains Arithmetic operators.
Increment & Decrement Operators

In programming (Java, C, C++, JavaScript etc.), the increment operator ++


increases the
value of a variable by 1. Similarly, the decrement operator -- decreases
the value of a
variable by 1.
Post-Increment (Ex: a ++): Value is first used for computing the result and
then incremented.
Pre-Increment (Ex: ++ a): Value is incremented first and then the result is
computed.
Post-decrement (Ex: a--): Value is first used for computing the result and
then decremented
Pre-decrement (Ex: --a): Value is decremented first and then the result is
computed.

Imp Points about Increment and Decrement operators


• Can only be applied to variables only
• Nesting of both operators is not allowed
• They are not operated over final variables
• Increment and Decrement Operators cannot be applied to Boolean

Relational operators
Relational operators are used to test comparison between operands or
values. It can be
used to test whether two values are equal or not equal or less than or
greater than etc.
The following table shows all relation operators supported by Java.
Logical operators
Logical Operators are used to check conditional expression. For example,
we can use logical
operators in if statement to evaluate conditional based expression. We can
use them into
loop as well to evaluate a condition. Java supports following 3 logical
operators. Suppose we have two variables whose values
are: a=true and b=false.
Assignment Operators
Assignment operators are used to assign a value to a variable. It can also
be used combine
with arithmetic operators to perform arithmetic operations and then
assign the result to the
variable. Assignment operator supported by Java are as follows:

Conditional operator
It is also known as ternary operator because it works with three
operands. It is short
alternate of if-else statement. It can be used to evaluate Boolean
expression and return
either true or false value
Syntax : epr1 ? expr2 : expr3
In ternary operator, if epr1 is true then expression evaluates after question
mark (?) else
evaluates after colon (:). See the below example.

instanceOf operator
It is a java keyword and used to test whether the given reference belongs
to provided type
or not. Type can be a class or interface. It returns either true or false.
Example:
Here, we created a string reference variable that stores “Ashok IT”. Since
it stores string
value so we test it using instance operator to check whether it belongs to
string class or not.
See the below example

new operator
• new is java keyword or operator which is used to create the object
• we can create an object for both user defined classes and predefine
classes
• creating an object nothing but allocating the memory so that we can use
in the
application.
• once an object created that will be located inside the Heap memory of
JVM.
. (Dot) operator
-> This operator used to access the members of the class using reference
or column like
follows
Eg:
reference.variable
reference.method()
-> This operator can also be used to refer or identify the class from a
package
Eg:
java.lang.NoSuchMethodError
java.lang.String
Control statements (flow control)
-> In java we can write any number of statements which are executed in
sequence order by default
-> But if we want to execute java statements according to our requirement
then we have to use control statements
-> These statements decide whether a specific part of the code will be
executed or not.

Types of Control Flow Statements


-> There are different types of control statements available in Java for
different situations or conditions.
-> In java, we can majorly divide control statements into three major
types:
1. Selection / Conditional statements
2. Loop statements
3. Jump / Branching / Transfer statements
Conditional / Selection Statements
-> Conditional statements are used to execute group of statements based
on condition
-> Conditional statements will evaluate boolean expression to make the
decision Simple ‘if’ statement in java
-> In java, we use if statement to test a condition and decide the execution
of a block of statements based on that condition result.
-> If the condition is True, then the block of statements is executed and if it
is false, then the block of statements will be ignored.

The syntax and execution flow of if the statement is as follows.


if-else statement in java
-> In java, we use the if-else statement to test a condition and pick the
execution of a block of statements out of two blocks based on that
condition result.
-> The if-else statement checks the given condition then decides which
block of statements to be executed based on the condition result.
-> If the condition is True, then the true block of statements is executed
and if it is False, then the false block of statements is executed.
Nested if statement in java

if...else if…else statement


if…else if statements will be used when we need to compare the value with
more than 2 conditions.
They are executed from top to bottom approach. As soon as the code finds
the matching condition, that block will be executed. But if no condition is
matching then the last else statement will be executed.

Switch statement
-> Java switch statement compares the value and executes one of the
case blocks based on the condition.
-> It is same as if…else if ladder. Below are some points to consider while
working with
switch statements:
• There can be one or N number of cases
• The values in the case must be unique
• case value must be of the same type as expression used in switch
statement
• each case statement can have break statement (it is optional)
Looping Statements in Java
-> Loop is an important concept of a programming that allows to iterate
over the sequence of statements.
-> Loop is designed to execute particular code block till the specified
condition is true or all the elements of a collection (array, list etc) are
completely traversed.
-> The most common use of loop is to perform repetitive tasks. For
example, if we want to
print table of a number then we need to write print statement 10 times.
However, we can do the same with a single print statement by using loop.
-> Loop is designed to execute its block till the specified condition is true.
Java provides mainly three loops based on the loop structure.
1. for loop
2. while loop
3. do while loop

for loop in java


The for loop is used to execute a single statement or a block of statements
repeatedly as long as the given condition is TRUE.
To create a for loop, we need to set the following parameters.
1) Initialization: It is the initial part, where we set initial value for the loop.
It is executed only once at the starting of loop. It is optional, if we don’t
want to set initial value.
2) Condition: It is used to test a condition each time while executing. The
execution continues until the condition is false. It is optional and if we don’t
specify, loop will be infinite.
3) Statement: It is loop body and executed every time until the condition is
false.
4) Increment/Decrement: It is used for set increment or decrement value
for the loop.
while statement in java
The while loop is used to execute a single statement or block of
statements repeatedly as long as the given condition is TRUE. The while
statement is also known as Entry control looping statement. The syntax
and execution flow of while statement is as follows.
do-while statement in java
The do-while loop is used to execute a single statement or block of
statements repeatedly as long as given the condition is TRUE. The do-
while statement is also known as the Exit control looping statement. The
do-while statement has the following syntax
Nested For Loop
Writing a loop inside another loop is called as Nested For Loop
for-each loop in java
-> The Java for-each statement was introduced since Java 5.0 version.
-> It provides an approach to traverse through an array or collection in
Java.
-> The for-each statement also known as enhanced for statement.
-> The for-each statement executes the block of statements for each
element of the given array or collection

Branching / Transfer Statements


-> Transferring statements are the control statements which are used to
transfer the control position from 1 location to another location
-> In Java we have following 3 types of transfer statements
1) break
2) continue
3) return

Break statement
-> In Java, break is a statement that is used to break current execution
flow of the program.
-> We can use break statement inside loop, switch case etc.
-> If break is used inside loop then it will terminate the loop.
-> If break is used inside the innermost loop then break will terminate the
innermost loop only and execution will start from the outer loop.
-> If break is used in switch case then it will terminate the execution after
the matched case.
Continue Statement
-> In Java, the continue statement is used to skip the current iteration of
the loop. It jumps
to the next iteration of the loop immediately.
-> We can use continue statement with for loop, while loop and do-while
loop as well.
Return statement
-> return is a transferring statement which is used to stop the continuity
of method execution

public String plot()


{
return "Khushi coffee point";
}

Arrays
• Array is an object which contains elements of similar data type
• Array is a container object that hold values of homogeneous type.
• Array is also known as static data structure because size of an array
must be specified at the time of its declaration.
• Array starts from zero index and goes to n-1 where n is length of the
array.
• Array in Java is index-based, the first element of the array is stored
at the 0th index, 2nd element is stored on 1st index and so on.
• In Java, array is treated as an object and stores into heap memory. It
allows to store primitive values or reference values.
-> Instantiation is a process of allocating memory to an array. At the time
of instantiation, we specify the size of array to reserve memory area.
-> In the above example, we created an array arr of int type and can store
5 elements. We iterate the array to access its elements and it prints five
times zero to the console. It prints zero because we did not set values to
array, so all the elements of the array initialized to 0 by default

Set Array Elements


We can set array elements either at the time of initialization or by
assigning direct to its index.

Here, we are assigning values at the time of array creation. It is useful


when we want to store static data into the array.
-> We can set value based on index position also
Accessing array element
We can access array elements by its index value. Either by using loop or
direct index value.
We can use loop like: for, for-each or while to traverse the array elements.
Length Of Array In Java
The length of an array indicates the number of elements present in the
array. Unlike C/C++, where we use ‘sizeof’ operator to get the length of the
array, Java array has ‘length’ property. We will explore more on this
property later.

Strings
-> String is an object that represents sequence of characters.
Ex: "hello”, "ashwani"

You might also like