0% found this document useful (0 votes)
7 views333 pages

Java

The document provides a comprehensive overview of Java programming concepts, including basic Java syntax, command line execution, memory management, garbage collection, and the Object class. It explains the structure of Java programs, the role of the JVM, and how to handle objects and memory in Java. Additionally, it covers the use of methods like hashCode() and equals() for object comparison and memory management practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views333 pages

Java

The document provides a comprehensive overview of Java programming concepts, including basic Java syntax, command line execution, memory management, garbage collection, and the Object class. It explains the structure of Java programs, the role of the JVM, and how to handle objects and memory in Java. Additionally, it covers the use of methods like hashCode() and equals() for object comparison and memory management practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Hitesh Vasant Manjare

(software developer)
Basic example

Example :

[Link]

package [Link];

public class BasicExample


{
public static void main(String[] args)
{
[Link]("Hello World");
}
}

Output :

Hello World

Questions :

1) Explain public static void main(String[] args) ?



public Access modifier
static keyword
void Return type
main method
String[] args Command line argument

2) Explain [Link]("Hello World");



System class
out object
println method
Run program by cmd

Step 1 : write java code in .txt file

Step 2 : open cmd and set path to jdk

command set path=C:\Program Files\Java\jdk1.8.0_281\bin

Step 3 : change path to where java file is stored

command cd /d C:\Users\hites\OneDrive\Desktop

Step 4 : compile java code

command javac [Link]

Step 5 : run java code

command java BasicExample


Command line arguments

Eclipse IDE

Example :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
[Link]("At position 1 : " + args[1]);
[Link]("--------------------------- ");

for (String s : args)


{
[Link]("arguments is : " + s);
}
}
}

Right click on projectName > Run as > Run configurations > Arguments

Output :

At position 1 : panduranga
---------------------------
arguments is : vithal
arguments is : panduranga
arguments is : swami
cmd

Example :

compile java code

command javac [Link]

run java code

command java Test bruceLee JackieChan JetLi

Output :
Write multiple class in single class

Example :

[Link]

package [Link];

public class Test // this must be public


{
public static void main(String[] args)
{
[Link]("Test is public class");

A a = new A();
a.m1();
B b = new B();
b.m2();
}
}

class A // this must be default


{
public void m1()
{
[Link]("A is default class");
}
}

class B // this must be default


{
public void m2()
{
[Link]("B is default class");
}
}

Output :

Test is public class


A is default class
B is default class
Java internal working

1) Source code :
- Human readable code

2) Compiler :
- Compiler finds any syntax error in the code
- It converts .java file to .class file

3) Bytecode :
- Not readable humans

4) JVM :
- Java virtual machine
- Converts bytecode to machine code

5) Machine code :
- Code readable by operating systems
JVM memory

1) method area :
- cretaed when jvm started
- stores static data and variables

2) Heap memory :
- cretaed when jvm started
- stores objects, instance variables, and arrays
- memory free done automatically by garbage collecor

3) Stack memory :
- created when new thread started
- stores local variables, and currrent methods
- It has LIFO structure
- Memory free done automatically

4) PC registers :
- Holds address of new executing instruction

5) Native method stacks :


- Methods of other languages like c, c++ stored here
Garbage collection

- Garbage collector removes unwanted objects from heap memory


- It is done automatically by jvm
- When jvm started it creates 3 threads as below,
1) Main thread
2) Thread scheduler
3) Garbage collector

Question :

1) How can be object unreferenced in java ?



There are 3 ways to do that,

a) By nulling te reference
e.g. s1=null;
making object null

b) By assigning a reference to another


e.g. s2=s3;
s2 object becomes unreferenced and pointing to object s3

c) By anonymous object
e.g. new student(4,”vithal”);
created object but not stored its reference value

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Student s1 = new Student(1, "ram");
Student s2 = new Student(2, "krishna");
Student s3 = new Student(3, "hari");

s1 = null; // making object null


s2 = s3; // object s2 becomes unreferenced and pointing to s3 object
new Student(4, "vithal"); // created object but not stored its refrence value
}
}
[Link]

package [Link];

public class Student


{
private int rollno;
private String name;

Student(int r, String n)
{
[Link]=r;
[Link]=n;
}

public void display()


{
[Link]("Roll no : "+rollno+ ", name : "+name);
}
}

Output :
Finalize method

- Garbage collectors gc() method first internally calls finalize() method


before garbaging object
- Finalize method closes all connections of objects so that it will not
affect further
- Real world example :
After passing exam before giving books to other people or raddiwala
We first check that book if it contains any of our secret data like hall
ticket or id card in it.
- So basicallly we are closing connection before removing that object

Syntax :

[Link]

[Link](); //garbage collector method

protected void finalize() //finalize method


{
//closing open connections
[Link](); //closing database connection
[Link](); //closing file connection
}

Question :

1) Where finalize() method is located ?



In [Link]

2) Is finalize() method is deprecated ?



Yes
Object class

- object class is the topmost parent class in java


- all other classes extends directly or indirectly object class only

Classes under [Link] :

methods of [Link] :
hashcode() method from [Link]

- hashcode() method generates unique number for each object for storing
in memory

Example 1 :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
[Link]("hashcode for s1 is : " + [Link]());
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}
}

Output :

hashcode for s1 is : 1651191114


Example 2 :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(101, "ram");

[Link]("hashcode for s1 is : " + [Link]());


[Link]("hashcode for s2 is : " + [Link]());
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}
}

Output :

hashcode for s1 is : 1651191114


hashcode for s2 is : 1579572132
Example 3 :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(102, "ram");

[Link]("hashcode for s1 is : " + [Link]());


[Link]("hashcode for s2 is : " + [Link]());
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}
}

Output :

hashcode for s1 is : 1651191114


hashcode for s2 is : 1579572132
Example 4 :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(102, "krishna");

[Link]("hashcode for s1 is : " + [Link]());


[Link]("hashcode for s2 is : " + [Link]());
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}
}

Output :

hashcode for s1 is : 1651191114


hashcode for s2 is : 1579572132
Example 5 : (overriding hashCode() method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(102, "krishna");

[Link]("hashcode for s1 is : " + [Link]());


[Link]("hashcode for s2 is : " + [Link]());
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}

@Override
public int hashCode()
{
return 123;
}

Output :

hashcode for s1 is : 123


hashcode for s2 is : 123
Example 6 : (overriding hashCode() method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(102, "krishna");

[Link]("hashcode for s1 is : " + [Link]());


[Link]("hashcode for s2 is : " + [Link]());
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}

@Override
public int hashCode()
{
return rollNum;
}

Output :

hashcode for s1 is : 101


hashcode for s2 is : 102
hashcode() method from [Link]

- [Link] overrided hashCode() method from [Link] only

Example 1 :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
String str1 = "bruce";
String str2 = "jackie";

[Link]("hashcode for str1 is : " + [Link]());


[Link]("hashcode for str2 is : " + [Link]());
}
}

Output :

hashcode for str1 is : 94016839


hashcode for str2 is : -1167640261
Example 2 : (Strings which retruns same hashcode numbers)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
String str1 = "FB";
String str2 = "Ea";

[Link]("hashcode for str1 is : " + [Link]());


[Link]("hashcode for str2 is : " + [Link]());
}
}

Output :

hashcode for str1 is : 2236


hashcode for str2 is : 2236

Note : same hashcode generation is done in [Link] only otherwise it creates


unique hashcode numbers
equals() method from [Link]

Example 1 : (== operator)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(101, "ram");
[Link](s1 == s2);
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}
}

Output :

false

Explaination :

- Both s1 and s2 belongs to different objects in heap memory


Example 2 : (== operator)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = s1;
[Link](s1 == s2);
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}
}

Output :

true

Explaination :

- Both s1 and s2 belongs to same objects in heap memory


Example 3 : (equals method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(101, "ram");

[Link]([Link](s2));
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}
}

Output :

false
Example 4 : (equals method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = s1;

[Link]([Link](s2));
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}
}

Output :

true

Question :

1) Why ==operator and equals() method output is same ?



Because equals() method of [Link] does == operation only
Example 5 : (equals method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(101, "ram");
Student s3 = new Student(101, "krishna");
Student s4 = new Student(102, "ram");

[Link]("[Link](s2) : "+ [Link](s2));


[Link]("[Link](s3) : "+ [Link](s3));
[Link]("[Link](s4) : "+ [Link](s4));
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}
}

Output :

[Link](s2) : false
[Link](s3) : false
[Link](s4) : false
Example 6 : (overriding equals method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(101, "ram");
Student s3 = new Student(101, "krishna");
Student s4 = new Student(102, "ram");

[Link]("[Link](s2) : "+ [Link](s2));


[Link]("[Link](s3) : "+ [Link](s3));
[Link]("[Link](s4) : "+ [Link](s4));
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}

@Override
public boolean equals(Object obj)
{
return true;
}
}

Output :

[Link](s2) : true
[Link](s3) : true
[Link](s4) : true
Example 7 : (overriding equals method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, "ram");
Student s2 = new Student(101, "ram");
Student s3 = new Student(101, "krishna");
Student s4 = new Student(102, "ram");

[Link]("[Link](s2) : "+ [Link](s2));


[Link]("[Link](s3) : "+ [Link](s3));
[Link]("[Link](s4) : "+ [Link](s4));
}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}

@Override
public boolean equals(Object obj)
{
Student student = (Student) obj;

if ([Link] != [Link])
{
return false;
}
return true;
}
}

Output :

[Link](s2) : true
[Link](s3) : true
[Link](s4) : false
Example 8 : (overriding equals method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101, null);
Student s2 = new Student(101, "ram");

Test t= new Test();

[Link]("[Link](t) : "+ [Link](t));

}
}

[Link]

package [Link];

public class Student


{
private int rollNum;
private String name;

public Student(int rollNum, String name)


{
[Link] = rollNum;
[Link] = name;
}

@Override
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if ([Link]() != [Link]())
{
return false;
}
Student student = (Student) obj;
if ([Link] != [Link])
{
return false;
}
if ([Link] == null)
{
if ([Link] != null)
{
return false;
}
}
if (![Link]([Link])) // equals() of [Link]
{
return false;
}
return true;
}
}

Output :
[Link](t) : false
equals() method from [Link]

- [Link] overrided equals() method from [Link] only

Example 1 : (equals method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
String str1="hitesh";
String str2="man";

[Link]("[Link](str2) : "+ [Link](str2));

}
}

Output :
[Link](t) : false

Example 2 : (equals method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
String str1="hitesh";
String str2="hitesh";

[Link]("[Link](str2) : "+ [Link](str2));

}
}

Output :
[Link](t) : true

Note :

- equals() method of [Link] works differently than as in [Link]

- [Link] internally checks reference is same or not i.e. (s1=s2)

- String class checks content is same or not i.e. (hitesh=hitesh)


Data types

Primitive data types

Data types range size example

boolean true/false boolean b = true;


char 0 to 65535 16 bits Char c = ‘A’
byte -128 to 127 8 bits byte a = 100;
short -32,768 to 32767 16 bits short s = 1000;
int -2,147,483,648 to 32 bits int i = 1000;
2,147,483, 647
long - 64 bits long l = 100L;
9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
float -3,4e38 to 3.4e38 32 bits float f = 234.5f;
double -1.7e308 to 1.7e308 32 bits double d = 234.5;

Non-Primitive data types

Data types range

String String str= “hello”;


array DataType[] arr = new DataType[arraySize];
class Public class Test { }
interface Public interface Test { }
variables

Example :

int a = 10; //a is variable here

Local variable

- Declared inside methods, constuctor, blocks

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Test v = new Test();
[Link]();
}

public void display()


{
int a = 10; // local variable
int b = 20; // local variable
int c = a + b;
[Link]("sum is : " + c);
}
}

Output :
sum is : 30
Instance variable

- Declared inside class but outside methods, constuctor, blocks

Example :

[Link]

package [Link];

public class Test


{
public String name; // instance variable
private double salary; // instance variable

public static void main(String args[])


{
Test empOne = new Test("Hitesh");
[Link](1000);
[Link]();
}

public Test (String empName)


{
name = empName;
}

public void setSalary(double empSal)


{
salary = empSal;
}

public void printEmp()


{
[Link]("name : " + name);
[Link]("salary :" + salary);
}
}

Output :
name : Hitesh
salary :1000.0
Static / class variable

- Declared inside class but outside methods, constuctor, blocks

- uses static keyword to declare

Example :

[Link]

package [Link];

public class Test


{
private static double salary; // static variable
public static final String DEPARTMENT = "IT";// static variable

public static void main(String args[])


{
salary = 1000;
[Link](DEPARTMENT + "average salary:" + salary);
}
}

Output :
ITaverage salary:1000.0
Question :

1) Instance vs static variable ?



- Static variables, methods can be called using clasname also.
- So no need to create an object.

Example :

[Link]

package [Link];

public class Test


{
int a;
static int b = 30;

public static void main(String args[])


{
Test obj = new Test();

[Link]("instance variable using object : " + obj.a);

[Link]("static variable using object : " + obj.b);


[Link]("static variable using classname : " + Test.b);
}
}

Output :
Value of instance variable using object : 0
Value of static variable using object : 30
Value of static variable using classname : 30
- Static variables initializes values once only.
- But instance variables initializes value again and again.

Example :

[Link]

package [Link];

public class Test


{
int a = 0;
static int b = 0;

public static void main(String args[])


{
Test obj1 = new Test();
obj1.a++;

[Link]("instance variable after increment : " + obj1.a);

Test obj2 = new Test();


obj2.a++;
[Link]("instance variable after increment : " + obj2.a);

obj1.b++;
[Link]("static variable after increment : " + obj1.b);

obj2.b++;
[Link]("static variable after increment : " + obj2.b);
}
}

Output :
instance variable after increment : 1
instance variable after increment : 1
static variable after increment : 1
static variable after increment : 2
modifier

Access modifiers

Access modifiers
Access modifier Description
Description

Default - No modifier name


- Accessible within same package
Public - Accessible to all
Private - Accessible to class only
Protected - Accessible to subclass even in
different packages
(only if it is inherited)

Access Subclass Subclass


class package world
modifiers Same package diff package

Default yes yes yes no no


public yes yes yes yes yes
private yes no no no no
protected yes yes yes yes no

Note :

- Class and interface can not be private or protected.


They are public or default only.
- Methods, variables, constructors can be private, protected, public, default.

Non-Access modifiers

1) Static : keyword of class level


2) final : keyword to avoid access
3) abstract : keyword used to achieve abstraction
4) synchronized : used in multithreading for concurrency output
5) volatile : modifies variable value of threads
6) transient : used in serialization to avoid serialization of specific
variables
Call private methods

Example : (using public method)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Sample t = new Sample();
[Link]();
}
}

[Link]

package [Link];

public class Sample


{
public void show()
{
display();
}

private void display()


{
[Link]("private method of Sample class");
}
}

Output :
private method of Sample class
Example : (using reflection API)

[Link]

package [Link];
import [Link];

public class Test


{
public static void main(String[] args)throws Exception
{
Class cls = [Link]("[Link]");
Sample sample = (Sample) [Link]();
Method mt = [Link]("display", null);
[Link](true);
[Link](sample, null);
}
}

[Link]

package [Link];

public class Sample


{
private void display()
{
[Link]("private method of Sample class");
}
}

Output :
private method of Sample class
loops

while loop

Syntax :

while(condition)
{
//code
}

Example :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int i = 4;

while (i <= 5)
{
[Link](i);
i++;
}
}
}

Output :
4
5

Example : (while true)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
while (true)
{
[Link]("vithal panduranga");
}
}
}

Output :
vithal panduranga
vithal panduranga
.
.
.
.
do while loop

- same as while loop but executes at least once before testing condition in while loop

Syntax :

do
{
//code
}
while(condition)

Example :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int i = 2;
do
{
[Link](i);
i++;
} while (i >= 5);
}
}

Output :

2 //executed once even though condition not matches

Example : (while true)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
do
{
[Link]("vithal pandurang");
} while (true);
}
}

Output :
vithal panduranga
vithal panduranga
.
.
.
.
.
for loop

Syntax :

for(initialization; condition; updateValue)


{
//code
}

Example :

[Link]

public class Test


{
public static void main(String[] args)
{
for (int i = 1; i <= 3; i++)
{
[Link](i);
}
}
}

Output :
1
2
3

for each loop

Syntax :

for(declaration; listObjects)
{
//code
}

Example :

[Link]

public class Test


{
public static void main(String[] args)
{
int[] input = { 125, 132, 95};

for (int num : input)


{
[Link](num);
}
}
}

Output :
125
132
95
loop control

break

- helps in breaking the loop

Example :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int[] input = { 10, 20, 30, 40, 50 };

for (int x : input)


{
if (x == 30)
{
break;
}
[Link](x);
}
}
}

Output :
10
20
continue

- helps in breaking the statement and continues loop

Example :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int[] input = { 10, 20, 30, 40, 50 };

for (int x : input)


{
if (x == 30)
{
continue;
}
[Link](x);
}
}
}

Output :
10
20
40
50
lables

- If we have nested loops and we apply break/continue it will work on inner loop

- So if we want to apply break/continue on outer loops we can use label

- We can specify which loop to break/continue using label

- We can specify name of loop using labels which we want to break or continue

Syntax :

LabelName : any loop


{
inner loops/statements
{
break labelName;
Or
continue labelName;
}
}
Break label

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Task: for (int i = 1; i <= 4; i++)
{
[Link]("-------- Outer loop value : " + i);
for (int j = 1; j < 10; j++)
{
[Link]("Inner loop value : " + j);
if (j == 2)
{
[Link]("breaking outer loop");
break Task;
}
}
}
}
}

Output :
-------- Outer loop value : 1
Inner loop value : 1
Inner loop value : 2
breaking outer loop
continue label

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Task: for (int i = 1; i <= 4; i++)
{
[Link]("-------- Outer loop value : " + i);
for (int j = 1; j < 10; j++)
{
[Link]("Inner loop value : " + j);
if (j == 2)
{
[Link]("breaking outer loop");
continue Task;
}
}
}
}
}

Output :
-------- Outer loop value : 1
Inner loop value : 1
Inner loop value : 2
breaking outer loop
-------- Outer loop value : 2
Inner loop value : 1
Inner loop value : 2
breaking outer loop
-------- Outer loop value : 3
Inner loop value : 1
Inner loop value : 2
breaking outer loop
-------- Outer loop value : 4
Inner loop value : 1
Inner loop value : 2
breaking outer loop
statements

if

Syntax :

if(condition)
{
//code
}

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
int age = 20;
if (age > 18)
{
[Link]("Age is greater than 18");
}
}
}

Output :

Age is greater than 18


if else

Syntax :

if(condition)
{
//code
}
else
{
//code
}

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
int age = 16;
if (age >= 18)
{
[Link]("inside if loop");
} else
{
[Link]("inside else loop");
}

}
}

Output :

inside else loop


nested if else

Syntax :

if(condition)
{
//code
if(condition)
{
//code
}
else
{
//code
}
}

Example :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int age = 15;
if (age <= 18)
{
[Link]("inside if loop");
if (age == 15)
{
[Link]("age is 15");
}
} else
{
[Link]("inside else loop");
}
}
}

Output :
inside if loop
age is 15
ternary / conditional operator

Syntax :

exp1 ? exp2 : exp3;

if exp1 is true,then exp2 is the answer

if exp1 is false, then exp3 is the answer

Example :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int n1 = 5;
int n2 = 10;
int maxNum = (n1 > n2) ? n1 : n2;
[Link]("Maximum is = " + maxNum);
}
}

Output :

Maximum is = 10
Switch case

Syntax :

Switch(CaseValue)
{
Case value : //statements
break;
Case value : //statements
break;
default : //statements //optional
}

Example :
[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
char grade = 'D';
switch (grade)
{
case 'A':
[Link]("Excellent!");
break;
case 'B':
case 'C':
[Link]("Well done");
break;
case 'D':
[Link]("You passed");
case 'F':
[Link]("Better try again");
break;
default:
[Link]("Invalid grade");
}
}
}

Output :
You passed //as D has no break statement it goes to F
Better try again
Increment / decrement operators

Example : (post-increment)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int i = 1;
i++;
[Link](" i : " + i);
}
}

Output :
i : 2

Example : (pre-increment)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int i = 1;
++i;
[Link](" i : " + i);
}
}

Output :
i : 2
Example : (post-decrement)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int i = 1;
i--;
[Link](" i : " + i);
}
}

Output :
i : 0

Example : (pre-decrement)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
int i = 1;
--i;
[Link](" i : " + i);
}
}

Output :
i : 0
Enumeration

- Enumeration created using enum keyword


- enum is a data type
- It contains fixed set of constants
- E.g. days {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
directions {NORTH, SOUTH, EAST, WEST}
colors {RED, YELLOW, BLUE, GREEN, WHITE, BLACK}
- According to java, these constants must be written in capital letters
- These constants are static and final implicitly (i.e. already static and final) So
we cant change their value
- It can have constructors, methods, and instance variables

Example :

[Link]

package [Link];

public class Test


{
public enum Days
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public static void main(String[] args)


{
for (Days s : [Link]())
{
[Link](s);
}
}
}

Output :
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
STRING
String

- String objects are stored in Heap memory


- Because String is a class and java treated String as an objects
- We can create String objects in two ways,

String literals

- e.g. String str = “Hitesh”;


- String literals are stored in String constant pool inside heap memory
- String constant pool is a cache stored inside heap memory
- till java 1.6 String constant pool was in method area of jvm (PEMGEN SPACE)
but its size was fix there so memory issue was there
- from java 1.7 its stored in heap area of jvm so size issue sorted
- When we create new object its value stored in pool
- only 1 object is created inside String constant pool and no object creation inside
heap

If same value is present for another object then it refers to previous value in pool
i.e. String str1 = “Hello”;
String str2 = “Hello”;
Here, as object str1 & str2 both having same value.
Both will refer same value in String constant pool

This helps in saving memory


new keyword

- e.g. String str = new String(“Hitesh”);


- String with new keyword are stored normally in heap memory and object str
refering to it
- String(“Hitesh”);
Will store String inside String constant pool but that object str is not refering
to it.
Instead jvm internally creates reference for it so that it may use in future.
This is extra object created
- here total 2 objects created in memory ([Link] in heap and another in String
constant pool)

- If same value is present for another object then it refers to previous in String
constant pool but create new object in heap memory
- i.e. String str1 = new String(“Hello”);
String str2 = new String(“Hello”);

Here, as object str1 & str2 both having same value.


Both will refers to previous object in String constant pool but create new object in
heap memory
Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
// String created using 'new' keyword
String s1 = new String("TAT");
String s2 = new String("TAT");

// String created using String literal


String s3 = "TAT";
String s4 = "TAT";
String s5 = new String("CAT");
String s6 = "BAT";
[Link](s1);
[Link](s2);
[Link](s3);
[Link](s4);
[Link](s5);
[Link](s6);
}
}

Output :
TAT
TAT
TAT
TAT
CAT
BAT

Explanation :

1) String s1 = new String("TAT");


- TAT is created in heap memory and object s1 pointing to it
- TAT is also created in String constant pool and JVM internally pointing to it
2) String s2 = new String("TAT");
- TAT is created in heap memory and object s2 pointing to it
- TAT is already present in String constant pool so another not created

3) String s3 = "TAT";
- TAT is already present in String constant pool so another not created and jvm internally
pointer gets replaced with object S3

4) String s4 = "TAT";
- TAT is already present in String constant pool so another not created and object S4 is
pointing to it
5) String s5 = new String("CAT");
- CAT is created in heap memory and object s5 pointing to it
- CAT is also created in String constant pool and JVM internally pointing to it

6) String s6 = "BAT";
- BAT is created in String constant pool and object S6 is pointing to it
Example : (Difference between string literal and new keyword)

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String str1 = "Sachin";
String str2 = new String("Sachin");
}
}

Explanation :

Here

str1 refers to String constant pool (helps in saving memory as duplicate values can stored
as single value)

Str2 refers to heap memory


immutable

- Immutable means which can not be changed / updated But new object is created

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s = "Sachin";
[Link](" Tendulkar");

[Link](s);
}
}

Output :
Sachin

Explanation :

1) String s = "Sachin";

- Sachin is created in string constant pool


- Object s is refering to it
2) [Link](" Tendulkar");

- Sachin Tendulkar is created separately in string constant pool


- But object s is stiil refering to Sachin only

- As object s is still refering to previous value sachin so it is immutable


- It means two objects created but object s refers to Sachin only

Example : (solution to immutable)

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s = "Sachin";
s = [Link](" Tendulkar");

[Link](s);
}
}

Output :
Sachin Tendulkar
Explanation :

1) String s = "Sachin";

- Sachin is created in string constant pool


- Object s is refering to it

2) [Link](" Tendulkar");

- Sachin Tendulkar is created separately in string constant pool


- But object s is stiil refering to Sachin only

3) s=[Link](" Tendulkar");
- object s is refering to Sachin Tendulkar now
Question :

1) Why String is immutable ?



We can understand its reason by below example,
[Link]

public class Test


{
public static void main(String args[])
{
String str1 = "Sachin";
String str2 = "Sachin";
}
}

Here, both str1 and str2 refers to same object in String constant pool
So memory is saved

Now we willl try to modify string value in below example,

[Link]

public class Test


{
public static void main(String args[])
{
String str1 = "Sachin";
String str2 = "Sachin";

[Link]("Dhoni");
}
}
Here, both str1 and str2 refers to same object in String constant pool
When str2 tries to concat its value as to Dhoni
Then value gets stored in memory but its not getting refferd so removed by garbage collector

Other reasons are given as below,

a) Security :
We use Strings for database connections, usernames/paswords
So if Strings were mutable these things ould be easily changed

b) synchronization & concurrency :


making String immutable automatically makes them thread safe
so solves synchronization issues

c) caching :
If two variables have same value then it creates only one object and both of them refer
to that same object
i.e. String a =”test”;
String b =”test”;
Here, Only one object will create in SCP for both variables a & b

d) class loading :
In java String is used as argument while class loading
i.e. public static void main(String args[])
so if String was mutable then it could load wrong class
string methods

charAt()

- Returns character of specific position

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String str = "Welcome to Java";
char ch = [Link](6);// returns the char value at the 6th index
[Link]("position 6 -> " + ch);

[Link]("--------------------------");

for (int i = 0; i < [Link](); i++)


{
[Link]("Char at " + i + " place " + [Link](i));
}
}
}

Output :
position 6 -> e
--------------------------
Char at 0 place W
Char at 1 place e
Char at 2 place l
Char at 3 place c
Char at 4 place o
Char at 5 place m
Char at 6 place e
Char at 7 place
Char at 8 place t
Char at 9 place o
Char at 10 place
Char at 11 place J
Char at 12 place a
Char at 13 place v
Char at 14 place a
toCharArray()

- converts String to array of characters

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = "Welcome to Java";

char[] ch = [Link]();

for (int i = 0; i < [Link]; i++)


{
[Link](ch[i]);
}
}
}

Output :
W
e
l
c
o
m
e

t
o

J
a
v
a
concat()

- It concats multiple strings

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String str1 = "Hello";
String str2 = "Javatpoint";
String str3 = "Reader";

str1=[Link]("world");

//Concatenating Space among strings


String str4 = [Link](" ").concat(str2).concat(" ").concat(str3);
[Link](str4);

//Concatenating Special Chars


String str5 = [Link]("!!!");
[Link](str5);

String str6 = [Link]("@").concat(str2);


[Link](str6);
}
}

Output :
Helloworld Javatpoint Reader
Helloworld!!!
Helloworld@Javatpoint
contains()

- checks if string contains another specified string

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String str = "what do you know about me";

// checks string str contains below strings or not


[Link]([Link]("do you know"));
[Link]([Link]("about"));
[Link]([Link]("ABOUT")); // it is case sensitive
[Link]([Link]("hello"));

if ([Link]("know"))
{
[Link]("This string contains know");
} else
{
[Link]("Result not found");
}
}
}

Output :
true
true
false
false
This string contains know
startsWith()

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String str = "java is coding";
if ([Link]("java"))
{
[Link]("starts with java");
} else
{
[Link]("Result not found");
}
if ([Link]("v", 2))
{
[Link]("starts with 'v' at position 2");
} else
{
[Link]("Result not found");
}
}
}

Output :
starts with java
starts with 'v' at position 2
endsWith()

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String str = "java is coding";
if ([Link]("java"))
{
[Link]("ends with coding");
} else
{
[Link]("Result not found");
}
if ([Link]("g"))
{
[Link]("ends with 'g'");
} else
{
[Link]("Result not found");
}
}
}

Output :
Result not found
ends with 'g'
equals()

Example :

[Link]

public class Test


{
public static void main(String args[])
{
String s1 = "java";
String s2 = "java";
String s3 = "JAVA";
[Link]([Link](s2)); // True because content is same
if ([Link](s3)) // equals is case sensitive
{
[Link]("both strings are equal");
} else
[Link]("both strings are unequal");
}
}

Output :
true
both strings are unequal

==

Example :

[Link]

public class Test


{
public static void main(String args[])
{
String s1 = "java";
String s2 = "java";
String s3 = "JAVA";
[Link](s1 == s2); // True because content is same in String constant pool
if (s1 == s3) // == is case sensitive
{
[Link]("both strings are equal");
} else
[Link]("both strings are unequal");
}
}

Output :
true
both strings are unequal
equals() vs ==

- equals() compares values


- == compares objects
- They will produce same result for String literals as shown in above examples.
Because String literals refers same object for duplicate values But == will give
false result if we create String using new keyword as shown in below example.

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
if (s1 == s2)
{
[Link]("result true for ==");
} else
{
[Link]("result false for ==");
}
if ([Link](s2))
{
[Link]("result true for equals");
} else
{
[Link]("result false for equals");
}
}
}

Output :
result false for ==
result true for equals
equalsIgnoreCase()

Example :
[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = new String("hello");
String s2 = new String("HELLO");
if ([Link](s2)) // not case sensitive
{
[Link]("result true");
} else
{
[Link]("result false");
}
}
}

Output :
result true

indexOf()

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = "this index is my example";
int i = [Link]("example");// returns the index of "example"
[Link]("position of 'example' -> " + i);
int j = [Link]("is", 4);
// returns the index of “is” substring after 4th index
[Link]("position of 'is' after 4th position -> " + j); //
second "is"
}
}

Output :

position of 'example' -> 17


position of 'is' after 4th position -> 11
lastIndexOf()

Example :

[Link]

public class Test


{
public static void main(String args[])
{
String str = "This is last index of example";

int i = [Link]('s');// s from "last"


[Link](i);

int k = [Link]('s', 5);// s from "This"


[Link](k);

int j = [Link]("of");
[Link](j);

int index = [Link]("of", 25);


// as of is at position 19 so we can mention any number > 19 here
[Link](index);

index = [Link]("of", 10);


//it will result -1 as 10 is < 19
[Link](index);
}
}

Output :
10
3
19
19
-1
isEmpty()

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = "";
if ([Link]() == 0 || [Link]())// Either length is zero or isEmpty
is true
{
[Link]("String s1 is empty");
} else
{
[Link]("s1");
}
}
}

Output :
String s1 is empty

join()

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s = [Link]("/", "[Link]", "email", "inbox");
[Link](s);
String str = [Link]("--yo--", "hello", "java", "world");
[Link](str);
}
}

Output :
[Link]/email/inbox
hello--yo--java--yo--world
replace()

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = "javatpoint is a very good website";
String str = [Link]('a', 'e');
// replaces all occurrences of 'a' to 'e'
[Link](str);
String str1 = [Link]("is", "was");
//replaces all occurrences of "is" to "was"
[Link](str1);
}
}

Output :
jevetpoint is e very good website
javatpoint was a very good website
replaceAll()

- It is similar to replace() method


- But it not works with chars
- In addition it uses regex to replace also i.e. replaceAll(String regex,String replacement)

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = "javatpoint is a very good website";
String str = [Link]("a", "e");
// replaces all occurrences of 'a' to 'e'
[Link](str);
String str1 = [Link]("is", "was");
//replaces all occurrences of "is" to "was"
[Link](str1);
String str2 = [Link]("\\s", "");
//regex to replace white spaces
[Link](str2);
}
}

Output :
jevetpoint is e very good website
javatpoint was a very good website
javatpointisaverygoodwebsite
spilt()

- splits String and stores in array

Example 1 :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
String str = "Hello-world-java";
String[] arr = [Link]("-");
for (String s : arr)
{
[Link](s);
}
}
}

Output :
Hello
world
java

Example 2 :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
String str = "Hello world java";
String[] arr = [Link](" ");
for (String s : arr)
{
[Link](s);
}
}
}

Output :
Hello
world

java
Example 3 : (using \\s+ to not consider white spaces)

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
String str = "Hello world java";
String[] arr = [Link]("\\s+");
for (String s : arr)
{
[Link](s);
}
}
}

Output :
Hello
world
java

length()

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = "javatpoint";
String s2 = "python";
[Link]("length of javatpoint is: " + [Link]());
[Link]("length of python is: " + [Link]());
}
}

Output :
length of javatpoint is: 10
length of python is: 6
substring()

- reads String from specific position to specific postion

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = "java is coding";

String substr = [Link](0); // Starts with 0 and goes to end


[Link](substr);

String substr1 = [Link](2); // Starts with 1 and goes to end


[Link](substr1);

String substr2 = [Link](5, 10); // Starts from 5 and goes to 10


[Link](substr2);
}
}

Output :

- java
helps is
in removing
coding leading and trailing spaces
va is coding
is co

trim()

Example :

[Link]

package [Link];
public class Test
{
public static void main(String args[])
{
String s1 = " hello string ";
[Link]("---" + s1 + "---");// without trim()
[Link]("---" + [Link]() + "---");// with trim()
}
}

Output

--- hello string ---


---hello string---
toLowerCase()

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = "JAVATPOINT HELLO stRIng";
String s1lower = [Link](); // converts to lower case
[Link](s1lower);
}
}

Output :
javatpoint hello string

toUpperCase()

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String s1 = "hello string";
String s1upper = [Link]();
[Link](s1upper);
}
}

Output :
HELLO STRING
StringBuffer

- It is mutable
- Methods are synchronized

Example :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
StringBuffer obj = new StringBuffer("hello");
[Link](" java");
[Link](obj);
}
}

Output :
hello java
StringBuilder

- It is mutable

Example :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
StringBuilder obj = new StringBuilder("hello");
[Link](" java");
[Link](obj);
}
}

Output :
hello java
Question :

1) Difference between String vs StringBuffer vs StringBuilder?


Sr String StringBuffer StringBuilder


no.
1. Creates immutable objects Creates mutable objects Creates mutable objects
2. Not thread safe thread safe Not thread safe
3. Slow performance Fast performance More fast performance
4. If data is not changing If data is changing If data is changing
frequently then use String frequently then use frequently then use
StringBuffer StringBuilder
[Link] app [Link] app
5. If we assign same values to If we assign same values If we assign same values
multiple objects then it to multiple objects then to multiple objects then
requires less memory As it it requires more memory it requires more memory
uses String constant pool
for storage
i.e.
String s1=”hello”;
String s2=”hello”;
ARRAY
Array

- superclass of Array is Object class


- Stores data in heap memory
- Stores multiple values in single variable
- We can only store same type of variable i.e. int only or String only

Declaration :

types meaning
int[] a; a is array
int[] a,b; a and b both are array
int []a; a is array
int []a,b; a and b both are array
int a[]; a is array
int a[],b; a is array and b is variable
int[]a; a is array

creation :

1) int[] a;
a=new int [3];

2) int[] a=new int [3];

initialization :
Declaration, creation, initialization :

1) int[] a= {10,20,30};
2) int[] a= new int [ ] {10,20,30};

Syntax :

DataType [ ] arr = new DataType [ araySize ];


arr [ 5 ] = 6; //stored value 6 at location 5 of array

Example 1 :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
int[] arr = new int[10];
arr[5] = 6;
arr[2] = 86;
[Link]("value at index 5 is : " + arr[5]);
for (int i : arr)
{
[Link](" " + i);
}
[Link](" ");
for (int i = 0; i < [Link]; i++)
{
[Link](" " + arr[i]);
}
}
}

Output :

value at index 5 is : 6
0 0 86 0 0 6 0 0 0 0
\\\\
0 0 86 0 0 6 0 0 0 0
Example 2 :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
String[] arr1 =
{ "RAM", "KRISHNA", null, "VITHAL", "", "NARSIMHA" };
for (String str : arr1)
{
[Link]("elements : " + str);
}
}

Output :
elements : RAM
elements : KRISHNA
elements : null
\\\\
elements : VITHAL
elements :
elements : NARSIMHA
OOPS
Introduction to oops
class

- In above fig, ANIMALS is a class

- Dog, rabbit ,tiger are its objects

- Class is a collection of objects i.e. Animals is collection of objects like dog, rabbit, tiger

- Class is not a real world entity It is a blueprint

- Class does not occupy memory i.e. Animals will not occupy memory but dog, giraffe, cat, tiger will
occupy memory

Syntax :

access_modifier class ClassName


{
methods()
contructor
block/variables
nested/inner class
}

Example :

public class Animals


{
public void dog()
{
[Link]("Helllo world");
}
}
object

- object is an instance of class

i.e. Dog is an instance of Animals

- object is a real world entity

- object consists of :

1) Identity -> name

2) state/attribute -> color, age

3) behavior -> eating, running (methods)

Syntax :

ClassName object = new ClassName();

Example :

Animals dog = new Animals();


[Link](); //call method bark()

Example :

package [Link];

public class Animal


{
public static void main(String args[])
{
Animal obj = new Animal();
[Link]();
[Link]();
}

public void eat()


{
[Link]("eating...");
}

public void run()


{
[Link]("running...");
}
}

Output :

eating...
running...
Question :

1) How object is stored in java ?


- when we declare a variable of class type, only a reference is created (memory


not allocated) and it will give compile time error as “Error here because obj is not
initialized”

i.e. Classname obj;

- In java, Objects are stored in “heap memory” dynamically But for that we have
to initialize object using “new” as below,

i.e. Classname obj = new Classname();


polymorphism

1) Compile time polymorphism : - achieved using method overloading

2) Run time polymorphism - achieved using method overriding


Method overloading
- Multiple methods with same name but different parameters is method overloading

- This is compile-time polymorphism as which method to excecute is decided at compile


time

Real example (MOBILE) :


U want to save name of person & his mobile number so we create method saveContact(String name,
int mob1) But few people can have more than one mobile numbers so we create method as
saveContact(String name, int mob1, int mob2)

Rules :
- Methods are within same class

- Methods have same name and different parameters

- All those methods should have same return type

Example 1 : (problem with methods same name and same parameters)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]();
}

void show()
{
[Link]("hello");
}

void show()
{
[Link]("java");
}
}

Output :

Compile time error!

Explaination :

Here compiler gets confused which method to execute as both are with same name and same
parameters
Example 2 : (solution is to methods same name and different parameters)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]();
}

void show()
{
[Link]("hello");
}

void show(int a)
{
[Link]("java");
}
}

Output :

hello

Example 3 : (return type should be same)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]();
}

void show()
{
[Link]("hello");
}

int show(int a) // used different return type int


{
[Link]("java");
}
}

Output :

Compile time error!


Example 4 : (overloading main() method)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link](10);
}

public static void main(int a)


{
[Link]("hello");
}
}

Output :

hello

Example 5 :

[Link]

package [Link];

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]('c'); // passing char
}

void show(String str)


{
[Link]("hello");
}
}

Output :

Compile time error!

Explaination :

compile time error as no method to pass char value


Example 6 : (Automatic promotion)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]('c'); // passing char
}

void show(String str)


{
[Link]("hello");
}

void show(int i)
{
[Link]("java");
}

void show(Object j)
{
[Link]("world");
}
}

Output :

java

Explaination :
- we passed char value ‘c’
- but we have no method written for char
- we have methods with parameters String and int
- but it will execute method with parameter int
- because of Automatic promotion in java as shown below
- as shown in fig, char gets promoted to int
Example 7 : (Automatic promotion)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]('c'); // passing char
[Link]("this is string");
}

void show(String str)


{
[Link]("hello");
}

void show(Object j)
{
[Link]("world");
}
}

Output :
world
hello

Explaination :

- we passed char value ‘c’


- but we have no method written for char
- we have methods with parameters String and Object
- but it will execute method with parameter Object
- because String class extends Object class
Example 8 : (Automatic promotion)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link](10, 20.5f);
[Link](20.5f, 40);
}

void show(int a, float b)


{
[Link]("hello");
}

void show(float a, int b)


{
[Link]("world");
}
}

Output :
hello
world

Explaination :
Example 9 : (Automatic promotion)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link](10, 20); // both values are int
}

void show(int a, float b)


{
[Link]("hello");
}
}

Output :
hello

Explaination :

- we passed both int values


- it work as per Automatic promotion in java as shown below
- so int value 20 gets promoted to float here
Example 10 : (Automatic promotion)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link](10, 20); // both values are int
}

void show(int a, float b)


{
[Link]("hello");
}

void show(float a, int b)


{
[Link]("world");
}
}

Output :

Compile time error!

Explaination :
- we passed both int values
- it work as per Automatic promotion in java as shown below
- but still compiler gets confused due to 2 methods written
Example 11 : (Automatic promotion)

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link](10.5f, 20.6f); // both values are float
}

void show(int a, float b)


{
[Link]("hello");
}

void show(float a, int b)


{
[Link]("world");
}
}

Output :

Compile time error!

Explaination :
- we passed both int values
- it work as per Automatic promotion in java as shown below
- float can not goes back to int
- so we get error here
Example 12 :

[Link]

public class Test


{
public static void main(String[] args)
{
Test obj = new Test();
[Link](10);
[Link]();
[Link](10, 20, 30, 40);
}

void show(int a)
{
[Link]("hello");
}

void show(int... a)
{
[Link]("world");
}
}

Output :

hello
world
world
Method overriding

- Can achieve Run-time polymorphism


as which method to execute is decided at run time by JVM When child class assigned to the
parent class
i.e. ParentClass p = new ChildClass();
then after program execution, JVM figures out the object type and run the method that
belongs to that particular object
- JVM will execute method of child class

Real world example :


Bank provides functionality to calculate RateOfInterates.
But Its value varies according to banks (even though formula is same).
e.g. SBI & ICICI could provide 8%, 9% rate of interest.

Rules :

- Method are in different class (subclass)


- Methods must have same name and same parameters as in parent class
- There must be IS-A relationship (i.e. inheritance,interface,abstract)
Example 1 :

[Link]

package [Link];

public class Test extends A


{
public static void main(String[] args)
{
A t1 = new A();
[Link]();
Test t2 = new Test();
[Link]();
A t3 = new Test(); // Run-time polymorphism
[Link]();
// Test t4 = new A(); //will give compile time error
}

public void display() // overriden method


{
[Link]("display in class Test");
}
}

[Link]

package [Link];

public class A
{
public void display()
{
[Link]("display in class A");
}
}

Output :

display in class A
display in class Test
display in class Test
Example 2 :

[Link]

public class Test


{
public static void main(String args[])
{
SBI s = new SBI();
ICICI i = new ICICI();
[Link]("SBI Rate of Interest: " + [Link]());
[Link]("ICICI Rate of Interest: " + [Link]());

Bank bank = new ICICI(); // child class ICICI assigned to the parent class Bank reference
[Link]("RUNTIME POLYMORPHISM : " + [Link]());
}
}

[Link]

public class Bank


{
int getRateOfInterest()
{
return 0;
}
}

[Link]

public class SBI extends Bank


{
int getRateOfInterest()
{
return 8;
}
}

[Link]

public class ICICI extends Bank


{
int getRateOfInterest()
{
return 7;
}
}

Output :

SBI Rate of Interest: 8


ICICI Rate of Interest: 7

RUNTIME POLYMORPHISM : 7
Example 3 : (using different return types)

[Link]

package [Link];

public class Test extends XYZ


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]();
XYZ st = new XYZ();
[Link]();
}

String show() // ovrriden method


{
[Link]("world");
return null;
}
}

[Link]

package [Link];

public class XYZ


{
Object show()
{
[Link]("hello");
return null;
}

Output :

world
hello

Explaination :

- generally different return types not allowed in method overriding

- but its allowed if parent class has parent return type

- in our example Object is parent return type of String


Example 4 : (using different return types)

[Link]

package [Link];

public class Test extends XYZ


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]();
XYZ st = new XYZ();
[Link]();
}

String show() // ovrriden method


{
[Link]("world");
return null;
}
}

[Link]

package [Link];

public class XYZ


{
int show()
{
[Link]("hello");
return 12;
}
}

Output :

Compile time error!

Explaination :

- generally different return types not allowed in method overriding

- in our example int is not parent return type of String

- so we get error
Example 5 : (using different access modifiers)

[Link]

package [Link];

public class Test extends XYZ


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]();
XYZ st = new XYZ();
[Link]();
}

public void show() // overriden method


{
[Link]("world");
}
}

[Link]

package [Link];

public class XYZ


{
protected void show()
{
[Link]("hello");
}
}

Output :

world
hello

Explaination :

- different access modifiers are allowed in method overriding

- but child class should have same or less restrict access modifier than its parent class

- in our example public of child class is less restricted than protected of parent class
Example 6 : (using different access modifiers)

[Link]

package [Link];

public class Test extends XYZ


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]();
XYZ st = new XYZ();
[Link]();
}

void show() // ovrriden method


{
[Link]("world");
}
}

[Link]

package [Link];

public class XYZ


{
protected void show()
{
[Link]("hello");
}
}

Output :

Compile time error!

Explaination :

- different access modifiers are allowed in method overriding

- but child class should have same or less restrict access modifier than its parent class

- in our example default of child class is more restricted than public of parent class
Example 7 : (using super keyword)

[Link]

package [Link];

public class Test extends XYZ


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]();
}

void show() // ovrriden method


{
[Link]("world");
[Link]();
}
}

[Link]

package [Link];

public class XYZ


{
void show()
{
[Link]("hello");
}
}

Output :

world
hello

Questions :

1) Can we override static method ?


➔ NO. because static method belongs to class while instance method belongs to object.

2) Can we override main method?


➔ NO. As main method is static.

3) Can we override synchronized method ?


➔ YES

4) Which methods can not override ?


➔ final , staic, private
constructor

- Constructor is a block similar to method.


- It is used to initialize objects
- It also perform operations like object creation, starting thread, calling a method
- It is invoked when class is created

Rules :
1) Constructor name must be same as class name
2) Don’t use any return type or void.
E.g. public ConstructorName //is correct.
Public void ConstructorName //is incorrect
public int ConstructorName //is incorrect
3) Don’t invoke explicitly
E.g. A obj =new A(6,”hello”); //is correct.
------------------------------
A obj =new A();
Obj.A(6,”hello”); //is incorrect
4) Can not be abstract, final, static, synchronized

Syntax :

access_modifier className()
{
//code
}

Example :

public Test()
{
//code
}

Types of constructors :

1) default / no-args
2) parameterized
Example : (problem without constructor)

[Link]

package [Link];

public class Employee


{
String name;
int id;

public static void main(String args[])


{
Employee e1 = new Employee();
Employee e2 = new Employee();

[Link]("[Link] : " + [Link]);


[Link]("[Link] : " + [Link]);

[Link]("[Link] : " + [Link]);


[Link]("[Link] : " + [Link]);
}
}

Output :
[Link] : null
[Link] : 0
[Link] : null
[Link] : 0

Explaination :

Both objects getting same values


Example : (solved problem without constructor)

[Link]

package [Link];

public class Employee


{
String name;
int id;

public static void main(String args[])


{
Employee e1 = new Employee();
[Link] = "krishna";
[Link] = 10;

Employee e2 = new Employee();


[Link] = "panduranga";
[Link] = 20;

[Link]("[Link] : " + [Link]);


[Link]("[Link] : " + [Link]);
[Link]("---------------");
[Link]("[Link] : " + [Link]);
[Link]("[Link] : " + [Link]);
}
}

Output :
[Link] : krishna
[Link] : 10
---------------
[Link] : panduranga
[Link] : 20

Explanation :

- Both objects getting different values


- To solve previous problem Here we just added below 2 lines,
[Link] = "krishna";
[Link] = 10;
But what if we want such 1000 objects Will u still add this 2 lines 1000 times?
Answer is No.
The better solution for this problem is to create the constructor
Example : (solved problem with constructor)

[Link]

package [Link];

public class Employee


{
String name;
int id;

Employee(String name, int id)


{
[Link] = name;
[Link] = id;
}

public static void main(String args[])


{
Employee e1 = new Employee("krishna", 10);
Employee e2 = new Employee("panduranga", 20);

[Link]("[Link] : " + [Link]);


[Link]("[Link] : " + [Link]);
[Link]("---------------");
[Link]("[Link] : " + [Link]);
[Link]("[Link] : " + [Link]);
}
}

Output :
[Link] : krishna
[Link] : 10
---------------
[Link] : panduranga
[Link] : 20

Explaination :

- Both objects getting different values


Example : (constructor overloading)

[Link]

package [Link];

public class Test


{
private Test(int i, String s) // constructor
{
[Link]("i : " + i);
[Link]("s : " + s);
}

private Test(int j, String d, int k) // overloading of above constructor


{
[Link]("j : " + j);
[Link]("d : " + d);
[Link]("k : " + k);
}

public static void main(String args[])


{
Test b = new Test(5, "hello world");
[Link]("------------------");
Test c = new Test(6, "hello world", 16);
}
}

Output :
i : 5
s : hello world
------------------
j : 6
d : hello world
k : 16
Example : (constructor chaining)

[Link]

package [Link];

public class Test


{
Test()
{
this(10);
[Link]("constructor 1 ...");
}

Test(int i)
{
this(20, "hit");
[Link]("constructor 2 ...");
}

private Test(int j, String d)


{
[Link]("constructor 3 ...");
}

public static void main(String args[])


{
Test t = new Test();
}

Output :
constructor 3 ...
constructor 2 ...
constructor 1 ...
Default/ no-args constructor

Example :

[Link]

package [Link];

public class Test


{
Test() //no-args constructor
{
[Link]("Hello world!");
}

public static void main(String args[])


{
Test b = new Test(); // call to constructor
}
}

Output :
Hello world!

parameterized constructor

Example :

[Link]

public class Test


{
Test(int i) //parameterized constructor
{
[Link]("number is : "+i);
}

public static void main(String args[])


{
Test b = new Test(10); // call to constructor
}
}

Output :
number is : 10
relationship

Types of relationship :

Examples of relationship :
Uses-A relationship

- Dependent relationship
- when method of one class uses an object of another class.

Has-A relationship

- Association relationship
- When an object of one class is created as data member inside another class
- In below example,
Object of Class Address is ceated as data member inside another class Person

- Association means creating relationship between two classes

Example :

[Link]

public class Employee


{
String name;
Address address; //association

public Employee(String name, Address address)


{
[Link] = name;
[Link] = address;
}

...
}

[Link]

public class Address


{
String state, country;

public Address(String state, String country)


{
[Link] = state;
[Link] = country;
}
}
Types of Association :

1) Aggregation :

- When classes are not dependent on each other then it called as aggregation
- suppose we delete one class then other class will not have any effect on it. Means it will not
stop working.
- So it represents weak bonding

Example :

[Link]

public class Employee


{
String name;
Address address; //association

public Employee(String name, Address address)


{
[Link] = name;
[Link] = address;
}

void display()
{
[Link]("address of " + name +" is " + [Link] + " " + [Link]);
}

public static void main(String[] args)


{
Address address = new Address("UP", "india");

Employee e = new Employee("varun", address);


[Link]();
}
}

[Link]

public class Address


{
String state, country;

public Address(String state, String country)


{
[Link] = state;
[Link] = country;
}
}

Output :
address of varun is UP india
2) Composition :

- When classes are dependent on each other then it called as composition


- suppose we delete one class then other class will have effect on it.
- So it represents strong bonding
- for example,
car has a engine
so if we delete engine from car then car will not work.

Example :

[Link]

public class Car


{
String modelName;
Engine engine; //association

Car(String modelName)
{
[Link]=modelName;
}

void show()
{
[Link]("car model name is : "+modelName);
}

public static void main(String args[])


{
Engine engine=new Engine(7);
Car car=new Car("Ferrari");
[Link]();
}
}

[Link]

public class Engine


{
int gen;

//composition
public Engine(int i)
{
[Link]=gen;
[Link]("Car engine is started...");
}
}

Output :
Car engine is started...
car model name is : Ferrari
IS-A relationship

- Inheritance relationship
- relationship between two classes in which one class extends another class
- we will learn this in detail in the next topic
Inheritance

- Inheritance is the mechanism where object of subclass acquires all behaviours and
properties of its parent class
- Helps in reusability of code
- Represents IS-A relationship (e.g. Dog IS A subclass of its parent Animal class)
- We can achieve polymorphism (method overriding)
- Its disadvantage is that it is tightly coupled i.e. if we change in one class it also affects
another class

Syntax :

public class Subclass extends ParentClass


{

Types :

Note :
- Multiple inheritance is not possible in java
single level

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Animal a = new Animal();
[Link]();
[Link]("----------------");
Dog d = new Dog();
[Link]();
[Link]();
}
}

[Link]

package [Link];

public class Animal


{
void eat()
{
[Link]("eating...");
}
}

[Link]

package [Link];

public class Dog extends Animal


{
void bark()
{
[Link]("barking...");
}
}

Output :
eating...
----------------
barking...
eating...
multi level

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
[Link]("####### class with same class obj creation #######");
Animal a = new Animal(); // contain methods of Animal only
[Link]();
Dog d = new Dog(); // contain methods of Animal, Dog only
[Link]();
[Link]();
BabyDog b = new BabyDog(); // contain methods of Animal, Dog, BabyDog
[Link]();
[Link]();
[Link]();

[Link]("####### class with Diff class obj creation #######");


Animal a1 = new Dog(); // contain methods of Animal only
[Link]();
Animal a2 = new BabyDog(); // contain methods of Animal only
[Link]();
Dog d1 = new BabyDog(); // contain methods of Animal, Dog only
[Link]();
[Link]();
}
}

[Link]

package [Link];

public class Animal


{
void eat()
{
[Link]("eating...");
}
}
[Link]

package [Link];

public class Dog extends Animal


{
void bark()
{
[Link]("barking...");
}
}

[Link]

package [Link];

public class BabyDog extends Dog


{
void weep()
{
[Link]("weeping...");
}
}

Output :
####### class with same class obj creation #######
eating...
barking...
eating...
barking...
eating...
weeping...
####### class with Diff class obj creation #######
eating...
eating...
eating...
barking...
hierarchical

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Animal a = new Animal();
[Link]();
[Link]("----------------");
Dog d = new Dog();
[Link]();
[Link]();
[Link]("----------------");
Cat c = new Cat();
[Link]();
[Link]();
}
}

[Link]

package [Link];

public class Animal


{
void eat()
{
[Link]("eating...");
}
}

[Link]

package [Link];

public class Dog extends Animal


{
void bark()
{
[Link]("barking...");
}
}
[Link]

package [Link];

public class Cat extends Animal


{
void meow()
{
[Link]("meowing...");
}
}

Output :
eating...
----------------
barking...
eating...
----------------
meowing...
eating...
Question :
1) why multiple inheritance is not allowed in java ?

Example :

[Link]

package [Link];

public class Test extends A,B


{
public static void main(String[] args)
{
Test obj = new Test();
[Link]();
}
}

[Link]

package [Link];

public class A
{
void show()
{
[Link]("class A...");
}
}

[Link]

package [Link];

public class B
{
void show()
{
[Link]("class B...");
}
}

Output :
Compile time error!

Explaination :
- Compiler will get confused that from which class show() method should call class A or
class B ?
2) Is constructor gets inherited ?

➔ NO

3) Is private method gets inherited ?

➔ NO

4) If class B extends class A. then who is parent class of class A ?

➔ Object class.
As Object class is the topmost class.
Abstract class

- Abstraction can be achieved in two ways,


1) abstract class : we can achieve o to 100% abstraction
2) interface : we can achieve 100% abstraction

- Abstraction is the process of hiding internal working and showing only functionality to user
- Abstract class can have both abstract and non-abstract methods

Real world example :


SMS sending. where you only know type and send message. but don’t know its internal working
how it works.
- Similarly in abstract class or interface we just write method names. But its actual
implementation or internal working we write in different class.

Rules :
1) Declare abstract class with keyword abstract
2) It can have both abstract and non-abstract methods
3) It can not be initiated
4) It can have normal final methods.
But that method should not be abstract else it will give compile-time error.
e.g. public abstract final void show(); //is incorrect
5) It can have constructors and static methods also

Syntax for class :

abstract class classname


{
//code here
}

Syntax for method :

abstract void methodname(); //put semicolon (;) after method


Example 1 :

[Link]

package [Link];

public class Bike


{
void start()
{
[Link]("bike starts with kick");
}

public static void main()


{
Vehicle v = new Vehicle(); // can not create object of astract class
}
}

[Link] //abstarct class

package [Link];

public abstract class Vehicle


{
abstract void start();
}

[Link]

package [Link];

public class Car extends Vehicle


{
void start()
{
[Link]("car starts with key");
}
}

Output :
Compile time error!
Example 2 :

[Link]

package [Link];

public class Bike


{
void start()
{
[Link]("bike starts with kick");
}

public static void main(String[] args)


{
Car c = new Car();
[Link]();
Bike b = new Bike();
[Link]();
}
}

[Link] //abstract class

package [Link];

public abstract class Vehicle


{
abstract void start();
}

[Link]

package [Link];

public class Car extends Vehicle


{
void start()
{
[Link]("car starts with key");
}
}

Output :
car starts with key
bike starts with kick
Example 3 :

[Link]

public class Test


{
public static void main(String args[])
{
Bike obj = new Honda();
[Link]();
[Link]();
[Link]();
}
}

[Link] //abstract class

public abstract class Bike


{
Bike() // constructor
{
[Link]("bike is created");
}

abstract void run(); // abstract method

void changeGear() // normal method


{
[Link]("gear changed");
}

public final void show() // this final method cannot be overriden


{
[Link]("bike show");
}
}

[Link]

public class Honda extends Bike


{
void run()
{
[Link]("running safely..");
}
}

Output :
bike is created
running safely..
gear changed
bike show
interface

- Interface is the blueprint of a class


- It helps in achieving abstraction
- It helps in achieving multiple inheritance

Rules :

1) It contains only abstract methods , not contain normal methods with body
By default methods are public abstract
[Link] create method,
void show();
then compiler automatically makes it as,
public abstract void show();
2) By default variables are public static final,
[Link] create variable,
int a=10;
then compiler automatically makes it as,
public static final int a=10;
3) Since java 8, it can have default & static methods also
4) Since java 9, it can have private methods also

Syntax for creation :

interface interfaceName
{
//code here
}

Syntax for calling interface :

Public class ClassName implements interfaceName


{
//code here
}
Example 1 :

[Link]

public class Test implements Sample


{
@Override
public void show()
{
[Link]("In method show");
}

public static void main(String args[])


{
// Sample s = new Sample(); //COMPILE ERROR as can’t create object of interface
Test t = new Test();
[Link]();
t.m1();
}
}

[Link] //interface

public interface Sample


{
void show(); // internally it is public abstract void show();

int a = 10; // internally it is public static final int a=10;

default void m1() // default method of java 8


{
[Link]("In default method");

m2();
m3();
}

static void m2() // sataic method of java 8


{
[Link]("In static method");
}

private void m3() // private method of java 9


{
[Link]("In private method");
}
}

Output :

In method show
In default method
In static method
In private method
Example 2 :

[Link]

public class Test


{
public static void main(String[] args)
{
//Bank b =new Bank(); //INCORRECT will give compile time error
//SBI sbi=new PNB(); //INCORRECT will give compile time error
SBI sbi=new SBI();
[Link]("SBI RI: " + [Link]());
PNB pnb =new PNB();
[Link]("PNB RI: " + [Link]());
Bank bank1 = new SBI();
[Link]("SBI RI: " + [Link]());
Bank bank2 = new PNB();
[Link]("PNB RI: " + [Link]());
[Link]("---------------------------------------");
[Link]();//calling msg method
[Link]("---------------------------------------");
[Link]("CUBE is : "+ [Link](3)); //as method is static it can't invoked like [Link]();
}
}

[Link] //interface

public interface Bank


{
public float rateOfInterest();

default void msg()


{
[Link]("JAVA 8 default method");
}

public static int cube(int num)


{
return num*num*num;
}
}

[Link]

public class SBI implements Bank


{
public float rateOfInterest()
{
return 9.15f;
}
}

[Link]

public class PNB implements Bank


{
public float rateOfInterest()
{
return 9.7f;
}
}
Output :
SBI RI: 9.15
PNB RI: 9.7
SBI RI: 9.15
PNB RI: 9.7
---------------------------------------
JAVA 8 default method
---------------------------------------
CUBE is : 27

Example 3 : (multiple inheritance achieved by interface)

[Link]

public class Test impments A, B


{
public void show()
{
[Link]("showing...");
}

public static void main(String args[])


{
Test obj = new Test();
[Link]();
}
}

[Link] //interface

public interface A
{
void show();
}

[Link] //interface

public interface B
{
void show();
}

Output :
showing...

Explanation :
Even though interface A and interface B has same method name show() we are able to call it.
Example 3 : (interface extends interface)

[Link]

package [Link];

public class Test implements B


{
public void print()
{
[Link]("Hello");
}

public void show()


{
[Link]("Welcome");
}

public static void main(String args[])


{
Test obj = new Test();
[Link]();
[Link]();
}
}

[Link] //interface

public interface A
{
void print();
}

[Link] //interface

public interface B extends A


{
void show();
}

Output :
Hello
Welcome
Question :
1) What is Marked or Tagged interface?
➔ An empty interface.
Means interface which don’t contain any method is known as marked/taged
interface.
e.g. Seriliazable, Cloneable, Remote, EventListener are few examples of marked
interface.
This interfaces provides some useful information to JVM so that JVM may
perform some operation using that information.

2) Can interface implements abstract class?


➔ NO.
because abstract is a class not an interface.

3) Can abstract class implements interface?


➔ Yes.
because class implements interface.

4) Explain which access-modifiers are suitable for abstract class and abstract
methods?
➔ Below table shows all conditions :

public abstract class Printable Abstract Class and abstract method can
{ public
public abstract void print();
}
private abstract class Printable Abstract Class and abstract method
{ cannot private
private abstract void print();
}
protected abstract class Printable Abstract Class cannot be protected
{
protected abstract void print(); Abstract method can be protected
}
abstract final class Printable Abstract Class cannot be final
{
abstract final void print(); Abstract method cannot be final

private final void msg() normal method can be final and


{ private/protected in abstract class
[Link]("hello");
}
}
5) Explain which access-modifiers are suitable for interface and its methods?
➔ Below table shows all conditions :

public interface Showable interface and its method can public


{
public void show();
}
private interface Showable interface and its method cannot
{ private
private void show();
}
protected interface Showable interface and its method cannot
{ protected
protected void show();
}
public final interface Showable interface its method and even normal
{ method in interface cannot be final
public final void show();

static final int cube(int x)


{
return x * x * x;
}
}

6) Can interface implements interface?


➔ No

7) Can interface extends interface?


➔ YES

8) Abstract class vs interface?


Sr Abstract class interface


no.
1. Can create constructor Can not create constructor
2. Can not achieve multiple inheritance Can achieve multiple inheritance
3. Less strict More strict
Encapsulation

- Encapsulation means wrapped capsule

- In which technique of data hiding is used

Real world Example (water tank) :

Suppose Water is our data which is secured in tank and only can be accessible via tap.

It means we have done data hiding on water using tank And filling water in yank via
pipe([Link] method),

accessing data (water) via tap ([Link] method)

- Java bean is the best example of fully encapsulation

Steps to perform encapsulation :

1) make data member private


2) create setter method
3) create gettter method

- we can achieve encapsulation by making all data members private and create public setter
and getter methods.

- By creating setter and getter method we can make class read-only and write-only. Because
in setters we set some values which is write only And in getters we get values which is read
only. [Link] read xml using getter methods and write(create) json using setter method

- Encapsulation helps in security of data.

As we don’t allow unauthorized access to it.

As data can not be accessible directly. It can be accessed only using setter & getter
methods.
Example 1 : (problem without encapsulation)

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Employee e = new Employee();
[Link] = 101; // by doing this data is accessible anywhere
}
}

[Link]

package [Link];

public class Employee


{
int empId;
}

Explanation :

In above example,

Data is updatable/accessible anywhere

So security is the problem


Example 2 : (using encapsulation)

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Employee e = new Employee();
[Link](101);
[Link]("ID : " + [Link]());
}
}

[Link]

package [Link];

public class Employee


{
private int empId;

public int getEmpId()


{
return empId;
}

public void setEmpId(int empId)


{
[Link] = empId;
}
}

Output :
ID : 101
Example 3 : (using encapsulation)

[Link]

public class Test


{
public static void main(String args[])
{
Employee e = new Employee();
[Link](16);
[Link]("ID : " + [Link]());
}
}

[Link]

public class Employee


{
private int empId;

public int getEmpId()


{
if(empId>20)
{
return empId;
}
return 0;
}

public void setEmpId(int empId)


{
[Link] = empId;
}
}

Output :
ID : 0

Explanation :
- here we authenticated employee Id

- If user enterd valid empId then only he will get his correct Id

- else he will get 0 in return


Question :
1) Is Data hiding vs Encapsulation?
➔ - Data hiding is the technique to hide data
where we keep data members as private.
- Encapsulation is the process which uses data hiding to secure data but data
is accessible using setters & getters methods

2) Is Abstraction V/S Encapsulation ?


Abstraction Encapsulation
Abstraction is about hiding working Encapsulation is about hiding data
And shows only functionality
e.g. mobile phones we don’t know its e.g. water tank where we hide water and
internal coding but we know its give access only via tap
functionaities

3) why Encapsulation is needed?


➔ - If we don’t use encapsulation then instance variables of class are easily accesible to other classes
- This can lead to modifying values of instance variables
- In encapsulation we are meking those instance variables private (data hiding)
- Which can be only accessible by methods of that class (setter and getter)
- So it makes instance variables protected
- We can also put some authentication on setter and getter method to validate a user
Call by reference

Note : There is no call by value in java

Example : (without call by reference)

[Link]

public class Test


{
int data = 50;

void change(int data)


{
data = data + 100;// changes will be in the local variable only
}

public static void main(String args[])


{
Test op = new Test();
[Link]("before change " + [Link]);

[Link](500);
[Link]("after change " + [Link]);
}
}

Output :
before change 50
after change 50

Example : (using call by reference)

[Link]

public class Test


{
int data = 50;

void change(Test op)


{
[Link] = [Link] + 100; // changes will be in the instance variable
}

public static void main(String args[])


{
Test op = new Test();
[Link]("before change " + [Link]);

[Link](op);// passing object


[Link]("after change " + [Link]);
}
}

Output :
before change 50
after change 150
Recursion

- Recursion is the process in which a method calls itself infinitely or continuously

Syntax :

returnType methodName()
{
methodName();
}

Example : (recursion with infinite loop)


[Link]

package [Link];

public class Test


{
static void show()
{
[Link]("hello");
show(); // method calls itself here
}

public static void main(String[] args)


{
show();
}
}

Output :

hello
hello
hello

....

helloException in thread "main" [Link]


Example : (recursion with finite loop)

[Link]

public class Test


{
public static void main(String[] args)
{
int result = sum(15);
[Link](result);
}

public static int sum(int k)


{
if (k > 0)
{
return k + sum(k - 1); // method calls itself here
} else
{
return 0;
}
}
}

Output :
120
instanceof

- It checks whether the object is an instance of specified class / subclass / interface

- It returns true or false value

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Printable p = new XYZ();
// beacuse we initialized XYZ class with printable here it will be instance of it
Call c = new Call();
[Link](p);
}
}

[Link]

package [Link];

public class Call


{
void invoke(Printable p) // upcasting
{
if (p instanceof ABC)
{
[Link]("p is instance of ABC");
ABC a = (ABC) p;// Downcasting
a.a();
}
if (p instanceof XYZ)
{
[Link]("p is instance of XYZ");
XYZ b = (XYZ) p;// Downcasting
b.b();
}
}
}// end of Call class
[Link]

package [Link];

public class ABC implements Printable


{
public void a()
{
[Link]("a method");
}
}

[Link]

package [Link];

public class XYZ implements Printable


{
public void b()
{
[Link]("b method");
}
}

[Link]

package [Link];

public interface Printable


{
}

Output :
p is instance of XYZ
b method
static keyword

- static keyword helps in memory management mainly

- staic is class level

- static data gets stored in class/method area of JVM

- variable, Nested class, block, method can be static


static variable

- It allocates memory once only at time of class loading

- So it helps in saving memory

Example 1 : (static variable can not declare inside method)

[Link]

public class Test


{
static int a = 10;

public static void main(String args[])


{
[Link]("a : " + a);
}

void m1()
{
static int b = 20; // compile time error
}
}

Output :
compile time error!

Example 2 : (static variable can be called without creating object)

[Link]

public class Test


{
public static void main(String args[])
{
[Link](Demo.a); // called without creating object
}
}

[Link]

public class Demo


{
static int a = 10;
}

Output :
10
Example 3 : (problem without static variable)

[Link]

public class Test


{
int empId;
String name;
String company;

public Test(int empId, String name, String company)


{
[Link] = empId;
[Link] = name;
[Link] = company;
}

void display()
{
[Link](empId + " " + name + " " + company);
}

public static void main(String args[])


{
Test e1 = new Test(101, "Rahul", "Capgemini");
[Link]();
Test e2 = new Test(102, "Suresh", "Capgemini");
[Link]();
}
}

Output :
101 Rahul Capgemini
102 Suresh Capgemini

Explanation :

- In above program Capgemini is the same data we are using repetively

- If we create such 1000 objects say e1,e2,….,e1000

- Then it will need lots of memory to store capgemini


Example 4 : (using static variable)

[Link]

public class Test


{
int empId;
String name;
static String company = "Capgemini";

public Test(int empId, String name)


{
[Link] = empId;
[Link] = name;
}

void display()
{
[Link](empId + " " + name + " " + company);
}

public static void main(String args[])


{
Test e1 = new Test(101, "Rahul");
[Link]();
Test e2 = new Test(102, "Suresh");
[Link]();
}
}

Output :
101 Rahul Capgemini
102 Suresh Capgemini

Explanation :

- Here we saved memory by storing Capgemini in static variable once only


Example 5 : (problem without static variable)

[Link]

public class Test


{
int count = 0;// will get memory each time when the instance is created

Test()
{
count++;// incrementing value
[Link](count);
}

public static void main(String args[])


{
// Creating objects
Test c1 = new Test();
Test c2 = new Test();
Test c3 = new Test();
}
}

Output :
1
1
1

Explanation :

- Here int count = 0 gets initialized again and again


Example 6 : (using static variable)

[Link]

package [Link];

public class Test


{
static int count = 0; // will get memory only once and retain its value

Test()
{
count++;// incrementing value
[Link](count);
}

public static void main(String args[])


{
// Creating objects
Test c1 = new Test(); // call to constructor
Test c2 = new Test(); // call to constructor
Test c3 = new Test(); // call to constructor
}
}

Output :
1
2
3

Explanation :

Here static int count = 0 gets initialized once only


static methods

- No need to create object of class we can call static method using classname only.

i.e. [Link]();

- Variables inside static method also need to be static.

i.e. static int k;

Example 1 :

[Link]

public class Test


{
public static void main(String args[])
{
Test t = new Test();
[Link]();
show(); // can call static method directly if method is within current class
[Link](); // can call static method directly if method is within current class/ouside class
}

static void show()


{
[Link]("showing...");
}
}

Output :
showing...
showing...
showing...
Example 2 :

[Link]

public class Test


{
public static void main(String args[])
{
Sample t = new Sample();
[Link]();
//show(); can call static method directly if method is within current class
[Link](); // can call static method using className if method is in class/ouside class
}
}

[Link]

public class Sample


{
static void show()
{
[Link]("showing...");
}
}

Output :
showing...
showing...

Example 3 : (static methods can access only static data)

[Link]

public class Test


{
int i = 10;

public static void main(String args[])


{
[Link]();
}

static void show()


{
[Link](i); // Compile time error
}
}

Output :

Compile time error!


Example 4 : (static methods can access only static data)

[Link]

public class Test


{
static int i = 10;

public static void main(String args[])


{
[Link]();
}

static void show()


{
[Link](i); // Compile time error
}
}

Output :
10

Example 5 : (static methods can be called through static methods only)

[Link]

public class Test


{
public static void main(String args[])
{
[Link]();
}

static void show()


{
display(); // Compile time error
}

void display()
{
[Link]("displaying");
}
}

Output :
Compile time error!
Example 6 : (static methods can be called through static methods only)

[Link]

public class Test


{
public static void main(String args[])
{
[Link]();
}

static void show()


{
display(); // Compile time error
}

static void display()


{
[Link]("displaying");
}
}

Output :
displaying

Example 7 : (Can not use this keyword within static methods)

[Link]

public class Test


{
int i = 10;
static int j = 20;

public static void main(String args[])


{
[Link]();
}

static void show()


{
[Link](this.i); // Compile time error
[Link](this.j); // Compile time error
}
}

Output :
Compile time error!
Example 8 : (Can not use super keyword within static methods)

[Link]

package [Link];

public class Test extends Sample


{
public static void main(String args[])
{
[Link]();
}

static void show()


{
[Link](super.i); //Compile time error
}
}

[Link]

package [Link];

public class Sample


{
static int i = 10;
}

Output :
Compile time error!
static block

- It is used to initialize static data types

- also used to call native methods (methods of other language i.e. c, c++, etc)

- It executes before main method executes.

- Before JDK 1.6 and older versions we were able to use static blocks without creating main
method in class

- But from JDK 1.7 we must use main method to call static blocks

Syntax :

static
{
//code
}

Example 1 :

[Link]

package [Link];

public class Test


{
static
{
[Link]("static block 1 is invoked");
}

public static void main(String args[])


{
[Link]("main method executed");
}

static
{
[Link]("static block 2 is invoked");
}
static
{
[Link]("static block 3 is invoked");
}
}

Output :
static block 1 is invoked
static block 2 is invoked
static block 3 is invoked
main method executed
Example 2 : (initialiing data in static block)

[Link]

public class Test


{
static int i;

public static void main(String args[])


{
[Link]("main method executed");
}

static
{
i = 50;
[Link]("static block 2 is invoked : " + i);
}
}

Output :
static block 2 is invoked : 50
main method executed
instance block

- instance block invoked after main method

- But before constructor

Syntax :

{
//code
}

Example :

[Link]

public class Test


{
Test() // constructor
{
[Link]("Constructor Called");
}

{
[Link]("block called"); // instance block
}

public static void main(String[] args)


{
[Link]("main called");

Test a = new Test(); // call to constructor


}
}

Output :
main called
block called
Constructor Called
this keyword

- Used as a reference variable for current class object

Example 1 : (without using this keyword)

[Link]

public class Test


{
public static void main(String args[])
{
Sample s = new Sample();
[Link](10);
[Link]();
}
}

[Link]

public class Sample


{
int i;

void data(int k) // name of local variable is same


{
i = k;
}

void show()
{
[Link](i); // prints value of instance variable
}
}

Output :
10
Example 2 : (problem without using this keyword)

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Sample s = new Sample();
[Link](10);
[Link]();
}
}

[Link]

package [Link];

public class Sample


{
int i;

void data(int i) // name of local variable is same


{
i = i; // it considered i in left side as local variable
}

void show()
{
[Link](i); // prints value of instance variable
}
}

Output :
0

Explanation :

- when we used name of local variable same as instance variable

- then we not get output as we want


Example 3 : (using this keyword)

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Sample s = new Sample();
[Link](10);
[Link]();
}
}

[Link]

package [Link];

public class Sample


{
int i;

void data(int i) // name of local variable is same


{
this.i = i; // now it considered i in left side as instance variable
}

void show()
{
[Link](i); // prints value of instance variable
}
}

Output :
10
Example 4 : (refers instance variable of current class)

[Link]

package [Link];

public class Test


{
// instance variables
int a;
int b;

Test(int a, int b) // Parameterized constructor


{
this.a = a;
this.b = b;
}

public void display()


{
[Link]("a = " + a + " b = " + b);
}

public static void main(String[] args)


{
Test object = new Test(10, 20);
[Link]();
}
}

Output :
a = 10 b = 20
Example 5 : (call method of current class)

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Test t = new Test();
[Link]();
}

void display()
{
[Link]("displaying...");
}

void show()
{
display(); // compiler call it as [Link]() internally
[Link]();
}
}

Output :
displaying...
displaying...

Explanation :

- Even though we call method of current class as display();

- compiler internally calls it as [Link]();


Example 6 : (pass argument to method)

[Link]

package [Link];

public class Test


{
void display(Test obj)
{
[Link]("displaying...");
}

void m1()
{
display(this);
}

public static void main(String[] args)


{
Test t = new Test();
t.m1();
}
}

Output :
displaying...

Explanation :

- Even though we call method of current class as display();

- compiler internally calls it as [Link]();


Example 7 : (pass argument to method)

[Link]

package [Link];

public class Test


{
int a;
int b;

// Default constructor
Test()
{
a = 10;
b = 20;
}

void display(Test obj)


{
[Link]("a = " + obj.a + " b = " + obj.b);
}

void get()
{
display(this); // returns current class instance
}

public static void main(String[] args)


{
Test object = new Test();
[Link]();
}
}

Output :
a = 10 b = 20
Example 8 : (call constructor of current class)

[Link]

public class Test


{
Test() // Default constructor
{
[Link]("Inside default constructor \n");
}

Test(int a) // Parameterized constructor


{
this();
[Link]("Inside parameterized constructor");
}

public static void main(String[] args)


{
Test object = new Test(10);
}
}

Output :
Inside default constructor

Inside parameterized constructor

Example 9 : (call constructor of current class)

[Link]

public class Test


{
int a;
int b;

Test() // Default constructor


{
this(10, 20); // refer to parametrized constructor

[Link]("Inside default constructor \n");


}

Test(int a, int b) // Parameterized constructor


{
this.a = a;
this.b = b;
[Link]("Inside parameterized constructor");
}

public static void main(String[] args)


{
Test object = new Test();
}
}

Output :
Inside default constructor

Inside parameterized constructor


Example 10 : (pass argument to constructor)

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
Test t = new Test();
t.m1();
}

void m1()
{
Sample s = new Sample(this);
}
}

[Link]

package [Link];

public class Sample


{
Sample(Test t)
{
[Link]("in Sample constructor...");
}
}

Output :
in Sample constructor...
Example 11 : (returns instance of current class)

[Link]

package [Link];

public class Test


{
Test m1()
{
return this;
}

void m2()
{
[Link]("in m2...");
}

public static void main(String[] args)


{
Test t = new Test();
t.m1().m2();
}
}

Output :
in m2...
super keyword

- this keyword refers to current class object

- super keyword used to refer parent class object

Example 1 :

[Link]

public class Test extends Sample


{
int i = 20;

void show(int i)
{
[Link](i);
}

public static void main(String[] args)


{
Test t = new Test();
[Link](30);
}
}

[Link]

public class Sample


{
int i = 10;
}

Output :
30
Example 2 : (using this keyword)

[Link]

public class Test extends Sample


{
int i = 20;

void show(int i)
{
[Link](this.i);
}

public static void main(String[] args)


{
Test t = new Test();
[Link](30);
}
}

[Link]

public class Sample


{
int i = 10;
}

Output :
20
Example 3 : (using super keyword)

[Link]

public class Test extends Sample


{
int i = 20;

void show(int i)
{
[Link](super.i);
}

public static void main(String[] args)


{
Test t = new Test();
[Link](30);
}
}

[Link]

public class Sample


{
int i = 10;
}

Output :
10
Example 4 : (using super keyword with variable)

[Link]

package [Link];

public class Test extends Sample


{
int maxSpeed = 180;

void display()
{

[Link]("Maximum Speed: " + [Link]); //prints speed of parent class


}

public static void main(String[] args)


{
Test t = new Test();
[Link]();
}
}

[Link]

package [Link];

public class Sample


{
int maxSpeed = 120;
}

Output :
Maximum Speed: 120
Example 5 : (using super keyword with method)

[Link]

package [Link];

public class Test extends Sample


{
void message()
{
[Link]("This is CAR");
}

void display()
{
[Link](); // calls parent class method
}

public static void main(String[] args)


{
Test t = new Test();
[Link]();
}
}

[Link]

package [Link];

public class Sample


{
void message()
{
[Link]("This is VEHICLE");
}
}

Output :
This is VEHICLE
Example 6 : (using super keyword with constructor)

[Link]

package [Link];

public class Test extends Sample


{
Test()
{
super();
[Link]("This is CAR");
}

public static void main(String[] args)


{
Test t = new Test();
}
}

[Link]

package [Link];

public class Sample


{
Sample()
{
[Link]("This is VEHICLE");
}
}

Output :
This is VEHICLE
This is CAR
final keyword

- Prevents constant variables access outside method

- Prevents method overriding

- Prevents inheritance

final variable

Example :

[Link]

package [Link];

public class Test


{
public static void main(String args[])
{
final int val = 50;

val = 60; // COMPILE-TIME ERROR as we cant change value once it is final

[Link]("value : " + val);


}
}

Output :
COMPILE-TIME ERROR
final method

Example :

[Link]

package [Link];

public class Test extends Car


{
public static void main(String args[])
{

Car ts = new Car();

[Link]();

public void show() // COMPILE-TIME ERROR as method is final


{
[Link]("hello");
}
}

[Link]

package [Link];

public class Car


{
public final void show()
{
[Link]("hello");
}
}

Output :
COMPILE-TIME ERROR
final class

Example :

[Link]

public class Test extends Car // COMPILE-TIME ERROR as class is final


{
public static void main(String args[])
{
Car ts = new Car();

[Link]();
}
}

[Link]

public final class Car


{
public void show()
{
[Link]("hello");
}
}

Output :
COMPILE-TIME ERROR

Questions :

1) Can we declare final variable as static ?


➔ YES

But you have create static block for it to access.

e.g.

static final int data;// static blank final variable

static
{
data = 50;
}

2) Can we create constructor final?


➔ NO.
Because constructor never inherited
wrapper class

- Till now we used premitive data types like int, byte, long, ect.

- But as java is object oriented programming language sometimes we need data types as
objects

- So wrapper classes provides that functionality

- Integer, Byte, Character, Short, Long, Float, Double, Boolean are all wrapper classes

- These classes are final internally like String class so helps in not modifying data

- Collection framework work only on wrapper classes

- In multithreading we need wrapper classes to support synchronization

Example : (common example)

[Link]

public class Test


{
public static void main(String[] args)
{
String str = "20";
int a = [Link](str); // boxing
[Link]("boxing : " + a);

int num = 30;


Integer val = [Link](num); // boxing
[Link]("boxing : " + val);

Integer num1 = 10;


int val1 = [Link]();
[Link]("unboxing : " + val1);

}
}

Output :
boxing : 20
boxing : 30
unboxing : 10
boxing

- convert premitive type to object

- i.e. int to Integer

Example :

[Link]

public class Test


{
public static void main(String args[])
{
int num = 20;
Integer obj = new Integer(num);

[Link]("boxing : " + obj);


}
}

Output :
boxing : 20

Auto-boxing

- automatically convert premitive type to object

- i.e. int to Integer

Example :

[Link]

public class Test


{
public static void main(String args[])
{
int num = 20;
Integer obj = num;

[Link]("auto-boxing : " + obj);


}
}

Output :
auto-boxing : 20
unboxing

- convert object to premitive type

- i.e. Integer to int

Example :

[Link]

public class Test


{
public static void main(String args[])
{
Integer obj = new Integer(8);
int num = [Link]();

[Link](unboxing : " + num);


}
}

Output :
unboxing : 8

Auto-unboxing

- automatically convert object to premitive type

- i.e. Integer to int

Example :

[Link]

public class Test


{
public static void main(String args[])
{
Integer obj = new Integer(8);
int num = obj;

[Link](unboxing : " + num);


}
}

Output :
auto-unboxing : 8
Data type conversion

Example :

[Link]

public class Test


{
public static void main(String args[])
{
String value = "12";
int a = [Link](value);
int a1 = [Link](value);
[Link]("INTEGER : " + a + " ------ " + a1);

long b = [Link](value);
long b1 = [Link](value);
[Link]("LONG : " + b + " ------ " + b1);

short c = [Link](value);
short c1 = [Link](value);
[Link]("SHORT : " + c + " ------ " + c1);

byte d = [Link](value);
byte d1 = [Link](value);
[Link]("BYTE : " + d + " ------ " + d1);

double e = [Link](value);
double e1 = [Link](value);
[Link]("DOUBLE : " + e + " ------ " + e1);

float h = [Link](value);
float h1 = [Link](value);
[Link]("FLOAT : " + h + " ------ " + h1);

boolean g = [Link](value);
boolean g1 = [Link](value);
[Link]("BOOLEAN : " + g + " ------ " + g1);

for (int i = 0; i < [Link](); i++)


{
char f = [Link](i);
[Link]("char at " + i + " index is: " + f);
}
}
}

Output :
INTEGER : 12 ------ 12
LONG : 12 ------ 12
SHORT : 12 ------ 12
BYTE : 12 ------ 12
DOUBLE : 12.0 ------ 12.0
FLOAT : 12.0 ------ 12.0
BOOLEAN : true ------ false
char at 0 index is: 1
char at 1 index is: 2
Serialization and De-serialization

Serialization :

- It is a mechanism of converting the state of object into a byte stream

De-Serialization :

- It is a mechanism of converting byte stream into the object

Real world example :

The mobile game in which two players play same game on different mobiles.

When player1 moves his move the player2 can see same on his screen.

This is because move of player1 gets converted to bytestream and transferred over network
quickly.

Syntax :

public class clasName implements Serializable


serialization

Example :

[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String args[]) throws IOException
{
try
{
// Creating the object
Student s1 = new Student(211, "ravi");

// Creating stream and writing the object


FileOutputStream fout = new FileOutputStream("D:\\[Link]");
ObjectOutputStream out = new ObjectOutputStream(fout);

//converting to byte stream


[Link](s1);
[Link]();
[Link]();
} catch (Exception e)
{
[Link](e);
}
}
}

[Link]

import [Link];

public class Student implements Serializable


{
int id;
String name;

public Student(int id, String name)


{
[Link] = id;
[Link] = name;
}
}

Output :
De-serialization

Input :

Example :

[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String args[]) throws IOException
{
try
{
// Creating stream to read the object
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("D:\\[Link]"));
Student s = (Student) [Link]();

// printing the data of the serialized object


[Link]([Link] + " " + [Link]);

// closing the stream


[Link]();
} catch (Exception e)
{
[Link](e);
}
}
}

[Link]

import [Link];

public class Student implements Serializable


{
int id;
String name;

public Student(int id, String name)


{
[Link] = id;
[Link] = name;
}
}

Output :

211 ravi
transient keyword

- If we use transient keyword with specific data variable then it will not be serialized

Example : (serialization)

[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String args[]) throws IOException
{
try
{
// Creating the object
Student s1 = new Student(211, "ravi");

// Creating stream and writing the object


FileOutputStream fout = new FileOutputStream("D:\\[Link]");
ObjectOutputStream out = new ObjectOutputStream(fout);

//converting to byte stream


[Link](s1);
[Link]();
[Link]();
} catch (Exception e)
{
[Link](e);
}
}
}

[Link]

import [Link];

public class Student implements Serializable


{
transient int id;
String name;

public Student(int id, String name)


{
[Link] = id;
[Link] = name;
}
}

Output :
Example : (De-serialization)

[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String args[]) throws IOException
{
try
{
// Creating stream to read the object
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("D:\\[Link]"));
Student s = (Student) [Link]();

// printing the data of the serialized object


[Link]([Link] + " " + [Link]);

// closing the stream


[Link]();
} catch (Exception e)
{
[Link](e);
}
}
}

[Link]

import [Link];

public class Student implements Serializable


{
transient int id;
String name;

public Student(int id, String name)


{
[Link] = id;
[Link] = name;
}
}

Output :

0 ravi
Exception handling

Exception handling is the process to handle the runtime errors so that normal flow
of the application can be maintained.
throws

- throws keyword Mostly used t o specify checked exceptions (compile-time exceptions) but can
also used to specify Un-Checked exceptions

Example :

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args) throws FileNotFoundException
{
FileInputStream file = new FileInputStream("D:\\[Link]");
[Link]("file loaded...");
}
}

Output :

file loaded...

throw

- user defined exception

Example :

[Link]

public class Test


{
public static void main(String args[])
{
validate(13);
}

static void validate(int age)


{
if (age < 18)
{
throw new ArithmeticException("age is not valid for voting");
} else
{
[Link]("welcome to vote");
}
}
}

Output :

Exception in thread "main" [Link]: age is not valid for


voting
at [Link]([Link])
at [Link]([Link])
try-catch block

- try-catch used to specify Un-checked exceptions (run-time exceptions) but can also used to
specify Checked exceptions

Syntax :

try
{
//code
}
catch( ExceptionClassName ref )
{
//print
}

Example : (without try catch)

[Link]

public class Test


{
public static void main(String[] args)
{
int data = 50 / 0; // may throw exception
[Link]("rest of the code");
}
}

Output :

Exception in thread "main" [Link]: / by zero


at [Link]([Link])
Example : (using try catch)

[Link]

public class Test


{
public static void main(String[] args)
{
try
{
int data = 50 / 0; // may throw exception

} catch (ArithmeticException e) // handling the exception


{
[Link]("exception is catched : " + e);
}
[Link]("hello");
}
}

Output :

exception is catched : [Link]: / by zero


hello

Example : (multi try catch)

[Link]

public class Test


{
public static void main(String[] args)
{
try
{
int a[] = new int[5];
a[5] = 30 / 0;
} catch (ArrayIndexOutOfBoundsException e)
{
[Link]("execption is : " + e);
} catch (ArithmeticException e)
{
[Link]("execption is : " + e);
} catch (Exception e) // general exception must written in last
{
[Link]("common task completed : " + e);
}
[Link]("rest of the code...");
}
}

Output :

execption is : [Link]: / by zero


rest of the code...
Example : (nested try catch)

[Link]

public class Test


{
public static void main(String[] args)
{
try
{
try
{
[Link]("going to divide");
int b = 39 / 0;
} catch (ArithmeticException e)
{
[Link]("exception in 2nd try : " + e);
}
try
{
int a[] = new int[5];
a[5] = 4;
} catch (ArrayIndexOutOfBoundsException e)
{
[Link]("exception in 3rd try : " + e);
}
[Link]("other statement");
} catch (Exception e)
{
[Link]("exception in 1st try : " + e);
}
[Link]("normal flow..");
}
}

Output :

going to divide
exception in 2nd try : [Link]: / by zero
exception in 3rd try : [Link]: Index 5 out
of bounds for length 5
other statement
normal flow..
finally block

- No matter try block gives an exception or not finally block will always executes

- We can write it after try-catch block or just with try block

Example :

[Link]

public class Test


{
public static void main(String[] args)
{
try
{
int data = 25 / 0;
[Link](data);
} catch (ArithmeticException e)
{
[Link](e);
} finally
{
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}

Output :

[Link]: / by zero
finally block is always executed
rest of the code...
Custom exception handling

Example : (without parameter)

[Link]

public class Test


{
public static void main(String[] args)
{
try
{
throw new SampleException();
}
catch(SampleException e)
{
[Link]("exception caught..."+[Link]());
}
}
}

[Link]

public class SampleException extends Exception


{
public SampleException()
{

}
}

Output :

exception caught...null
Example : (with parameter)

[Link]

public class Test


{
public static void main(String[] args)
{
try
{
throw new SampleException("Hello Its my own exception...");
}
catch(SampleException e)
{
[Link]("exception caught..."+[Link]());
}
}
}

[Link]

public class SampleException extends Exception


{
public SampleException(String str)
{
super(str);
}
}

Output :

exception caught...Hello Its my own exception...


Method overriding in exception handling

Rule 1 : If super class don’t declares an exception

Case 1: If super class don’t declaes an exception and child class can have

runtime exception

Example : (It will get executed)

[Link]

public class Test extends Parent


{
void msg() throws ArithmeticException //Un-checked exception
{
[Link]("Child");
}

public static void main(String args[])


{
Parent p = new Test();
[Link]();
}
}

[Link]

public class Parent


{
void msg()
{
[Link]("parent");
}
}

Output :

Child
Rule 2 : If super class declares an exception

Case 1 : If parent class has specific exception “ArithmeticException”

then child class can have same exceptions “ArithmeticException”

Example :

[Link]

public class Test extends Parent


{
void msg() throws ArithmeticException // same exception as in superclass
{
[Link]("child");
}

public static void main(String args[])


{
Parent p = new Test();
[Link]();
}
}

[Link]

public class Parent


{
void msg() throws ArithmeticException // same exception as in subclass
{
[Link]("parent");
}
}

Output :

Child
Case 2 : If parent class has child exception “ArithmeticException”

then child class can not have parent exception “Exception”

Example :

[Link]

public class Test extends Parent


{
public static void main(String args[])
{
Parent p = new Test();
[Link]();
}

void msg() throws Exception //compile time error


{
[Link]("child");
}
}

[Link]

public class Parent


{
void msg() throws ArithmeticException
{
[Link]("parent");
}
}

Output :

compile time error


Case 3 : If parent class has exception “Exception” and child class can have child
exception “ArithmeticException”

Example :

[Link]

public class Test extends Parent


{
public static void main(String args[]) throws Exception
{
Parent p = new Test();
[Link]();
}

void msg() throws ArithmeticException


{
[Link]("child");
}
}

[Link]

public class Parent


{
void msg() throws Exception
{
[Link]("parent");
}
}

Output :

child
Case 4 : If parent class has some exception “Exception” and child class can have no

exception

Example :

[Link]

public class Test extends Parent


{
public static void main(String args[]) throws Exception
{
Parent p = new Test();
[Link]();
}

void msg() // no exception


{
[Link]("child");
}
}

[Link]

public class Parent


{
void msg() throws Exception
{
[Link]("parent");
}
}

Output :

child
multithreading

multi tasking

- Performing multiple tasks at single time

- E.g.

- Here VLC, Word doc, Browser running at same time

- It happens because CPU switches tasks one by one

- It happens so fast that we cant see by our eyes

- So we think they all are executing simultaneously

- It inceases CPU performance

- It can be achieved through,

1) Multi-processing

2) Multi-threading
multi processing

- When single system is connected to multiple CPU’s (processors) to complete task

- E.g.

multi threading

- E.g. VLC has multiple tasks like volume, sidebar, audio, video, timer, etc

- This tasks are called as threads

- This multiple threads executes at same time

- Multithreading used in games,animatins,softwares like VLC


Example : (without multithreading)

[Link]

public class VLC


{
public static void main(String[] args)
{
Video vid = new Video();
[Link]();

Audio aud = new Audio();


[Link]();
}
}

[Link]

public class Video


{
public void playVideo()
{
[Link]("video is playing...");
}
}

[Link]

public class Audio


{
public void playAudio()
{
[Link]("audio is playing...");
}
}

Output :

video is playing...
audio is playing...

Explanation :
- without multithreading video and audio are running separately

- means running one by one and not at same time


thread life cycle

1) New :

Thread is created using Thread class.

But thread is not started yet

2) Runnable :

Thread started using start() method

3) Running :

Thread is in running state using run() method

4) Blocked (Not Runnable) / waiting :

Thread is alive but not running Its in waiting state due to sleep(), wait() methods called

5) Terminated :

Thread is terminated/dead
create threads

We can create threads in two ways,

1) extending Thread class : (it implements Runnable interface internally)

Example :

[Link]

public class Example extends Thread


{
public static void main(String args[])
{
Example e = new Example();
[Link]();
[Link]("THREAD IS STARTED...");
}

public void run()


{
[Link]("THREAD IS RUNNING...");
}
}

Output :

THREAD IS STARTED...
THREAD IS RUNNING...

2) implementing Runnable interface :

Example :
[Link]

public class Example implements Runnable


{
public static void main(String args[])
{
Example e = new Example();
Thread t1 = new Thread(e);
[Link]();
[Link]("THREAD IS STARTED...");
}

public void run()


{
[Link]("THREAD IS RUNNING...");
}
}

Output :

THREAD IS STARTED...
THREAD IS RUNNING...
Question :

1) which way is better extending thread or implements Runnable ?

➔ implements Runnable is better

reason behind it is that java does not supports multiple inheritance.

e.g.

public class A extends B, Thread //compiletime exception


{
//code
}

if we use extends Thread as above it is not possible to extend class B also at same time.

So we have below thing,

public class A extends B implements Runnable


{
//code
}

Now we can extend class B also using implements Runnable.


call start() twice

- It is not possible

Example :

[Link]

public class Example extends Thread


{
public void run()
{
[Link]("running...");
}

public static void main(String args[])


{
Example e = new Example();
[Link]();
[Link](); // Run-time exception
}
}

Output :

Exception in thread "main" [Link]


running...
at [Link]/[Link]([Link])
at [Link]([Link])
call run() twice

- It is possible but you will not get expected result as multhreading gives

Example :

[Link]

public class Example extends Thread


{
public void run()
{
for (int i = 1; i < 5; i++)
{
try
{
[Link](500);
} catch (InterruptedException e)
{
[Link](e);
}
[Link](i);
}
}

public static void main(String args[])


{
Example e1 = new Example();
Example e2 = new Example();
[Link](); // calling run() without start()
[Link](); // calling run() without start()
}
}

Output : (multithreded is not happening here)

1
2
3
4
1
2
3
4

Expected Output is : (multithreded output)

1
1
2
2
3
3
4
4
multi tasking

Example : (single task by single thread)

[Link]

public class Example extends Thread


{
public void run()
{
[Link]("running...");
}

public static void main(String args[])


{
Example t = new Example();
[Link]();
}
}

Output :

running...

Example : (single task by multiple thread)

[Link]

public class Example extends Thread


{
public void run()
{
[Link]("running...");
}

public static void main(String args[])


{
Example t1 = new Example();
[Link]();
Example t2 = new Example();
[Link]();
}
}

Output :

running...
running...
Example : (multiple task by single thread)

Not possible,

Suppose in VLC player we are trying to play audio, video, timer such multiple tasks by single
thread t1

Example : (multiple tasks by multiple threads)

[Link]

public class Example


{
public static void main(String args[])
{
A a = new A();
[Link]();
B b = new B();
[Link]();
}
}

[Link]

public class A extends Thread


{
public void run()
{
[Link]("class A");
}
}
[Link]

public class B extends Thread


{
public void run()
{
[Link]("class B");
}
}

Output :

class A
class B

Explanation : (Thread t1 and t2 running at same time)


sleep() method

- Thread sleeps for specific time and then starts execution again

Example 1 : (main thread)

[Link]

public class Example


{
public static void main(String[] args)
{
for (int i = 1; i <= 3; i++)
{
try
{
[Link](500); // main Thread sleeps for 500 ms
} catch (InterruptedException e)
{
[Link](e);
}
[Link](i);
}
}
}

Output :

1
//Sleep for 500 ms
2
//Sleep for 500 ms
3
Example 2 : (user thread)

[Link]

public class Example extends Thread


{
public static void main(String[] args)
{
Example t1 = new Example();
[Link]();
}

public void run()


{
for (int i = 1; i <= 3; i++)
{
try
{
[Link](500); // Thread sleeps for 500 ms
} catch (InterruptedException e)
{
[Link](e);
}
[Link](i);
}
}
}

Output :

1
//Sleep for 500 ms
2
//Sleep for 500 ms
3
volatile keyword

- as shown in below image one computor may have 2 cpu

public class Test


{
public int counter = 0;

- as shown in below image,

- when thread1 updates value of counter as 7 it gets stored in cache as 7 but not yet in main
memory

- at same time thread2 tries to read value of that variable from main memory but as the value
is not updated yet so thread2 get value as 0 only

- It may create problem in whole calulations in systems like bank applications

- by using volatile keyword data gets stored directly into main memory.

- Means data not get stored in cache now.

- so this problem can be resolved

public class Test


{
public volatile int counter = 0;

}
synchronization

- when multiple threads try to access same resource on same time then we may get wrong
result

- to stop this we need synchronization

- it helps only single thread to access resource

- it can be achieved using,

1) method synchronization

2) block synchronization

Example : (problem without synchronization)

- here all threads t1, t2, t3 tries to access same resource at same time which may give
wrong result
method synchronization

Real world problem :

- Bank has only RS 5000 left today

- Person t1, t2, t3 goes to bank and tried to get RS 5000 at same time.

- Practically this is impossible.

- only one person who goes first should get the rs 5000 and others should get message
like no sufficient balance

- But we may get wrong result like RS 15000 retrived from bank in multithreading program
as all three threads t1, t2, t3 will access same resource.

- to resolve this problem method synchronization is used where only one thread will have
access to resource at one time

Example :
Example : (without method synchronization)

[Link]

public class Example


{
public static void main(String[] args)
{
Table obj = new Table();

Five t1 = new Five(obj);


Two t2 = new Two(obj);

[Link]();
[Link]();
}
}

[Link]

public class Table


{
public void printTable(int n)
{
for(int i=1;i<=10;i++)
{
[Link](n*i);
}
}
}

[Link]

public class Two extends Thread


{
Table t;

public Two(Table t)
{
this.t=t;
}

public void run()


{
[Link](2);
}
}
[Link]

public class Five extends Thread


{
Table t;

public Five(Table t)
{
this.t=t;
}

public void run()


{
[Link](5);
}
}

Output : (output is not as expected)

5
10
15
20
2
25
30
35
40
45
50
4
6
8
10
12
14
16
18
20
Example : (using method synchronization)

[Link]

public class Example


{
public static void main(String[] args)
{
Table obj = new Table();

Five t1 = new Five(obj);


Two t2 = new Two(obj);

[Link]();
[Link]();
}
}

[Link]

public class Table


{
public synchronized void printTable(int n)
{
for(int i=1;i<=10;i++)
{
[Link](n*i);
}
}
}

[Link]

public class Two extends Thread


{
Table t;

public Two(Table t)
{
this.t=t;
}

public void run()


{
[Link](2);
}
}
[Link]

public class Five extends Thread


{
Table t;

public Five(Table t)
{
this.t=t;
}

public void run()


{
[Link](5);
}
}

Output :

5
10
15
20
25
30
35
40
45
50
2
4
6
8
10
12
14
16
18
20
block synchronization

Real world problem :

- here many students walking on road to reach home

- but there is one small bridge.

- If many students try to walk on that ridge it may cause traffic

- so we allow only one student to walt at a time on that bridge

- block synchronization is fast over method synchronization

- because if in above example we use method synchronization then only one student is allowed to
walk on that entire road so it will take so much time to reach each student to their home

Example :
Example : (using method synchronization)

[Link]

public class Example


{
public static void main(String[] args)
{
Table obj = new Table();

Five t1 = new Five(obj);


Two t2 = new Two(obj);

[Link]();
[Link]();
}
}

[Link]

public class Table


{
public synchronized void printTable(int n)
{
[Link]("100 lines of code");

for(int i=1;i<=10;i++)
{
[Link](n*i);
}
}
}

[Link]

public class Two extends Thread


{
Table t;

public Two(Table t)
{
this.t=t;
}

public void run()


{
[Link](2);
}
}
[Link]

public class Five extends Thread


{
Table t;

public Five(Table t)
{
this.t=t;
}

public void run()


{
[Link](5);
}
}

Output : (100 lines are printing gets stuck due to method synchronization)

100 lines of code


2
4
6
8
10
12
14
16
18
20
100 lines of code
5
10
15
20
25
30
35
40
45
50
Example : (using block synchronization)

[Link]

public class Example


{
public static void main(String[] args)
{
Table obj = new Table();

Five t1 = new Five(obj);


Two t2 = new Two(obj);

[Link]();
[Link]();
}
}

[Link]

public class Table


{
public void printTable(int n)
{
[Link]("100 lines of code");

synchronized (this)
{
for (int i = 1; i <= 10; i++)
{
[Link](n * i);
}
}
}
}

[Link]

public class Two extends Thread


{
Table t;

public Two(Table t)
{
this.t=t;
}

public void run()


{
[Link](2);
}
}
[Link]

public class Five extends Thread


{
Table t;

public Five(Table t)
{
this.t=t;
}

public void run()


{
[Link](5);
}
}

Output : (100 lines are printed easily due to block synchronization)

100 lines of code //by thread t1


100 lines of code //by thread t2
2
4
6
8
10
12
14
16
18
20
5
10
15
20
25
30
35
40
45
50
static synchronization

- In static synchronization thread is locked as class level

problem in synchronization :

- Till now we worked with single object as below,

Table obj = new Table();

Five t1 = new Five(obj);


Two t2 = new Two(obj);

[Link]();
[Link]();

as shown above only one tread t1 is accesing printTable method

- what if we have to deal with two object as below,

Table obj1 = new Table();


Five t1 = new Five(obj1);
Two t2 = new Two(obj1);

Table obj2 = new Table();


Five t3 = new Five(obj2);
Two t4 = new Two(obj2);

[Link]();
[Link]();
[Link]();
[Link]();

as shown above tread t1 and tread t3 are accesing printTable method which will give wrong
output because synchronization is failing here.
Example : (using method synchronization)

[Link]

public class Example


{
public static void main(String[] args)
{
Table obj1 = new Table();
Five t1 = new Five(obj1);
Two t2 = new Two(obj1);

Table obj2 = new Table();


Five t3 = new Five(obj2);
Two t4 = new Two(obj2);

[Link]();
[Link]();
[Link]();
[Link]();
}
}

[Link]

public class Table


{
public synchronized void printTable(int n)
{
for(int i=1;i<=10;i++)
{
[Link](n*i);
}
}
}

[Link]

public class Two extends Thread


{
Table t;

public Two(Table t)
{
this.t=t;
}

public void run()


{
[Link](2);
}
}
[Link]

public class Five extends Thread


{
Table t;

public Five(Table t)
{
this.t=t;
}

public void run()


{
[Link](5);
}
}

Output : (gives wrong output)

5
5
10
10
15
20
15
25
30
35
40
45
50
20
25
30
35
40
2
4
6
8
10
12
14
45
50
16
18
20
2
4
6
8
10
12
14
16
18
20
Example : (using static synchronization)

[Link]

public class Example


{
public static void main(String[] args)
{
Table obj1 = new Table();
Five t1 = new Five(obj1);
Two t2 = new Two(obj1);

Table obj2 = new Table();


Five t3 = new Five(obj2);
Two t4 = new Two(obj2);

[Link]();
[Link]();
[Link]();
[Link]();
}
}

[Link]

public class Table


{
public static synchronized void printTable(int n)
{
for(int i=1;i<=10;i++)
{
[Link](n*i);
}
}
}

[Link]

public class Two extends Thread


{
Table t;

public Two(Table t)
{
this.t=t;
}

public void run()


{
[Link](2);
}
}
[Link]

public class Five extends Thread


{
Table t;

public Five(Table t)
{
this.t=t;
}

public void run()


{
[Link](5);
}
}

Output : (gives wrong output)

5
10
15
20
25
30
35
40
45
50
2
4
6
8
10
12
14
16
18
20
2
4
6
8
10
12
14
16
18
20
5
10
15
20
25
30
35
40
45
50
deadlock

- Deadlock in Java is a part of multithreading.

- Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by
another thread and second thread is waiting for an object lock that is acquired by first thread.

- Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
Example :

[Link]

public class Example


{
static String s1 = "vithal";
static String s2 = "krishna";

public static void main(String args[])


{
Demo1 t1 = new Demo1(s1, s2);
Demo2 t2 = new Demo2(s1, s2);
[Link]();
[Link]();
}
}

[Link]

public class Demo1 extends Thread


{
String lock1;
String lock2;

public Demo1(String lock1, String lock2)


{
this.lock1=lock1;
this.lock2=lock2;
}

public void run()


{
synchronized (lock1)
{
[Link]("Thread 1: Holding lock 1...");

try
{
[Link](10);
} catch (InterruptedException e)
{
}
[Link]("Thread 1: Waiting for lock 2...");

synchronized (lock2)
{
[Link]("Thread 1: Holding lock 1 & 2...");
}
}
}
}
[Link]

public class Demo2 extends Thread


{
String lock1;
String lock2;

public Demo2(String lock1, String lock2)


{
this.lock1=lock1;
this.lock2=lock2;
}
public void run()
{
synchronized (lock2)
{
[Link]("Thread 2: Holding lock 2...");

try
{
[Link](10);
} catch (InterruptedException e)
{
}
[Link]("Thread 2: Waiting for lock 1...");

synchronized (lock1)
{
[Link]("Thread 2: Holding lock 1 & 2...");
}
}
}
}

Output : (program is not getting terminated due to deadlock)

Thread 1: Holding lock 1...


Thread 2: Holding lock 2...
Thread 1: Waiting for lock 2...
Thread 2: Waiting for lock 1...
Example : (resolving deadlock by changing order of locks in [Link])

[Link]

public class Example


{
static String s1 = "vithal";
static String s2 = "krishna";

public static void main(String args[])


{
Demo1 t1 = new Demo1(s1, s2);
Demo2 t2 = new Demo2(s1, s2);
[Link]();
[Link]();
}
}

[Link]

public class Demo1 extends Thread


{
String lock1;
String lock2;

public Demo1(String lock1, String lock2)


{
this.lock1=lock1;
this.lock2=lock2;
}

public void run()


{
synchronized (lock1)
{
[Link]("Thread 1: Holding lock 1...");

try
{
[Link](10);
} catch (InterruptedException e)
{
}
[Link]("Thread 1: Waiting for lock 2...");

synchronized (lock2)
{
[Link]("Thread 1: Holding lock 1 & 2...");
}
}
}
}
[Link]

public class Demo2 extends Thread


{
String lock1;
String lock2;

public Demo2(String lock1, String lock2)


{
this.lock1=lock1;
this.lock2=lock2;
}
public void run()
{
synchronized (lock1)
{
[Link]("Thread 2: Holding lock 2...");

try
{
[Link](10);
} catch (InterruptedException e)
{
}
[Link]("Thread 2: Waiting for lock 1...");

synchronized (lock2)
{
[Link]("Thread 2: Holding lock 1 & 2...");
}
}
}
}

Output : (now program terminated successfully)

Thread 1: Holding lock 1...


Thread 1: Waiting for lock 2...
Thread 1: Holding lock 1 & 2...
Thread 2: Holding lock 2...
Thread 2: Waiting for lock 1...
Thread 2: Holding lock 1 & 2...
Inter thread communication

1) wait() : helps in releasing lock of current resource

2) notify() : resumes current thread which is in waiting state

3) notifyAll() : resumes all threads which are in waiting state

Real world example :

1) person has RS 500 in his bank account

2) he go to atm and tried to get rs 1000 from bank but in this case he will get error like
no sufficient balance

3) in this case he should call wait() current retrive cash method

4) and execute another method which will deposit some money in his account

5) then he will call notify() method which will resume retrive method again aso he can get
rs 1000 in his hand
Read input from console

scanner

Example :

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String : ");
String b = [Link]();
[Link]("String is : " + b);
[Link]("---------------------------");
[Link]("Enter an integer : ");
int a = [Link]();
[Link]("Integer is : " + a);
}
}

Output :

Enter a String :
bruce lee
String is : bruce lee
---------------------------
Enter an integer :
12 78
Integer is : 12
BufferedReader

Example :

[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String args[]) throws NumberFormatException, IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter a String : ");
String b = [Link]();
[Link]("String is : " + b);
[Link]("---------------------------");
[Link]("Enter an integer : ");
int a = [Link]([Link]());
[Link]("Integer is : " + a);
}
}

Output :

Enter a String :
bruce lee
String is : bruce lee
---------------------------
Enter an integer :
12
Integer is : 12
Collection
collection framework
Hierarchy of collection and map

Question :

1) Why Map is not part of Collection framework ?

➔ Map is a part of Collection framework but not implements collection interface.

Because Map stores data as key and value pairs.

2) List vs Set ?

List Set
It has index No index
Order of elements preserved Order of elements not preserved
Duplicates allowed Duplicates not allowed

3) What is package name of collection framework ?

➔ [Link]

[Link]
ArrayList

Internal working

1) Default size :
- ArrayList default size is 0 at below line,

ArrayList list=new ArrayList();

- when we add element its size becomes is 10

[Link]("hitesh");

- It creates array of size 10 internally as below,

Example :

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList list = new ArrayList();

[Link]("hitesh");
}
}

Debug mode :
2) size after 10th element :
- when array size gets full till 10

- then it increases array size dynamically by 50%

- as shown old array elements gets copied to new array

- then old array is eligible for garbage collection

Question :
1) why insert / remove elements from ArrayList is time consuming?

➔ Because when we add/ remove any element from arraylist Shifting of elements is done
So if we there are 1000 elements present in arraylist and we do add/remove element then need to shift
those 1000 elements Which takes more time

2) why read elements from ArrayList is faster?

➔ Because ArrayList uses RandomeAccess interface


This is marker interface which contains no method

This hepls to search elements more faster We want 1st element or 1000th elements it will take same
time to fetch
List

Example :

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String args[])
{
List<Integer> list = new ArrayList<Integer>();
[Link](20);
[Link](30);
[Link](10);
[Link](list);
}
}

Output :

[20, 30, 10]


ArrayList initialization

Example : (with [Link]())

[Link]

import [Link];

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> list = new ArrayList<String>([Link]("Pratap", "Peter", "Harsh"));
[Link]("Elements are : " + list);
}
}

Output :

Elements are : [Pratap, Peter, Harsh]

Example : (with normal initialization)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> list = new ArrayList<String>();

[Link]("python");
[Link]("java");
[Link]("sql");
[Link]("Elements are : " + list);
}
}

Output :

Elements are : [python, java, sql]


Reading elements

Example : (with for loop)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<Integer> list = new ArrayList<Integer>();
[Link](14);
[Link](7);

for (int counter = 0; counter < [Link](); counter++)


{
[Link]([Link](counter));
}
}
}

Output :

14
7

Example : (with for each loop)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<Integer> list = new ArrayList<Integer>();
[Link](14);
[Link](7);

for (Integer num : list)


{
[Link](num);
}
}
}

Output :

14
7
add elements

Example : add(element);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> list = new ArrayList<String>();
[Link]("Ram");
[Link]("Shyam");

[Link]("Elements are : " + list);


}
}

Output :

Elements are : [Ram, Shyam]

Example : add(index , element);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("Hi");
[Link]("hello");
[Link]("yo");
[Link]("Test");
[Link]("Elements are :" + al);

// adding string to 3rd position


[Link](3, "Howdy");
[Link]("Elements after adding string Howdy :" + al);

// adding string to 1st position


[Link](0, "Bye");
[Link]("Elements after adding string bye :" + al);
}
}

Output :

Elements are :[Hi, hello, yo, Test]


Elements after adding string Howdy :[Hi, hello, yo, Howdy, Test]
Elements after adding string bye :[Bye, Hi, hello, yo, Howdy, Test]
Example : addAll(list);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("Hi");
[Link]("hello");

[Link]("ArrayList1 elements are :" + al);


// ArrayList2 of String Type
ArrayList<String> al2 = new ArrayList<String>();
[Link]("Text1");
[Link]("Text2");

// Adding ArrayList2 into ArrayList1


[Link](al2);
[Link]("ArrayList1 after addAll :" + al);
}
}

Output :

ArrayList1 elements are :[Hi, hello]


ArrayList1 after addAll :[Hi, hello, Text1, Text2]

Example : addAll(index , list);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("Hi");
[Link]("hello");

[Link]("ArrayList1 elements are :" + al);


// ArrayList2 of String Type
ArrayList<String> al2 = new ArrayList<String>();
[Link]("Text1");
[Link]("Text2");

// Adding ArrayList2 into ArrayList1


[Link](1,al2);
[Link]("ArrayList1 after addAll :" + al);
}
}

Output :

ArrayList1 elements are :[Hi, hello]


ArrayList1 after addAll :[Hi, Text1, Text2, hello]
remove elements

Example : remove(index);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("hitesh");
[Link]("ramesh");
[Link]("suresh");

[Link]("ArrayList elements : " + al);


[Link](2);
[Link]("ArrayList After removing element : " + al);
}
}

Output :

ArrayList elements : [hitesh, ramesh, suresh]


ArrayList After removing element : [hitesh, ramesh]

Example : remove(elements);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("hitesh");
[Link]("ramesh");
[Link]("suresh");

[Link]("ArrayList elements : " + al);


[Link]("ramesh");
[Link]("ArrayList After removing element : " + al);
}
}

Output :

ArrayList elements : [hitesh, ramesh, suresh]


ArrayList After removing element : [hitesh, suresh]
Example : removeAll(list);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{

ArrayList<String> al = new ArrayList<String>();


[Link]("hitesh");
[Link]("ramesh");
[Link]("suresh");

[Link]("ArrayList elements : " + al);

[Link](al);
[Link]("ArrayList After removing elements : " + al);
}
}

Output :

ArrayList elements : [hitesh, ramesh, suresh]


ArrayList After removing elements : []
update elements

Example : set(index);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{

ArrayList<String> al = new ArrayList<String>();


[Link]("hitesh");
[Link]("ramesh");
[Link]("suresh");

[Link]("ArrayList elements : " + al);

[Link](1,"panduranga");
[Link]("ArrayList After update elements : " + al);
}
}

Output :

ArrayList elements : [hitesh, ramesh, suresh]


ArrayList After update elements : [hitesh, panduranga, suresh]

get elements

Example : get(index);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{

ArrayList<String> al = new ArrayList<String>();


[Link]("hitesh");
[Link]("ramesh");
[Link]("suresh");

[Link]("ArrayList elements : " + al);

[Link]("get 2nd element: " + [Link](1));


}
}

Output :

ArrayList elements : [hitesh, ramesh, suresh]


get 2nd element: ramesh
size

Example : size();

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<Integer> al = new ArrayList<Integer>();
[Link]("Initial size: " + [Link]());
[Link](1);
[Link](13);
[Link](45);

[Link]("Size after few additions: " + [Link]());


}
}

Output :

Initial size: 0
Size after few additions: 3

clone

Example : clone();

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
// Adding elements to the ArrayList
[Link]("Apple");
[Link]("Orange");

[Link]("ArrayList: " + al);


ArrayList<String> a2 = (ArrayList<String>) [Link]();
[Link]("cloned (copy) ArrayList: " + a2);
}
}

Output :

ArrayList: [Apple, Orange]


cloned (copy) ArrayList: [Apple, Orange]
get index

Example : indexOf(element);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("AB");
[Link]("CD");
[Link]("EF");
[Link]("EF");

[Link]("Index of 'EF': " + [Link]("EF"));


[Link]("Index of ‘hitesh’ : " + [Link]("hitesh"));
}
}

Output :

Index of 'EF': 2
Index of ‘hitesh’ : -1

Example : lastIndexOf(element);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("AB");
[Link]("CD");
[Link]("EF");
[Link]("EF");

[Link]("Last occurrence of element is : " + [Link]("EF"));


}
}

Output :

Last occurrence of element is : 3


clear

Example : clear(list);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al1 = new ArrayList<String>();
[Link]("abc");
[Link]("xyz");
[Link]("ArrayList contents : " + al1);
[Link]();
[Link]("ArrayList after clear : " + al1);
}
}

Output :

ArrayList contents : [abc, xyz]


ArrayList after clear : []

check ArrayList empty

Example : isEmpty();

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("Is ArrayList Empty: " + [Link]());

[Link]("abc");
[Link]("xyz");

[Link]("Is ArrayList Empty: " + [Link]());


}
}

Output :

Is ArrayList Empty: true


Is ArrayList Empty: false
contains

Example : contains(element);

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("pen");
[Link]("pencil");
[Link]("ink");
[Link]("notebook");
[Link]("ArrayList contains 'ink pen': " + [Link]("ink pen"));
[Link]("ArrayList contains 'pen': " + [Link]("pen"));
[Link]("ArrayList contains 'book': " + [Link]("book"));
}
}

Output :

ArrayList contains 'ink pen': false


ArrayList contains 'pen': true
ArrayList contains 'book': false

subList

Example : subList(startIndex, endIndex);

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("Steve");
[Link]("Justin");
[Link]("Ajeet");
[Link]("John");

[Link]("Original ArrayList Content: " + al);


ArrayList<String> al2 = new ArrayList<String>([Link](1, 3));
[Link]("SubList stored in ArrayList: " + al2);

List<String> list = [Link](1, 3);


[Link]("SubList stored in List: " + list);
}
}

Output :

Original ArrayList Content: [Steve, Justin, Ajeet, John]


SubList stored in ArrayList: [Justin, Ajeet]
SubList stored in List: [Justin, Ajeet]
swap

Example : [Link](list, index1, index2);

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("Sachin");
[Link]("Rahul");
[Link]("Saurav");

[Link]("ArrayList contents : " + al);

[Link](al, 1, 2);
[Link]("ArrayList after swap : " + al);
}
}

Output :

ArrayList contents : [Sachin, Rahul, Saurav]


ArrayList after swap : [Sachin, Saurav, Rahul]

sort

Example : [Link](list);

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
[Link]("hitesh");
[Link]("abhijit");
[Link]("rahul");

[Link]("ArrayList contents : " + al);

[Link](al);
[Link]("ArrayList after sort : " + al);
}
}

Output :

ArrayList contents : [hitesh, abhijit, rahul]


ArrayList after sort : [abhijit, hitesh, rahul]
comparable interface

- compares single element

- uses compareTo() method

Example : (sorting int values)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<Laptop> list = new ArrayList<>();
[Link](new Laptop("lenovo", 8, 50000));
[Link](new Laptop("dell", 4, 30000));
[Link](new Laptop("apple", 16, 80000));
[Link](list);
[Link]("\nList after sorting : ");
for (Laptop l : list)
{
[Link]("list is : " + l);
}
}
}
[Link]

public class Laptop implements Comparable<Laptop>


{
private String brand;
private int ram;
private int price;

public Laptop(String brand, int ram, int price)


{
[Link] = brand;
[Link] = ram;
[Link] = price;
}

public String getBrand()


{
return brand;
}

public void setBrand(String brand)


{
[Link] = brand;
}

public int getRam()


{
return ram;
}

public void setRam(int ram)


{
[Link] = ram;
}

public int getPrice()


{
return price;
}

public void setPrice(int price)


{
[Link] = price;
}

@Override
public String toString()
{
return "Laptop [brand=" + brand + ", ram=" + ram + ", price=" + price + "]";
}

@Override
public int compareTo(Laptop lap2)
{
if ([Link]() < [Link]())
{
return -3;
}
if ([Link]() == [Link]())
{
return 0;
}
return 2;
}
}
Output :

List after sorting :


list is : Laptop [brand=dell, ram=4, price=30000]
list is : Laptop [brand=lenovo, ram=8, price=50000]
list is : Laptop [brand=apple, ram=16, price=80000]

Example : (sorting String values)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<Laptop> list = new ArrayList<>();
[Link](new Laptop("lenovo", 8, 50000));
[Link](new Laptop("dell", 4, 30000));
[Link](new Laptop("apple", 16, 80000));
[Link](list);
[Link]("\nList after sorting : ");
for (Laptop l : list)
{
[Link]("list is : " + l);
}
}
}
[Link]

public class Laptop implements Comparable<Laptop>


{
private String brand;
private int ram;
private int price;

public Laptop(String brand, int ram, int price)


{
[Link] = brand;
[Link] = ram;
[Link] = price;
}

public String getBrand()


{
return brand;
}

public void setBrand(String brand)


{
[Link] = brand;
}

public int getRam()


{
return ram;
}

public void setRam(int ram)


{
[Link] = ram;
}

public int getPrice()


{
return price;
}

public void setPrice(int price)


{
[Link] = price;
}

@Override
public String toString()
{
return "Laptop [brand=" + brand + ", ram=" + ram + ", price=" + price + "]";
}

@Override
public int compareTo(Laptop lap2)
{
return [Link]().compareTo([Link]()); // this compareTo is String method
}
}

Output :

List after sorting :


list is : Laptop [brand=apple, ram=16, price=80000]
list is : Laptop [brand=dell, ram=4, price=30000]
list is : Laptop [brand=lenovo, ram=8, price=50000]
comparator interface

- compares multiple elements

- uses compare() method

Example : (sorting int and String values together)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String args[])
{
ArrayList<Laptop> list = new ArrayList<>();
[Link](new Laptop("lenovo", 8, 50000));
[Link](new Laptop("dell", 4, 30000));
[Link](new Laptop("apple", 16, 80000));

[Link](list, new Price());


[Link]("\nList after sorting as per price : ");
for (Laptop l : list)
{
[Link]("list is : " + l);
}

[Link]("----------------------");
[Link](list, new Brand());
[Link]("\nList after sorting as per Brand : ");
for (Laptop l : list)
{
[Link]("list is : " + l);
}
}
}

[Link]

import [Link];

public class Price implements Comparator<Laptop>


{
public int compare(Laptop l1, Laptop l2)
{
if ([Link]() < [Link]())
{
return -3;
}
if ([Link]() == [Link]())
{
return 0;
}
return 2;
}
}

[Link]
import [Link];

public class Brand implements Comparator<Laptop>


{
public int compare(Laptop l1, Laptop l2)
{
return [Link]().compareTo([Link]());
}
}
[Link]

public class Laptop


{
private String brand;
private int ram;
private int price;

public Laptop(String brand, int ram, int price)


{
[Link] = brand;
[Link] = ram;
[Link] = price;
}

public String getBrand()


{
return brand;
}

public void setBrand(String brand)


{
[Link] = brand;
}

public int getRam()


{
return ram;
}

public void setRam(int ram)


{
[Link] = ram;
}

public int getPrice()


{
return price;
}

public void setPrice(int price)


{
[Link] = price;
}

@Override
public String toString()
{
return "Laptop [brand=" + brand + ", ram=" + ram + ", price=" + price + "]";
}
}

Output :

List after sorting as per price :


list is : Laptop [brand=dell, ram=4, price=30000]
list is : Laptop [brand=lenovo, ram=8, price=50000]
list is : Laptop [brand=apple, ram=16, price=80000]
----------------------

List after sorting as per Brand :


list is : Laptop [brand=apple, ram=16, price=80000]
list is : Laptop [brand=dell, ram=4, price=30000]
list is : Laptop [brand=lenovo, ram=8, price=50000]
vector

Internal working

1) Default size :
- Vector default size is 0

2) size after 10th element :


- when array size gets full till 10

- then it increases array size dynamically by 100%

Question :

1) ArrayList vs Vector?

ArrayList Vector
ArrayList next capacity is increased by 50% Vector next capacity is increased by 100%
methods are not synchronized methods are synchronized
LinkedList

- LinkedList is implemented using the doubly linked list data structure

- In doubly LinkedList there are next and previous pointers so we can traverse in both
direction

- It also has few disadvantages like the nodes cannot be accessed directly instead we need to
start from the head and follow through the link to reach to a node we wish to access (in short
performance of searching is bad as compared to ArrayList)

- In LinkedList if we want to add,change,delete an element then instead of shifting position of


elements it will just change pointer of nodes

Note :

All methods in LinkedList are same as in ArrayList because they both implements same
interface List But few methods are different we will discuss them.

singly linkedList

- Head contains address of first node

- Each node contains data and address of next node

- Last node contains data and address null as it is not pointing to any node
doubly linkedList

- traverse in both direction

- LinkedList class uses Doubly LinkedList internally

- Head contains address of first node

- Each node contains data, address of previous node, address of next node

- Last node contains data, address of previous node, address of next node as null as next is
not pointing to any node

Example :

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
LinkedList<String> list = new LinkedList<String>();
[Link]("Apple");
[Link]("Orange");
[Link]("Mango");
for (String a : list)
{
[Link](a);
}
}
}

Output :

Apple
Orange
Mango
Question :

1) ArrayList vs LinkedList?

ArrayList LinkedList
Uses dynamic array internally Uses doubly linkedList internally
Add/remove elemetns is slow Add/remove elemetns is fast
Search element faster Search element slower
Memory consumption is less Memory consumption is more
Works as List Works as List and queue

2) Can ArrayList and LinkedList store null values ?


➔ YES
HashSet

- HashSet implements Set interface

- It internally uses HashMap

Internal working

- HashSet internally uses HashMap

- when we use below line,

[Link]("Apple");

- HashMap uses key = “ram” and value = some predefined Object

- Refer HashMap chapter for HashMap internal working

Example :

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashSet hset = new HashSet();
[Link]("ram");
[Link](hset);
}
}

Output :

[ram]
Debug mode :

As shown below “ram” is getting stored as a key in HashMap,


features

1) order of elements not preseved

2) elements are not duplicate

3) null values allowed

but if you enter more than one null value it will display only one

4) elements are not synchronized

Example : (elements not ordered)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashSet<String> hset = new HashSet<String>();
[Link]("Apple");
[Link]("Mango");
[Link]("Grapes");
[Link]("Orange");
[Link]("Fig");
[Link]("hashset contents : " + hset);
}
}

Output :

hashset contents : [Apple, Grapes, Fig, Mango, Orange]

Example : (elements not duplicate)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashSet<String> hset = new HashSet<String>();
[Link]("Apple");
[Link]("Apple");

[Link]("hashset contents : " + hset);


}
}

Output :

Example
hashset :contents
(elements: can be null)
[Apple]
Example : (elements can be null)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashSet<String> hset = new HashSet<String>();
[Link]("Apple");
[Link](null);
[Link](null);
[Link]("hashset contents : " + hset);
}
}

Output :

hashset contents : [null, Apple]


HashMap

- HashMap implements Map interface

- Data stored in <key, value> format

Internal working

1) Buckets :
- HashMap data stored inside buckets

- these buckets are stored in Heap memory

- default size of buckets is 16

2) LinkedList :
- data inside buckets are stored as LinkedList
3) Loading factor :
- default size of loading factor is 0.75

- as default bucket size is 16

- threshold = 0.75 x 16 = 12 (i.e. 75% of 16)

4) Rehashing :
- when 12 buckets get filled up

- then jvm increases size of bucket to its double

- here it will become 32 (i.e.16 * 2)

As it reached to 12 th index

Now it will increase size to double i.e. 32

As shown in below image,


5) Hash collision :
- as hashCode of key is genereated in hashmap

- so if any keys having same hashcodes

- then its called as Hash collision

- because as hashcode is same bucket index will also same

- e.g. “FB”.hashCode() = 1256

“EA”.hashCose() = 1256

So the bucket index will also be same say 4 for both of them

- here JVM might get confused to which data store at index 4 ?


6) equals() method :
- equals() method is the solution for hash collision

- e.g. “FB”.equals(“EA”);

As FB and EA are not same values

So both of them will get stored in bucket at index 4 In linkedList manner

- e.g. “FB”.equals(“FB”);

As FB and FB are same values

So only of them which latest value gets replaced in linkedList manner

Diagram of HashMap working :


Example 1 : (without hash collision)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashMap<String, String> hmap = new HashMap<>();
[Link]("FB", "hitesh");
}
}

Internal working :
Step 1: generate hashCode()

hashcode = “FB”.hashCode(); //[Link]();

hashcode = 1256

Step 2: generate bucket index

Bucket index = “FB”.hashCode() & (16 – 1) //[Link]() & (bucketLength - 1)

Bucket index = 1256 & (16 – 1)

Bucket index = 4

Step 3: hash collision occurred?

NO

Step 4: insert data in LinkedList as first node

Data will get insert at index 4 of bucket

as shown below,
Example 2 : (with hash collision but without equals())

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashMap<String, String> hmap = new HashMap<>();
[Link]("FB", "hitesh");
[Link]("LD", "manish");
[Link]("EA", "ramesh");
}
}

Internal working :
Step 1: generate hashCode()

hashcode = “FB”.hashCode(); //[Link]();

hashcode = 1256

------------------------------

hashcode = “LD”.hashCode(); //[Link]();

hashcode = 2106

------------------------------

hashcode = “EA”.hashCode(); //[Link]();

hashcode = 1256

Step 2: generate bucket index

Bucket index = “FB”.hashCode() & (16 – 1) //[Link]() & (bucketLength - 1)

Bucket index = 1256 & (16 – 1)

Bucket index = 4
------------------------------

Bucket index = “LD”.hashCode() & (16 – 1) //[Link]() & (bucketLength - 1)

Bucket index = 2106 & (16 – 1)

Bucket index = 7
------------------------------

Bucket index = “EA”.hashCode() & (16 – 1) //[Link]() & (bucketLength - 1)

Bucket index = 1256 & (16 – 1)

Bucket index = 4
Step 3: hash collision occurred?

YES (as hashCode of FB and EA is same i.e. 1256)

Step 4: check key equals() or not?

NO

Step 4: insert data in LinkedList as next node

FB and EA get insert at index 4

& LD get insert at index 7 of bucket as shown below,


Example 3 : (with hash collision and with equals())

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashMap<String, String> hmap = new HashMap<>();
[Link]("FB", "hitesh");
[Link]("LD", "manish");
[Link]("FB", "ramesh");
}
}

Internal working :
Step 1: generate hashCode()

hashcode = “FB”.hashCode(); //[Link]();

hashcode = 1256

------------------------------

hashcode = “LD”.hashCode(); //[Link]();

hashcode = 2106

------------------------------

hashcode = “FB”.hashCode(); //[Link]();

hashcode = 1256

Step 2: generate bucket index

Bucket index = “FB”.hashCode() & (16 – 1) //[Link]() & (bucketLength - 1)

Bucket index = 1256 & (16 – 1)

Bucket index = 4
------------------------------

Bucket index = “LD”.hashCode() & (16 – 1) //[Link]() & (bucketLength - 1)

Bucket index = 2106 & (16 – 1)

Bucket index = 7
------------------------------

Bucket index = “FB”.hashCode() & (16 – 1) //[Link]() & (bucketLength - 1)

Bucket index = 1256 & (16 – 1)

Bucket index = 4
Step 3: hash collision occurred?

YES (as hashCode of FB and FB is same i.e. 1256)

Step 4: check key equals() or not?

YES (as FB came twice so “FB”.equals(“FB”) = true)

Step 4: insert data in LinkedList as existing node

FB get replaced at index 4 with value = ramesh

& LD get insert at index 7 of bucket as shown below,


Debug hashmap

Example 1 : (keys with different hashcode)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashMap hmap = new HashMap();
[Link](101, "hit");
[Link](102, "man");
[Link](hmap);
}
}

Output :

{101=hit, 102=man} Example : (elements

Debug mode :

1) creating hashmap :

HashMap hmap = new HashMap();

loadFactor is 0.75

threshold is 0
2) creating hashmap :

[Link](101, "hit");

loadFactor is 0.75

threshold is 12 (i.e. 75% of 16)

just open table, (16 buckets created)

Value is inserted at bucket index 5,


3) creating hashmap :

[Link](102, "man");

loadFactor is 0.75

threshold is 12 (i.e. 75% of 16)

Value is inserted at bucket index 6,


Example 2 : (keys with same hashcode)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashMap hmap = new HashMap();
[Link]("FB", "hit");
[Link]("EA", "man");
[Link](hmap);
}
}

Output :

{FB=hit, EA=man} Example : (elements

Debug mode :
- as key FB and Ea has same hashCode

- gets stored in same bucket index as next node of LinkedList


Example 3 : (bucket size increases when reaches 0.75 of bucket)

[Link]

import [Link];

public class Test


{
public static void main(String args[])
{
HashMap hmap = new HashMap();
[Link](101, "hit");
[Link](102, "man");
[Link](103, "tom");
[Link](104, "jam");
[Link](105, "yep");
[Link](106, "chao");
[Link](107, "kim");
[Link](108, "bruce");
[Link](113, "jackie");
[Link](115, "jet");
[Link](116, "scot");
[Link](125, "tony");
[Link](168, "kavya");
[Link](hmap);
}
}

Output :

Example168=kavya,
{101=hit, 102=man, 103=tom, 104=jam, : (elements
105=yep, 106=chao, 107=kim,
108=bruce, 113=jackie, 115=jet, 116=scot, 125=tony}

Debug mode :
- Here size of bucket gets double 16 *2 = 32 and threshold = 24 (i.e. 12 x 2 =24)
HashTable

- HashTable implements Map interface

- Same has HashMap but its methods are synchronized

- Data stored in <key, value> format

features

1) order of elements not preseved

2) keys are not duplicate but values can be duplicate

3) null key and values not allowed

4) elements are synchronized

Example : (elements not ordered)

[Link]

import [Link].*;

public class Test


{
public static void main(String args[])
{
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
[Link](101, " ajay");
[Link](102, "Rahul");
[Link](106, "Rahul");
[Link](ht);
}
}

Output :

{106=Rahul, 102=Rahul, 101= ajay}


Example : (keys not duplicate)

[Link]

import [Link].*;

public class Test


{
public static void main(String args[])
{
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
[Link](101, " ajay");
[Link](101, "Rahul");
[Link](ht);
}
}

Output :

{101=Rahul}

Example : (values can be duplicate)

[Link]

import [Link].*;

public class Test


{
public static void main(String args[])
{
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
[Link](101, " ajay");
[Link](102, "ajay");
[Link](ht);
}
}

Output :

{102=ajay, 101= ajay}


Example : (null key and value not allowed)

[Link]

import [Link].*;

public class Test


{
public static void main(String args[])
{
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
[Link](null, "ajay");
[Link](106, null);
[Link](ht);
}
}

Output :

Exception in thread "main" [Link]: Cannot invoke


"[Link]()" because "key" is null
at [Link]/[Link]([Link])
at [Link]([Link])

Question :

1) HashMap vs HashSet ?

HashMap HashTable
order of elements not preseved order of elements not preseved
keys are not duplicate but keys are not duplicate but
values can be duplicate values can be duplicate
null key and values allowed null key and values not allowed
elements are not synchronized elements are synchronized
TreeSet

- Elements are already sorted in TreeSet

Example :

[Link]

import [Link].*;

public class Test


{
public static void main(String args[])
{
TreeSet ts = new TreeSet();

// Add elements to the tree set


[Link]("narsimha");
[Link]("vithal");
[Link]("pandurang");
[Link]("krishna");
[Link]("shripad");
[Link]("yogananda");
[Link](ts);
}
}

Output :

[krishna, narsimha, pandurang, shripad, vithal, yogananda]


TreeMap

- key/values are already sorted in TreeMap

Example :

[Link]

import [Link].*;

public class Test


{
public static void main(String args[])
{
TreeMap tm = new TreeMap();

// Put elements to the map


[Link]("Zara", new Double(3434.34));
[Link]("Mahnaz", new Double(123.22));
[Link]("Ayan", new Double(1378.00));
[Link]("Daisy", new Double(99.22));
[Link]("Qadir", new Double(-19.08));
[Link](tm);
}
}

Output :

{Ayan=1378.0, Daisy=99.22, Mahnaz=123.22, Qadir=-19.08, Zara=3434.34}


1.8
Functional interface

- In functional interface only single abstract method is allowed

- It can have static and normal methods too

- Helps to achieve functional programming approach

- Helps to use lambda expressions

Example : (normal interface)

[Link]

public class Test implements Sample


{
public static void main(String[] args)
{
Test t = new Test();
t.m1();
t.m2();
}

@Override
public void m1()
{
[Link]("executing m1...");
}

@Override
public String m2()
{
[Link]("executing m2...");
return "done";
}
}

[Link]

public interface Sample


{
public void m1();

public String m2();


}

Output :

executing m1...
executing m2...
Example : (functional interface)

[Link]

public class Test implements Sample


{
public static void main(String[] args)
{
Test t = new Test();
t.m1();
}

@Override
public void m1()
{
[Link]("executing m1...");
}
}

[Link]

public interface Sample


{
public void m1();
}

Output :

executing m1...
@FunctionalInterface

- @FunctionalInterface will give compile time error if we add more than one abstract
method

- It can have static and normal methods too

Example : (gives error when adding more than one abstract method)

[Link]

public class Test implements Sample


{
public static void main(String[] args)
{
Test t = new Test();
t.m1();
}

@Override
public void m1()
{
[Link]("executing m1...");
}
}

[Link]

@FunctionalInterface
public interface Sample
{
public void m1();
public void m2(); //compile time error
}

Output :

Compile time error!


Example : (can have static/default method)

[Link]

public class Test implements Sample


{
public static void main(String[] args)
{
Test t = new Test();
t.m1();
t.m3();
}

@Override
public void m1()
{
[Link]("executing m1...");
}
}

[Link]

@FunctionalInterface
public interface Sample
{
public void m1();

// public void m2(); //compile time error

public default void m3()


{
[Link]("executing default m3...");
}
}

Output :

executing m1...
executing default m3...

Question :

1) can Functional interface extend another normal interface or functional interface ?

➔ NO (as it allows only one abstract method)

2) why Functional interface allows only one abstract method?

➔ Otherwise lambda expression will get confused which method to call. (we will learn this
in next chapter)
Lambda expression

- It is an enhanced version of Anonymous class

- works only with functional interface

Example : (normal class)

[Link]

public class Test implements Sample


{
public static void main(String[] args)
{
Test t = new Test();
[Link]();
}

@Override
public void show()
{
[Link]("executing show...");
}
}

[Link]

public interface Sample


{
public void show();
}

Output :

executing show...
Example : (Anonymous class)

[Link]

public class Test


{
public static void main(String[] args)
{
Sample obj = new Sample()
{
@Override
public void show()
{
[Link]("executing show...");
}
};

[Link]();
}
}

[Link]

public interface Sample


{
public void show();
}

Output :

executing show...
Example : (Anonymous class)

[Link]

public class Test


{
public static void main(String[] args)
{
Sample obj = new Sample()
{
public void show()
{
[Link]("executing show...");
}

public void print(int x)


{
[Link]("executing print... "+x);
}
};

[Link]();
[Link](14);
}
}

[Link]

public interface Sample


{
public void show();
public void print(int x);
}

Output :

executing show...
executing print... 14
How to create lambda expression ?

1) Remove access-modifier

2) Remove return type

3) Remove method name

4) add ->

Example 1 : (no parameter)

Example 2 : (with parameter)

Example 3 : (with parameter)

Example 4 : (we can remove curly braces {} and return keyword if single statement is used)
Example : (Lambda expression with no parameter method)

[Link]

public class Test


{
public static void main(String[] args)
{
Sample obj = () ->
{
[Link]("executing show...");
};

[Link]();
}
}

[Link]

public interface Sample


{
public void show();
}

Output :

executing show...

Example : (Lambda expression with parameterized method)

[Link]

public class Test


{
public static void main(String[] args)
{
Sample obj = (a, b) ->
{
return a + b;
};

[Link]("sum is : " + [Link](10, 20));


}
}

[Link]

public interface Sample


{
public int sum(int a,int b);
}

Output :

sum is : 30
Example : (Lambda expression with parameterized method)

[Link]

public class Test


{
public static void main(String[] args)
{
Sample s = (a, b) -> a + b;

[Link]("sum is : " + [Link](10, 20));


}
}

[Link]

public interface Sample


{
public int sum(int a,int b);
}

Output :

sum is : 30

Example : (Lambda expression with parameterized method)

[Link]

public class Test


{
public static void main(String[] args)
{
Sample s = (a) -> [Link]();

[Link]("length is : " + [Link]("hello"));


}
}

[Link]

public interface Sample


{
int getData(String str);
}

Output :

length is : 5
Example : (Lambda expression with parameterized method)

[Link]

public class Test


{
public static void main(String[] args)
{
Sample person = (message) ->
{
String str1 = "I would like to say, ";
String str2 = str1 + message;
return str2;
};
[Link]([Link]("time is precious."));
}
}

[Link]

public interface Sample


{
String getData(String str);
}

Output :

I would like to say, time is precious.

Example : (Lambda expression with forEach method)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
[Link]("ankit");
[Link]("mayank");

[Link]((n) -> [Link](n));


}
}

Output :

ankit
mayank
Example : (Lambda expression with multi-threading)

[Link]

public class Test


{
public static void main(String[] args)
{
Runnable r1 = () ->
{
[Link]("Thread 1 is running...");
};
Thread t1 = new Thread(r1);
[Link]();

Runnable r2 = () ->
{
[Link]("Thread 2 is running...");
};
Thread t2 = new Thread(r2);
[Link]();
}
}

Output :

Thread 1 is running...
Thread 2 is running...
forEach() method

- helps to iterate elements

Example :

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();

[Link]("krishna");
[Link]("pandurang");

for(String str:list)
{
[Link]("element is : "+str);
}
}
}

Output :

element is : krishna
element is : pandurang

Example : (Lambda expression with forEach method)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
[Link]("krishna");
[Link]("pandurang");

[Link]((str) -> [Link]("element is : "+str));


}
}

Output :

element is : krishna
element is : pandurang
Example : (method reference with forEach method)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
[Link]("Krishna");
[Link]("Pandurang");

[Link]([Link]::println);
}
}

Output :

Krishna
Pandurang
method reference

- method reference is used to refer method of functional interface

- It is compact and easy form of lambda expression

- Each time when you are using lambda expression to just referring a method, you can
replace your lambda expression with method reference

Syntax : (static method)

Interface obj=Class::method

Syntax : (instance method)

Class obj1 = new Class();


Interface obj2= obj1::method

Syntax : (constructor)

Interface obj1 = Class::new;


Class obj2= [Link]
Example : (method reference for static method)

[Link]

public class Test


{
public static void main(String[] args)
{
Sample sample = Test::display;
[Link]();
}

public static void display() // instance method


{
[Link]("displaying...");
}
}

[Link]

public interface Sample


{
public void show();
}

Output :

displaying...
Example : (method reference for instance method)

[Link]

public class Test


{
public static void main(String[] args)
{
Test test = new Test();
Sample sample = test::display;
[Link]();
}

public void display() // instance method


{
[Link]("displaying...");
}

[Link]

public interface Sample


{
public void show();
}

Output :

displaying...
Example : (constructor reference)

[Link]

public class Test


{
public Test()
{
[Link]("this is constructor...");
}

public static void main(String[] args)


{
Sample sample = Test::new;
Test test = [Link]();
[Link]();
}

public void display()


{
[Link]("displaying...");
}
}

[Link]

public interface Sample


{
public Test show();
}

Output :

this is constructor...
displaying...
Optional class

- It is used to handle NullPointerException

Example : (without optional class)

[Link]

public class Test


{
public static void main(String[] args)
{
String str=null;

[Link]([Link]());
}
}

Output :

Exception in thread "main" [Link]: Cannot invoke


"[Link]()" because "str" is null
at [Link]([Link])

Example : (using optional class)

[Link]

import [Link];

public class Test


{
public static void main(String[] args)
{
String str = null;

Optional<String> checkNull = [Link](str);

if ([Link]())
{
String word = [Link]();
[Link](word);
} else
{
[Link]("word is null");
}
}
}

Output :

word is null
Example : (using optional class)

[Link]

import [Link];

public class Test


{
public static void main(String[] args)
{
String str = null;

Optional<String> checkNull = getData(str);

if ([Link]())
{
String word = [Link]();
[Link](word);
} else
{
[Link]("word is null");
}
}

public static Optional<String> getData(String str)


{
return [Link](str);
}
}

Output :

word is null
Stream API

- Streams read input from collections and perform various operations on it

forEach()

- helps to iterate list

Example : (normal for each loop arrayList)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<String> list = new ArrayList();

[Link]("vithal");
[Link]("krishna");

for (String s : list)


{
[Link](s);
}
}
}

Output :

vithal
krishna

Example : (using stream forEach arrayList)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<String> list = new ArrayList();

[Link]("vithal");
[Link]("krishna");

[Link]()
.forEach(s->[Link](s));
}
}

Output :

vithal
krishna
Example : (normal for each loop hashmap)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
Map<String, String> hmap = new HashMap();

[Link]("vithal", "pandharpur");
[Link]("krishna", "mathura");
[Link]("vishnu", "vaikuntha");

for ([Link]<String, String> entry : [Link]())


{
[Link]("Key = " + [Link]() + ", Value = " + [Link]());
}
}
}

Output :

Key = vishnu, Value = vaikuntha


Key = krishna, Value = mathura
Key = vithal, Value = pandharpur

Example : (using stream forEach hashmap)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
Map<String, String> hmap = new HashMap();

[Link]("vithal", "pandharpur");
[Link]("krishna", "mathura");
[Link]("vishnu", "vaikuntha");

[Link]()
.stream()
.forEach(s->[Link](s));

}
}

Output :

vishnu=vaikuntha
krishna=mathura
vithal=pandharpur
filter()

- replacement for if else condition

Example : (normal if else)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<String> list = new ArrayList();

[Link]("vithal");
[Link]("krishna");
[Link]("vishnu");

for (String s : list)


{
if([Link]("v"))
{
[Link](s);
}

}
}
}

Output :

vithal
vishnu

Example : (using filter)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<String> list = new ArrayList();

[Link]("vithal");
[Link]("krishna");
[Link]("vishnu");

[Link]()
.filter(s->[Link]("v"))
.forEach(s->[Link](s));
}
}

Output :

vithal
vishnu
Example : (find values less than 20)

[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<>();
[Link](12);
[Link](20);
[Link](6);
[Link](82);

[Link]()
.filter(i -> i < 20)
.collect([Link]())
.forEach(s->[Link](s));;
}
}

Output :

12
6
Example : (real world example)
- find out employees who are eligible for paying tax

i..e employess having salary greater than 5 lac

[Link]

public class Employee


{
private int id;
private String name;
private String dept;
private long salary;

public Employee(int id, String name, String dept, long salary)


{
super();
[Link] = id;
[Link] = name;
[Link] = dept;
[Link] = salary;
}

public int getId()


{
return id;
}

public void setId(int id)


{
[Link] = id;
}

public String getName()


{
return name;
}

public void setName(String name)


{
[Link] = name;
}

public String getDept()


{
return dept;
}

public void setDept(String dept)


{
[Link] = dept;
}

public long getSalary()


{
return salary;
}

public void setSalary(long salary)


{
[Link] = salary;
}

}
[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<Employee> list = new ArrayList();
[Link](new Employee(176,"vithal","IT",600000));
[Link](new Employee(456,"krishna","civil",900000));
[Link](new Employee(268,"panduranga","mechanics",400000));

[Link]()
.filter(emp->[Link]()>500000) //if([Link]()>500000)
.collect([Link]())
.forEach(s->[Link]([Link]()+" - "+[Link]()));
}

Output :

vithal - 600000
krishna - 900000
map()

- map() is used for data transformation

Example : (find sqaure of each element)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<>();
[Link](12);
[Link](20);

[Link]()
.map(i -> i * i)
.forEach(i -> [Link]("square of element is : " + i));
}
}

Output :

square of element is : 144


square of element is : 400
flatMap()

- flatMap() is used for data transformation and fatten array

Example : (find sqaure of each element)

[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<>();
[Link](12);
[Link](6);

[Link]()
.flatMap(i->[Link](i*i))
.forEach(i->[Link]("square of element is : "+i));
}
}

Output :

square of element is : 144


square of element is : 400

Example : (flatten array)

[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<Integer> list1 = [Link](1, 2, 3);
List<Integer> list2 = [Link](4, 5, 6);
List<Integer> list3 = [Link](7, 8, 9);
List<List<Integer>> listOfLists1 = [Link](list1, list2, list3);
[Link]("Before flatten : " + listOfLists1);
List<Integer> newList1 = [Link]().flatMap(x -> [Link]()).collect([Link]());
[Link]("After flatten : " + newList1);
}
}

Output :

Before flatten : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


After flatten : [1, 2, 3, 4, 5, 6, 7, 8, 9]
reduce()

- returns data as a single value

Example : (find sqaure of each element)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<>();
[Link](12);
[Link](20);

int sum = [Link]().reduce(0, (ans, i) -> ans + i);


[Link]("sum of elements is : " + sum);

}
}

Output :

sum of elements is : 32

Explanation :
reduce(0, (ans, i) -> ans + i); //here 0 is the initial value

0+12 = 12

12+20 = 32
min() max()

Example : (find min and max element)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<>();
[Link](12);
[Link](20);
[Link](6);
[Link](82);
[Link](46);

int minValue = [Link]().min((x, y) -> [Link](y)).get();


[Link]("min value is : " + minValue);

int maxValue = [Link]().max((x, y) -> [Link](y)).get();


[Link]("max value is : " + maxValue);
}
}

Output :

min value is : 6
max value is : 82
combination of methods

Example : (find sum of sqaure of elements less than 20)

[Link]

import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<>();
[Link](12);
[Link](20);
[Link](6);
[Link](82);
[Link](46);

int sum = [Link]().filter(i -> i < 20).map(i -> i * i).reduce(0, (ans, i) -> ans + i);
[Link]("sum is : " + sum);
}
}

Output :

sum is : 180 //(12²)+(6²)=180


Collectors class

- helps to save result data into collections like list, set

Example : (find values less than 20)

[Link]

import [Link];
import [Link];
import [Link];

public class Test


{
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<>();
[Link](12);
[Link](20);
[Link](6);

List<Integer> list2 = [Link]().filter(i -> i < 20).collect([Link]());


[Link]("elements less than 20 : " + list2);
}
}

Output :

elements less than 20 are : [12, 6]


static and default methods

- static and default methods were not allowed before java 8 in interface

- but now it is allowed

Example :

[Link]

public class Test implements Sample


{
public static void main(String[] args)
{
Test t = new Test();
t.m1("welcome");
t.m2();
Sample.m3();
}

@Override
public void m1(String msg)
{
[Link](msg);
}
}

[Link]

public interface Sample


{
void m1(String msg);

default void m2()


{
[Link]("this is default method");
}

static void m3()


{
[Link]("this is static method");
}
}

Output :

welcome
this is default method
this is static method

You might also like