Unit I
Unit I
JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was developed by James
Gosling and Patrick Naughton.
• Java Development Kit (JDK) is a software development environment used to develop java applications
• It physically exists
Here Java Environment refers to JRE (Java Runtime Environment) JRE is set of software tools which are used for
developing java applications.
Main component of JRE are JVM, set of libraries , User interface toolkits, deployment technologies and other files.
What is JVM?
JVM (Java Virtual Machine)
JVMs are available for many hardware and software platforms - JVM is platform dependent.
Internal Architecture of JVM
A Picture is Worth…
The output of the
compiler is .class
file
byte 1 byte Stores whole numbers from -128 to 127. Default Value is 0.
short 2 bytes Stores whole numbers from -32,768 to 32,767. Default Value is 0.
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647. Default Value is 0.
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits. Default Value is
0.0f.
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits. Default Value is
0.0d.
char 2 bytes Stores a single character/letter or ASCII values. Default Value is '\u0000'
1. boolean
• The boolean data type has two possible values, either true or false.
• Default value: false.
• They are usually used for true/false conditions.
• Example:
class Main
{
public static void main(String[] args)
{
boolean flag = true;
System.out.println(flag); // prints true
}
}
2. byte
• The byte data type can have values from -128 to 127 (8-bit signed two's complement
integer).
• If it's certain that the value of a variable will be within -128 to 127, then it is used instead
of int to save memory.
• Default value: 0
• Example:
class Main
{
public static void main(String[] args)
{
byte range;
range = 124;
System.out.println(range); // prints 124
}
}
3. short
• The short data type in Java can have values from -32768 to 32767 (16-bit signed two's
complement integer).
• If it's certain that the value of a variable will be within -32768 and 32767, then it is used
instead of other integer data types (int, long).
• Default value: 0
• Example:
class Main
{
public static void main(String[] args)
{
short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}
4. int
• The int data type can have values from -231 to 231-1 (32-bit signed two's complement
integer).
• If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have a
minimum value of 0 and a maximum value of 232-1.
• Default value: 0
• Example:
class Main
{
public static void main(String[] args)
{
int range = -4250000;
System.out.println(range); // print -4250000
}
}
5. long
• The long data type can have values from -263 to 263-1 (64-bit signed two's complement
integer).
• If you are using Java 8 or later, you can use an unsigned 64-bit integer with a minimum
value of 0 and a maximum value of 264-1.
• Default value: 0
• Example:
class LongExample
{
public static void main(String[] args)
{
long range = -42332200000L;
System.out.println(range); // prints -42332200000
}
}
6. float
• he float data type is a single-precision 32-bit floating-point. Learn more about single-
precision and double-precision floating-point if you are interested.
• It should never be used for precise values such as currency.
• Default value: 0.0 (0.0f)
• Example: • Notice that we have used -
instead of -42.3 in the
42.3f
class Main
{
public static void main(String[] args)
{
double number = -42.3;
System.out.println(number); // prints -42.3
}
}
8. char
• It's a 16-bit Unicode character.
• The minimum value of the char data type is '\u0000' (0) and the maximum value of the is
'\uffff'.
• Default value: '\u0000’
• Example:
class Main {
public static void main(String[] args)
{
char letter = '\u0051';
System.out.println(letter); // prints Q
char letter1 = '9';
System.out.println(letter1); // prints 9
char letter2 = 65;
System.out.println(letter2); // prints A
}
• Example:
class Main
{
public static void main(String[] args)
{
char letter = '\u0051';
System.out.println(letter); // prints Q
char letter1 = '9';
System.out.println(letter1); // prints 9
char letter2 = 65;
System.out.println(letter2); // prints A
}
}
TYPE CONVERSION AND CASTING
• Type casting is a mechanism in which one data type is converted to another
data type using a casting () operator by a programmer.
• Example:
Narrowing Casting (manually) - converting a larger type to a smaller type
double -> float -> long -> int -> char -> short -> byte
• Type conversion allows a compiler to convert one data type to another data
type at the compile time of a program or code.
• Example:
Widening Casting (automatically) - converting a small type to a larger type
byte -> short -> char -> int -> long -> float -> double
Difference between Type Casting and Type Conversion
OPERATORS
Examples
3+5 // uses + operator
14+5-4*(5-3) // uses +, -, * operators
Types of operators in Java:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. Instance of operator
Java Operator Precedence
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• – : Subtraction
Example
// Arithmetic Operators
import java.io.*;
// Drive Class
class GFG
{
// Main Function
public static void main (String[] args) Output
{ • Addition:30
int a = 10;
int b = 3;
• Substraction:10
System.out.println("a + b = " + (a + b)); • Multiplication:200
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
• Division:2
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
2.Unary Operators
The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:
Example 1 : ++ and –
Output
10
public class OperatorExample 12
{
public static void main(String args[])
12
{ 10
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Example 2:
Output:
public class OperatorExample
{
-11
public static void main(String args[]) 9
{ false
int a=10; true
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
3. Assignment Operator
• The assignment operator can be combined with other operators to build a shorter version of the statement
called a Compound Statement.
• +=, for adding the left operand with the right operand and then assigning it to the variable on the left.
• -=, for subtracting the right operand from the left operand and then assigning it to the variable on the left.
• *=, for multiplying the left operand with the right operand and then assigning it to the variable on the left.
• /=, for dividing the left operand by the right operand and then assigning it to the variable on the left.
• %=, for assigning the modulo of the left operand by the right operand and then assigning it to the variable
on the left.
import java.io.*; Output:
class GFG
{
f += 3: 10
public static void main(String[] args) f -= 2: 8
{
int f = 7;
f *= 4: 32
System.out.println("f += 3: " + (f += 3)); f /= 3: 10
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
f %= 2: 0
System.out.println("f /= 3: " + (f /= 3)); f &= 0b1010: 0
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
f |= 0b1100: 12
System.out.println("f |= 0b1100: " + (f |= 0b1100)); f ^= 0b1010: 6
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
f <<= 2: 24
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1)); f >>= 1: 12
System.out.println("f >>>= 1: " + (f >>>= 1));
f >>>= 1: 6
}
}
4. Relational Operators
These operators are used to check for relations like equality, greater than, and less than.
The general format is,
variable relation_operator value
• ==, Equal to returns true if the left-hand side is equal to the right-hand side.
• !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
• <, less than: returns true if the left-hand side is less than the right-hand side.
• <=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.
• >, Greater than: returns true if the left-hand side is greater than the right-hand side.
• >=, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-hand side.
import java.io.*;
class GFG
{ Output:
public static void main(String[] args) a > b: true
{
a < b: false
int a = 10;
int b = 3; a >= b: true
int c = 5; a <= b: false
System.out.println("a > b: " + (a > b)); a == c: false
System.out.println("a < b: " + (a < b)); a != c: true
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations,
i.e., a function similar to AND gate and OR gate in digital electronics.
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
Example:
import java.io.*;
class GFG
{
public static void main (String[] args) Output
{ x && y: false
boolean x = true; x || y: true
boolean y = false; !x: false
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}
6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name Ternary.
Output
Max of three numbers = 30
7. Bitwise Operators
• These operators are used to perform the manipulation of individual bits of a number.
• can be used with any of the integer types.
• used when performing update and query operations of the Binary indexed trees.
• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns the one’s
complement representation of the input value, i.e., with all bits inverted.
import java.io.*;
class GFG
{
public static void main(String[] args) Output :
{ d & e: 8
int d = 0b1010;
int e = 0b1100; d | e: 14
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e)); d ^ e: 6
System.out.println("d ^ e: " + (d ^ e)); ~d: -11
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2)); d << 2: 40
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1)); e >> 1: 6
} e >>> 1: 6
}
8. Shift Operators
General format-
• <, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar
effect as multiplying the number with some power of two.
• >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a
result. The leftmost bit depends on the sign of the initial number. Similar effect to dividing the number
with some power of two.
• >>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a
result. The leftmost bit is set to 0.
import java.io.*;
// Driver Class
class GFG
{
// main function
Output
public static void main(String[] args)
a<<1 : 20, a>>1 : 5
{
int a = 10;
System.out.println("a<<1 : " + (a << 1));
System.out.println("a>>1 : " + (a >> 1));
}
}
9. Instance of operator
• There are three types of variables in java: local, instance and static.
• A variable provides us with named storage that our programs can manipulate.
• Each variable in Java has a specific type, which determines the size and layout of the
variable’s memory; the range of values that can be stored within that memory; and the set
of operations that can be applied to the variable.
• Before using any variable, it must be declared.
• Here data type is one of Java’s data types and variable is the name of the variable.
• To declare more than one variable of the specified type, use a comma-separated list.
Example:
• int a, b, c; // Declaration of variables a, b, and c.
• int a = 20, b = 30; // initialization
• byte B = 22; // Declaration initializes a byte type variable B.
Types of Variable
• A variable declared inside the class but outside the method, is called instance variable.
• Instance variables are declared in a class, but outside a method, constructor or any block.
• A slot for each instance variable value is created when a space is allocated for an object in
the heap.
• Instance variables are created when an object is created with the use of the keyword ‘new’
and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present throughout
the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
Instance Variable
• The instance variables are visible for all methods, constructors and block in the class. It is
recommended to make these variables as private. However, visibility for subclasses can
be given for these variables with the use of access modifiers.
• However, within static methods (when instance variables are given accessibility), they
• should be called using the fully qualified name. ObjectReference.VariableName.
Static Variable
• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• Only one copy of each class variable per class is created, regardless of how many objects
are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
• Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
• Visibility is same as instance variables.
• However, most static variables are declared public since they must be available for users
of the class.
Static Variable
class LearningVariables
{
static int x =10; //This is a static variable
int y = 15; // This is an instance variable
void method ( )
{
int z = 20; // This is a local variable
}
}
Example for local variable:
import java.io.*;
public class A
{
public void TeacherAge()
{
int age = 25; // local variable
System.out.println("a = " + age);
}
public static void main(String args[])
{
A obj = new A();
obj.TeacherAge();
}
}
Example for instance variable:
import java.io.*;
class Marks
{
int engMarks; //instance variable
}
class MarksDemo
{
public static void main(String args[])
{
Marks obj = new Marks();
obj.engMarks = 50;
System.out.println("Marks = " + obj.engMarks);
}
}
Example for static variable:
import java.io.*;
class Emp
{
public static double salary; //static variable
public static String name = "Tuhin";
}
public class EmpDemo
{
public static void main(String args[])
{
Emp.salary = 1000;
System.out.println(Emp.name);
System.out.println(Emp.salary);
}
}
ARRAYS
• Array is a collection of similar type of elements that have contiguous memory location.
• In Java all arrays are dynamically allocated.
• Since arrays are objects in Java, we can find their length using member length.
• A Java array variable can also be declared like other variables with [] after the data type.
• The variables in the array are ordered and each have an index beginning from 0.
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
Advantage of Java Array
• Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
• Random access: We can get any data located at any index position.
Syntax:
• type var-name[ ];
• Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array.
• These are also known as Jagged Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per dimension.
Syntax:
type var-name[ ][ ]=new type[row-size ][col-size ];
Multidimensional Arrays
• Java String class provides a lot of methods to perform operations on string such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
• +
• The CharSequence interface is used to represent sequence of characters.
• It is implemented by String, StringBuffer and StringBuilder classes.
• It means can create string in java by using these 3 classes.
• The java.lang.String class provides many useful methods to perform operations on sequence of char values.
The following program is an example for String concat function:
class string_method
{
public static void main(String args[]) Output:
{ Java Programming
String s=”Java”;
s=s.concat(“ Programming”);
System.out.println(s);
}
}
CONTROL STATEMENT
• Control statements decide the flow (order or sequence of execution of statements) of a
Java program.
• In Java, statements are parsed from top to bottom.
• Therefore, using the control flow statements can interrupt a particular section of a
program based on a certain condition.one or more clauses.
Conditional / Selection Statements
1) Simple if
2) if-else
3) if-else-if ladder
4) switch
1. Simple if
Syntax :
Example:
if(condition)
public class Student
{
{
statement 1; //executes when condition is true
public static void main(String[] args)
{
}
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2. if-else
Syntax: Example:
if(condition) public class Student
{ {
statement 1; //executes when condition is true public static void main(String[] args)
} {
else int x = 10;
{ int y = 12;
statement 2; //executes when condition is false if(x+y < 10)
} {
System.out.println("x + y is less than10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
3. if-else–if ladder
The if-else-if ladder statement executes one condition from multiple statements.
Example:
public class Student
{
public static void main(String[] args)
Syntax of if-else-if : {
if(condition 1) String city = "Delhi";
if(city == "Meerut")
{
{
statement 1; //executes when condition 1 is true System.out.println("city is meerut");
} }
else if(condition 2) else if (city == "Noida")
{ {
statement 2; //executes when condition 2 is true System.out.println("city is noida");
}
} else if(city == "Agra")
else {
{ System.out.println("city is agra");
statement 2; //executes when all the conditions are false }
else
} {
System.out.println(city);
}
}
}
Output:
Delhi
4. Nested if-statement
Syntax:
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when condition 2 is false
}
Example:
public class JavaNestedIfExample2
{
public static void main(String[] args)
{
int age=25; Output:
int weight=48; You are not eligible to donate blood
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
else
{
System.out.println("You are not eligible to donate blood");
}
}
else
{
System.out.println("Age must be greater than 18");
}
}
5. Java Switch Statement
• The Java switch statement executes one statement from multiple conditions.
• It is like if-else-if ladder statement.
• The switch statement works with byte, short, int, long, enum types, String and some
wrapper types like Byte, Short, Int, and Long.
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only.
• The case value must be literal or constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• Each case statement can have a break statement which is optional.
• When control reaches to the break statement, it jumps the control after the switch
expression. If a break statement is not found, it executes the next case.
• The case value can have a default label which is optional.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example:
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: System.out.println("10"); Output:
break; 20
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Loop / Iterative Statement
1. For loop
2. While loop
3. Do-while loop
1. for loop
For loop can initialize the variable, check condition and increment/decrement value. It consists
of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we
can initialize the variable, or we can use an already initialized variable. It is an optional
condition.
2. Condition: It is the second condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return boolean value either true
or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement)
{
//statements (For Body)
}
// Java Program to demonstrate the example of
Output
for loop which prints table of 1 1
public class ForExample 2
{ 3
public static void main(String[] args) 4
5
{
6
for(int i=1;i<=10;i++) 7
{ 8
System.out.println(i); 9
} 10
}
}
Nested for loop
• a for loop inside the another loop, it is known as nested for loop.
• The inner loop executes completely whenever outer loop executes.
public class PyramidExample
{ Output
public static void main(String[] args)
{ *
for(int i=1;i<=5;i++) **
{ ***
for(int j=1;j<=i;j++) ****
*****
{
System.out.print("* ");
}
System.out.println(); //new line
}
}
}
2. while loop
The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false,
the loop automatically stops.
Note: important thing about while loop is that, sometimes it may not even execute. If
the condition to be tested results into false, the loop body is skipped and first
statement after the while loop will be executed.
Syntax:
while (condition)
{
//code to be executed
increment / decrement statement
}
Example:
public class WhileExample Output
{ 1
public static void main(String[] args) 2
{
3
int i=1;
while(i<=10) 4
{ 5
System.out.println(i); 6
i++; 7
}
8
}
} 9
10
3. do while loop
The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition
is true.
Note: If the number of iteration is not fixed and have to execute the loop at least once, it is
recommended to use a do-while loop.
The different parts of do-while loop:
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and
control goes to update expression. As soon as the condition becomes false, loop breaks automatically.
Example:
i <=100
2. Update expression: Every time the loop body is executed, the this expression increments or
decrements loop variable.
Example:
i++;
Syntax do while loop: Example:
do public class DowhileExample Output:
{ { 1
//code to be executed / loop body public static voidW main(String[] args) 2
{ 3
//update statement int i=1; 4
}while (condition); do 5
{ 6
System.out.println(i); 7
i++; 8
}while(i<=10); 9
} 10
}
Flow control / Jump Statement
Jumping statements are control statements that transfer execution control from one point to another point in the
program.
There are two Jump statements that are provided in the Java programming language:
1. Break statement.
2. Continue statement.
1. Break statement
Using Break Statement to exit a loop:
• In java, the break statement is used to terminate the execution of the nearest looping statement or switch
statement.
• The break statement is widely used with the switch statement, for loop, while loop, do-while loop.
Syntax:
break;
1. break
Example:
import java.io.*;
class GFG
{ Output
public static void main(String[] args)
{ 0
int n = 10; 1
for (int i = 0; i < n; i++)
{ 2
if (i == 6) 3
break;
System.out.println(i); 4
} 5
}
}
Use Break as a form of goto
class GFG
{
public static void main(String[] args)
• Java does not have a goto {
statement because it produces an for (int i = 0; i < 3; i++)
unstructured way to alter the flow {
of program execution. one : { // label one Output:
two : { // label two
• Java illustrates an extended form three : { // label three i=0
of the break statement. This form System.out.println("i=" + i); after label one
of break works with the label. if (i == 0) i=1
break one; // break to label one after label two
• The label is the name of a label if (i == 1)
that identifies a statement or a break two; // break to label two after label one
block of code. if (i == 2) i=2
break three; // break to label three after label three
} after label two
Syntax: System.out.println("after label three");
} after label one
break label; System.out.println("after label two");
}
System.out.println("after label one");
}
}
}
2. continue
Example:
import java.io.*;
The continue statement pushes the class GFG
next repetition of the loop to take
place, hopping any code between {
Output:
itself and the conditional public static void main(String[] args)
0
expression that controls the loop. {
1
for (int i = 0; i < 10; i++)
2
{
3
if (i == 6)
4
{
5
System.out.println();
7
continue;
8
}
9
System.out.println(i);
}
}
}