Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Core Java All Notes

The document is an index for a core Java tutorial covering various topics such as arrays, classes, inheritance, polymorphism, exception handling, collections, and more. It provides a structured outline of chapters along with key concepts and examples related to each topic. The content is designed to guide learners through the fundamentals of Java programming.

Uploaded by

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

Core Java All Notes

The document is an index for a core Java tutorial covering various topics such as arrays, classes, inheritance, polymorphism, exception handling, collections, and more. It provides a structured outline of chapters along with key concepts and examples related to each topic. The content is designed to guide learners through the fundamentals of Java programming.

Uploaded by

abhijeettidke123
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 347

CORE_JAVA

INDEX
SR.NO CHAPTER PAGE NO

01 INTRODUCTION OF JAVA 03-08


Byte code, Access specifier.

02 ARRAY IN JAVA 09-17


Types to declare array, Sub array, Anonymous array, Two-dimensional array,
Jagged array.
03 CLASESS AND OBJECT 18-46
Class, Object, Method with a variable argument, POJO class, Difference:
Static variable instance variable and local variable, Garbage collection,
Encapsulation.
04 CONSTRUCTOR IN JAVA 47-57
Types of constructors, Constructor chaining, Utility class, Singleton class.

05 INHERITANCE IN JAVA 58-77


Constructor in inheritance, Final Keyword, Method Overriding, Super,
Method hiding, Difference: Overriding and Overloading.
06 ABSTRACTION IN JAVA 78-87
Adapter class,

07 DYNAMIC POLYMORPHISM 88-94


Coupling and their types. Tight coupling, Loose Coupling or Run time
polymorphism, compile tile polymorphism.
08 INTERFACE IN JAVA 95-106
Diamond problem, Difference: Interface and Abstraction

09 EXCEPTION HANDLING 107-120


Types of exception handling
10 INTRODUCTION OF COLLECTION 121-128
Types of collection, Inbuild method.

11 VECTOR CLASS IN COLLECTION 129-134


Constructor of vector, Threads hold of vector.

12 FETCH DATA FROM COLLECTION 135-161


Types of Data fetching And Method: Using a for loop, Using Enumeration,
[ Dat
]

Using Iterator, Using ListIterator, Using for each.


e
1

13 ARRAYLIST IN COLLECTION 162-165


Difference ArrayList and Vector, constructor of ArrayList.

14 LINKEDLIST IN COLLECTION 166-171


Difference LinkedList and ArrayList, constructor of LinkedList.

15 STACK IN COLLECTION 172-174

16 SET COLLECTION 175-182


Types and Difference of set: HashSet, LinkedHashSet, TreeSet.
Constructors HashSet, LinkedHashSet, TreeSet.

17 COLLECTIONS CLASS 183-203


Utility class, comparable and its methods, Comparator and its methods

18 GENERICS IN COLLECTION 204-211


Solve ClassCastException: solutions Use instanceof operator, Use Generics,
Types of generics.
19 OBJECT CLASS IN COLLECTION 212-229
Hashcode, Object clone, marker interface, String toString method,

20 QUEUE IN COLLECTION 230-231

21 WRAPPER CLASSES IN JAVA 232-248


Primitive Type of conversion, Explicit, Implicit, Auto Boxing, Auto
Unboxing, Reference Type of conversion, Immutable, constant pool, String
Methods, StringBuffer and StringBuilder.
22 MULTI-THREADING IN JAVA 249-267
Thread, Synchronization, Asynchronization, wait() and its type, notify() and
notifyAll(), Thread priority and its type, Runnable interface, Daemon thread,
Life cycle of thread.
23 IOSTREAM OR FILE HANDLING 268-285
Writer class and its constructors, Constructors of Bufferedwriter, Reader,
Methods of reader Constructors of Bufferedreader, STREAM CLASSES:
Input stream Output stream, methods and constructors, Serialization,
[ Dat
]

Deserialization.
e
24 MAP INTERFACE 286-299
Methods of map interface, Types of map interface and its constructors:
HashMap, LinkedHashMap, TreeMap. Store user define object Map Interface,
Map using ArrayList.

2
INTORDUCTION OF JAVA
Q. what is java

java is a pure object-oriented programming language We


have two types of object-oriented programming languages
1) Semi object oriented: semi object-oriented programming language means
those languages can work with object-oriented feature as well as can work with
procedural oriented feature called as semi object oriented.
Example of semi object oriented is: C++
2) Pure Object oriented: those languages can work with object-oriented
programming concept called as pure object-oriented means using OOP feature, we
cannot create its application or run its application called as pure object means in
java, we cannot create program without class.
Example: JAVA, C# etc.

Q. what is difference between C++ and JAVA?


C++ JAVA
C++ is a semi object-oriented language Java is pure object oriented
C++ can use pointer externally Java use pointer internally
C++ can use operator overloading Java not use operator overloading concept
C++ class is by default private Java class is by default use default access
specifier
C++ use three access specifiers private, Java class use four access
specifiers public and protected private, public protected and default C++ use
delete operator for memory Java use garbage collections release purpose
and destructor
C++ use friend function Java not use friend function
C++ use pure virtual function for Java use abstract keyword for achieve achieve
abstraction abstraction
C++ use const keyword for constant Java use final keyword for constant
declaration declaration
C++ can work with structure Java not work with structure
C++ use standard template for data Java use Collection framework for data structure
implementation structure implementation

How to create application using JAVA


If we want to create application using java, we have some important steps.

1) Installed JDK

Q. what is JDK?
JDK stands for java development kit
Def: JDK is software cluster or it is grouping of software which contain some
supporting software’s those help us to create and execute java application.

What is JRE: JRE is stands for java run time environment it is collection of
bundle package etc.
[ Dat

Q. what is compiler?
]
e
Compiler is application or software which is used for convert source code to byte
code in java.

Q. what is byte code?


Byte code is intermediate code which easily converts in machine code with the
help of JVM or byte code is machine understandable code. Q. why java
develop byte code?

byte code is platform independent code here platform indicate operating system
means once we create byte code on any operating system it will execute on any
another operating system so it is platform independent.

5
Example: if we generate byte code on windows operating system then you can
execute it on linux operating system without any modification or without any
thirdparty software.

Above diagram shows platform independency Q.


what is JVM?
JVM is application which is used for convert your byte code to machine code in
and it is present in JDK and JRE also.

2) Create Sample application


if we want to create any program in java, we have following standard syntax or
generalize syntax if we want to write any code in java, we need to write
minimum single class.
Syntax:
access specifier class classname
[ Dat
]
e

6
{
public static void main (String x [])
{write here your logics
}
}
Example:
public class FirstJavaMarch
{public static void main (String x [])
{System.out.println(“good morning”);
} } public class FirstJavaMarch: if we think about this statement here
public is access specifier and class is keyword for class declaration and
FirstJavaMarch is classname and user can give any name to his class. Q. what
is access specifier?

access specifier is some keywords which is used for apply restrictions on class and
its member
there are four types of access specifier in java public: public access specifier
means member can access within a same class or outside of class or within a same
package as well as outside of package also. private: private is access specifier
which is used for restrict class use outside of his class body protected: protected
access specifier which is used for restrict class use only for child not outside of
class using object.
default: default means member can access outside of class but within same
package not outside of package means it is package level access specifier.
public static void main (String x []): it is main function of java same like as main
function in c or cpp.
System.out.println(“good morning”): it is output statement of java same like as
printf () in C language 3) Save Application

if we want to save program then save in bin folder where jdk installed and
give classname and filename same with .java extension. 4) Compilation
[ Dat
]
e
Application
7

STEPS TO COMPILE JAVA PROGRAM


i) open command prompt
task bar -- search -- command prompt ---

ii)
go where java file save and type command javac filename.java javac
FirstJavaMarch.java
once we compile program then java compiler creates new file automatically with
extension of .class and in this file contain your byte code as per our example
after compilation we have two files
FirstJavaMarch.java --- source code
FirstJavaMarch.class --- byte code
5) Run application: program execution is responsibility of JVM so if we want to
run program, we have command java filename
Example: java FirstJavaMarch

[ Dat
]
e
8
ARRAY IN JAVA

]
Date
Q. What is Array?
array is a collection of similar type of data called as array.
THERE IS MAJOR TWO STEPS TO WORK WITH ARRAY IN JAVA
1) Declare variable of array: if we want to declare array variable in java, we
have following syntax

Syntax: datatype variablename [];


Here when we declare array variable it works as reference or pointer internally
Example: int a [];

2) Allocate memory of array: if we want to allocate memory of array in java,


we have following syntax variable = new datatype[size];
Example: a [] = new int [ 5];

Exampe: WAP to input five value in array and display


import java.util.*; public class ArrApp
{
public static void main (String x [])
{
int a [] =new int [5];
Scanner xyz = new Scanner (System.in);

[ Dat
]
e
System.out.println("Enter five values in array");
for (int i=0; i<a. length; i++)

10

{a[i]=xyz. nextInt ();


}
System.out.println("Display array");
for (int i=0; i<a. length; i++)
{System.out.printf("%d\t", a[i]);
}
}
}
Example:

Output: 10 100 30 40 50

Sub Array and sequences


Q. what is sub array?
Sub array is continuous part of array i.e., sub array is an array that is inside of
another array.
In general, for an array of size n, there are n*(n+1)/2 non empty sub array.
[ Dat
]
e
Example: consider we have array [1,2,3,4] as per the above equation we can we
can create 10 sub arrays of this array if we think about this array, we have size 4 so
our formula is step1: 4*(4+1)/2; step2: 4*5/2 step3: 20/2 step4: 10
Your Sub array looks like as

11

(1), (2), (3), (4)


(1,2), (2,3), (3,4)
(1,2,3), (2,3,4)
(1,2,3,4)
Example:
public class TestArrApp
{ static int a[];
public static void main(String x[])
{ a[0]=100;
System.out.println(a);
}
}
above code generate NullPointerException in the case of java we cannot use any
array without new keyword means we cannot allocate memory of array without
using new keyword.

Q. what is anonymous array in java?


array without reference called as anonymous array in java. public
class TestArrApp
{
public static void main(String x[])
{
show(new int[]{10,20,30,40,50});
}
[ Dat
]
e
public static void show(int a[])
{
for(int i=0; i<a.length; i++)
{
System.out.println(a[i]);
}
}
}
Example: WAP to create array of size 5 and input value and find pair of indexes
whose value sum is equal with input value.
12
import java.util.*;
public class TestArrApp
{
public static void main(String x[])
{ Scanner xyz = new Scanner(System.in);
int a[]=new int[5]; boolean flag=false;
System.out.println("Enter five values in array");
for(int i=0; i<a.length; i++)
{ a[i]=xyz.nextInt();
}
System.out.println("Enter input value");
int ivalue=xyz.nextInt(); int j=0,k=0;
for(int i=0; i<a.length;i++)
{ int sum=0;
k=(i+1);
for( j=(i+1); j<a.length; j++)
{
sum =sum+a[j];
if(sum==ivalue)
{flag=true;
break;
}
}
if(sum!=0 && flag)
{ break;
}
}
System.out.printf("%d\t%d\n”, k, j);
}
}
Two Dimensional arrays

it is used for create matrix.


[ Dat
]
e

13
Syntax: datatype variablename[][]=new datatype[size][size];
Example: int a[][]=new int[3][3];

Source code
import java.util.*; public class TestMaxApp
{
public static void main(String x[])
{
int a[][]= new int[3][3];
Scanner xyz = new Scanner(System.in);
System.out.println("Enter values in matrix");
for(int i=0; i<a.length; i++)
{
for(int j=0; j<a[i].length; j++)
{
a[i][j]=xyz.nextInt();
}
}
System.out.println("display matrix"); for(int i=0; i<a.length; i++)

]
Date
[

14
{ for(int j=0; j<a[i].length; j++)
{
System.out.printf("%d\t",a[i][j]);
}
System.out.printf("\n");
}
}
}
Q. what will be output of given code?

Source code
import java.util.*; public
class TestMaxApp
{public static void main(String x[])
{int a[][]=new int[][]{
{1,2,3},
{4,5,6},
{7,8,9}
};
show(a,0);
System.out.println("Display matrix");
[ Dat
]
e

15
for(int i=0; i<a.length;i++)
{
for(int j=0; j<a[i].length; j++)
{ System.out.printf("%d\d”,a[i][j]);
}
System.out.printf("\n");
}
}
public static void show(int m[][],int count)
{ if(count!=3)
{ m[count][count]=m[count][0];
show(m,++count);
}
}
}
Q. What is Jagged Array?
Jagged Array is a concept in Java where we create matrix every row having a
different column list.
Example:
1 2 3
4 5 6 7
8 9
Syntax:
data type variablename[][]=new datatype[row][]; variablename[rowindex]=new
datatype[colsize];

import java.util.*; public


class TestMaxApp
{ public static void main(String x[])
{ Scanner xyz = new Scanner(System.in);
int a[][]=new int[3][];
a[0]=new int[3];
a[1]= new int[4]; a[2]
[ Dat

= new int[2];
]
e
16
System.out.println("Enter value in array");
for(int i=0; i<a.length;i++)
{
for(int j=0; j<a[i].length; j++)
{
a[i][j]=xyz.nextInt();
}
}
System.out.println("Display array"); for(int i=0; i<a.length;i++) {
for(int j=0; j<a[i].length; j++)
{
System.out.printf("%d\d”,a[i][j]);
}
System.out.printf("\n");
}
}
}

]
Date
[

17
CLASSES AND OBJECTS

]
Date
[

18
Q. what is class?
class is a combination of state and behavior or it is combination of variables and
functions.
Here state means variable and behavior means function define within a class. or
class is a combination of instance variable, class variable, methods, constructor,
static initializer, instance initializer and nested classes.

Instance variable means variable declared within class without static keyword
Variable declared within class with a static keyword called as class Static
variable
If we define function within class called as method
If we define block within class called as instance initializer If
we define static block within class called as static initializer
And if we define class within class called as nested class.

Example: class
ABC
{int x; //instance variable
static int y; //class variable
void show()//method
{
}
ABC() //constructor
{
}
{
//instance initializer
}
static{
//static initializer
}
class MNO //nested class
{
[ Dat
]
e
19

}
}

Q. why use class or what is benefit of class?


THERE ARE THREE BENEFITS OF CLASS
1) Ability to store different kind of data
class Employee
{private int id;
private String name;
private int sal;
public void setDetails(String name, int id, int sal)
{this.name=name;
this.id=id;
this.sal=sal;
}
void show()
{ System.out.printf(“%s\t%d\t%d\n”,this.name,this.id,this.sal);
}
}
2) Provide Reusability: means we can declare class only once and can use it more
than one time
How we can reuse class?
If we want to reuse class, we can create its object or by using object we can reuse
any class
Q. What is object?
Object is a block of memory where class data store or object is instance of class
Means when we create object of class then JVM create block in memory and store
all data of class in object.
Q. how to create object in Java?
If we want to create object in java, we have following syntax.
[ Dat
]
e
Syntax: classname ref = new classname();
Example: Employee emp = new Employee();
Here emp is a reference of Employee class and new Employee() is a real object

20

Q. what is diff between reference and object?


Reference is a variable which hold address of object and object is block of memory
where class data store.

STEPS TO USE ANY CLASS IN JAVA


a) Declare class
b) Define function or method within class
c) Create object of class
d) Call its member using object. membername Example as per above steps.

class Square //declare class


{int no;
void setValue(int x) //define function
{ no=x;
}
void showSquare()
{ int sq =no*no;
System.out.printf("Square is %d\n”, sq);
} } public class

[ Dat
]
SquareApplication {public static

e
void main(String x[])
{
Square s1 = new Square();

21

s1.setValue(5);
s1.showSquare();
}}
Q. what happen if we not use reference with object?
if we not use reference with object then JVM create new object every time in
memory show in following diagram.

if we think about above diagram we have statement in main function new


Square().setValue(5) this statement create new object in memory whose address
consider as 10000 and call setValue() function and pass 5 value in object means
this 5 get stored in no which is present in 10000 address block or object whose
address is 10000 again we have statement new Square().showSquare() this function
is used for create new object in memory whose address is 11000 shown in diagram
and we call showSquare() function and in this function contain statement sq=no*no
so the default value no is 0 because we not store 5 in 11000 and we call
showSquare() by 11000 address location so we get answer square is 0 so, if we
want to solve this problem, we can use reference with object

Q. why use reference with object?


When we want to use same object multiple time then we can use reference with
object shown in following diagram.

[ Dat
]
e

22
if we think about
above code we have statement Square s1 = new Square() here s1 is reference of
Square class and new Square() is a real object and we store its address in s1
reference so we consider 10000 is address which we stored in s1 reference again
we have statement s1.setValue(5) meaning is 10000.setValue(5) means we call
setValue() function by object whose address is 10000 and store 5 value in 10000
location and again we have statement s1.showSquare() means here we not use
new keyword means not created new object s1.showSquare() indicate we want to
use same object whose address stored in s1 means s1.showSquare() is equal with
10000.showSquare() means here we use same object with setValue() function as
well as same object with showSquare() so get proper result means here we can say
with the help of reference we use same object multiple time.

Q. can we apply more than one reference on object?


Yes, we can apply more than one reference of single object and if we perform any
change on object by reference then object previous content may be lost or override
shown in following diagram.
[ Dat
]
e

23
Method with a variable argument concept
Method with a variable argument is a concept where we can pass infinite number
of parameters to function and it is denoted by … (triple dot)

Syntax: return type functionname(datatype …


variablename) {write here your logics
}

If we want to work with method with variable arguments, we have


some important points given below.

a) … must be left hand side of variable and right-hand side of data type.
[ Dat
]
e
24
b) If we have some simple argument and some variable argument then variable
argument must be
Last parameter in function
class Sum {int s=0; void calSum(String name, int ...x)
{ System.out.println("Name is "+name);
for(int i=0; i<x.length; i++)
{
s =s+x[i];
}
System.out.printf("Sum of all element is %d\n", s);
}}
public class SumApp
{ public static void main(String x[])
{
Sum s = new Sum();
s.calSum("Ram",10,20,30,40,50);

}
}
c) we cannot pass more than one variable arguments in single function.
class Sum {int s=0; void calSum(String ...name, int ...x)
{ System.out.println("Name is "+name);
for(int i=0; i<x.length; i++)
{
s =s+x[i];
}
System.out.printf ("Sum of all element is %d\n", s);
}}

]
Date
[

25
Above code generate compile time error to us because we pass multiple variable
arguments in single function

Q. what will be output of given code?


class Sum {
int s=0;
void calSum(int []...x)
{
for(int i=0; i<x.length;i++)
{
for(int j=0; j<x[i].length;j++)
{
System.out.printf("%d\t", x[i][j]);
}
System.out.printf("\n");
}
}}
public class SumApp
{ public static void main(String ...x) //java abc 10 20 30 0
{ Sum s = new Sum();
s.calSum(new int[]{1,2,3},new int[]
{4,5,6},new int[]{7,8,9});
}
}
POJO (plain old java objects) class
POJO class means a class with a setter and getter method called as POJO class and
using a setter method we can store data in it and using getter method we can
retrieve data from it.
POJO class is used to create container class means if we want to store data in
object and send it
In another object or use at any another place then we can use POJO class.
The standard of POJO class is use setter and getter keywords before variables in
class
[ Dat
]
e

26
Example: Suppose consider we have class name as Employee with field id name
and sal and we want create class as POJO class.

if
we think about above diagram we create object Employee emp = new Employee
(); and we have statement emp.setId(1); emp.setName(“ABC”); using these
methods we store data in object and we have statement int id=emp.getId() and
emp.getName() using these method we can retrieve data from object. class
Employee
{private int id; private String name; public void setId(int id)
{this.id=id;
}
public int getId(){ return id;
}
public void setName(String name)
{this.name=name;
}
public String getName(){
return name;
}
}
public class POJOAPP
{public static void main(String ...x) //java abc 10 20 30 0

]
Date
{Employee emp = new Employee(); [

emp.setId(1); emp.setName("ABC");
System.out.println(emp.getId()+"\t" +emp.getName()); 27
}
}

Example: we want to create class name as Player with field id name and run create
POJO class and store data in it and retrieve data from POJO object.

class Player {private int id; private String name; private int run;
public void setId(int id)
{this.id=id;
}
public int getId(){
return id;
}
public void setName(String name)
{this.name=name;
}
public String getName(){
return name;
}
public void setRun(int run)
{this.run=run;
}
public int getRun(){ return run;
}}
public class PlayerPOJOAPP
{ p
ub
{ lic static void main(String x[])

Player p = new Player(); p.setId(1);


p.setName("ABC");
p.setRun(10000);
System.out.println("Name is "+p.getName());
System.out.println("Id is "+p.getId());
System.out.println("Run is "+p.getRun());
}
}

Q. WAP to create class name as Company with two methods?


void addNewEmployee(String name, int id, int sal, String address): this
function accept data of employee void showDetails(): this function can
display data of employee.
class Company {private
String name;
private int id; private
int sal; private String
address;
public void addNewEmployee(String name,int id,int sal,String address)
{
this.name=name;
this.id=id;
this.sal=sal;
this.address=address;
}
public void showDetails(){
System.out.println(name+"\t"+id+"\t"+sal+"\t"+address);
} }
public class CompanyApplication
[ Dat
]
e

29
{
public static void main(String x[])
{ Company c = new Company();
c.addNewEmployee("Ram",1,10000,"PUNE");
c.showDetails();

}
}
if we think about above codethere is limitation if we think addNewEmployee()
function we pass here four different type of data like name, Id, sal, address but if
we have more parameter of different type then passing individual parameter si
difficult means suppose if we want to passemployee name , id , sal , address ,
Aadhar, pan etc. it is very difficult to maintain parameter sequence , its data type
from function calling point so better we way when we have different type of data
as parameter in function so we can store all parameter in POJO class and pass
POJO class reference as parameter in function so you can create object of POJO
class at function calling and store data using a setter method and pass POJO
reference to method and youcan use getter method of POJO class where wewant
to use data from POJO class.

]
Date
[

30
Source code
class Employee {private
String name;
private int id;
private int sal;
public void setId(int id)
{this.id=id;
}
public int getId()
{return id;
}
public void setName(String name)
{this.name=name;
}
public String getName(){
return name;
}
public void setSal(int sal)
{this.sal=sal;
}
public int getSal(){
return sal;
}
}
class Company {Employee
employee;
public void addNewEmployee(Employee emp)
{
employee=emp;
}
public void showDetails(){
String name=employee.getName();
int id=employee.getId();
int sal=employee.getSal();
[ Dat
]
e
31

System.out.println(name+"\t"+id+"\t"+sal);
} }
public class CompanyApplication {public
static void main(String x[])
{Company c = new Company();
Employee e = new Employee();
e.setId(1);
e.setName("RAM");
e.setSal(1000);
c.addNewEmployee(e);
c.showDetails();
}
}

Q. WAP to create class name as Library with two methods?


void addNewBook(String bookName, price, String pub) void
displayBook()

class Library
{String bookName;
int price;
String pub;
void addNewBook(String bookName, price, String pub)
{ this.bookName=bookName;
this.price=price;
this.pub=pub;
}
void displayBook(){
System.out.println(bookName+"\t"+price+"\t"+pub);
} } public class
LibraryApplication {public static
[ Dat
]
e
void main(String x[])
{

32

Library l = new Library();


l.addNewBook("Let us c",200,"BPB");
l.displayBook();
}}
if we think about above code, we have Library class with method name as void
addNewBook() it contain three arguments of different type so better way you can
POJO class name as Book and can store three different type of data in it and pass
Book class pojo object in it.

Q. WAP to create class name as Library with two methods


void addNewBook(String bookName, price, String pub) void
displayBook()

class Library
{ String bookName;
int price;
String pub;
void addNewBook(String bookName, price, String pub)
{ this.bookName=bookName;
this.price=price;
this.pub=pub;
}
void displayBook(){
System.out.println(bookName+"\t"+price+"\t"+pub);
} } public class
LibraryApplication { public static
void main(String x[])
{
Library l = new Library();
l.addNewBook ("Let us c",200,"BPB");
l.displayBook ();
}}

[ Dat
]
e
33
if we think about above code, we have Library class with method name as void
addNewBook () it contains three arguments of different type so better way you
can POJO class name as Book and can store three different types of data in it and
pass Book class pojo object in it.

class Book
{ private String name;
private int price; private
String pub;

public void setName(String name)


{ this.name=name;
}
public String getName(){
return name;
}
public void setPrice(int price)
{ this.price=price;
}
public int getPrice()
{ return price;
}
public void setPub(String pub)
{ this.pub=pub;
}
public String getPub(){
return pub;
}}
class Library {
Book []book;
void addNewBook(Book ...b)
{ book=b;
} ]
Dat
[
void showBook(){

38
for(int i=0; i<book.length;i++)
{
System.out.println(book[i].getName()+"\t"+book[i].getPrice()+"\t"+book[i].getPub
());
}
}}
public class LibBookApp
{
public static void main(String x[])
{
Library l = new Library();
Book b = new Book();
b.setName("Let us C");
b.setPrice(200);
b.setPub("BPB");

Book b1 = new Book(); b1.setName("Complete


JAVA");
b1.setPrice(1000);
b1.setPub("Black Book");

Book b2= new Book();


b2.setName("Step By Step C#");
b2.setPrice(1000);
b2.setPub("Microsoft pub");

l.addNewBook(b,b1,b2);
l.showBook();
}
}

Static variable, Instance Variable and Local Variable ]


Dat
[

39
STATIC VARIABLE INSTANCE VARIABLE LOCAL VARIABLE
Static variable means a If we declare variable If we declare
variable declared with a within class without static variable within a
static keyword in class keyword called as instance function of class
called as static or class variable Example: class called as local
variable also. Example: ABC variable. Example:
Class abc { int y; //instance class ABC
{ static int y; //class variable } { void setValue(int
variable x)//local
} {
int y; //local
variable
}
}
Static variable allocates its Instance variable can Local variable can
memory before creating allocate memory after allocate memory after
object of class and stored creating object of class and calling function and
in permanent generation store in object and object stored in stack section
section of memory or meta stored in heap section of of memory
section memory Example:
of memory Example: Example:

You can access static You can access instance You can access local
variable by using variable by using variable by calling
classname.membername object.membername function and cannot
Example: Example: access outside of his
Class statvar class InstanceVar block
]
Dat
[

40
{ { int Example:
static int m; m; } class StatVar
} public class InstanceVarApp {
Public class statvarapp { public static void setValue(int x)
{ public static void void m.ain(String {
main(string x[]) x[]) System.out.println("x
{ statvar.m=100; { InstanceVar sv1 = new is "+x);
system.out.println("m is InstanceVar(); }}
“+statvar.m); sv1.m=100; public class
} System.out.printf("M = StatVarApp
} %d\n”, sv1.m); { public static
} void main(String
} x[]) { StatVar
sv1 =
new StatVar();

sv1.setValue(100);
}
}

Static variable shares Instance Variable share Local Variable not separate
common memory in memory for object. stored in object and
multiple objects of same Example: not accessible by
class
Example:

]
Dat
[

41
object.

]
Dat
[

42
Static variable has default instance variable has default Local
variable has no value provided by java as value provided by java as
default even garbage per his data type means per his data type means
also means when we when programmer not when programmer not
want to use local provide value to static provide value to static
variable in java variable then java jvm variable then java JVM
program then we must initialize some value by initialize some value
by be initializing some default static variable as default static variable as per
value in it otherwise
per his data type his data type compiler will generate
For integer 0, for float For integer 0, for float 0.0, error to us 0.0, for
double 0.0, for for double 0.0, for boolean Example: boolean false, for
string false, for string null, for byte class StatVar null, for byte 0, for long 0
0, for long 0 etc. {
etc. void show()
Example: { int x;
Example: class InstanceVar
Class statvar { boolean b; System.out.println(x);
{ } }
static boolean b; public class InstanceVarApp }
}{ public class
Public class statvarapp public
static void StatVarApp
{ main(String x[]) {
public static void { InstanceVar iv=new public static void
main(string x[]) InstanceVar(); main(String x[])
{ System.out.println("B is { StatVar sv=new system.out.println("b is
"+iv.b); StatVar();
"+statvar.b); } sv.show();
}} }
} Output: B is false. }
Output: b is false. Above code generate
compile time error to us because we use ]
Dat
Date
]

[
local variable without
[

38

44
initialize value in it so
if we want to solve this
problem, we have to
initialize some value in
it.
Example:
class StatVar
{
void show()
{ int x=0;

System.out.println(x);
}}
public class
StatVarApp
{ public static
void main(String
x[]) { StatVar
sv=new
StatVar();
sv.show();
}
}

But instance variable only Local variable can


access in non-static function declare within a static
we cannot access it in static function but local
function variable cannot declare
as static and if we
Static variable can access
declare then we get
in static function as well
compile time error
as non-static function
Life of static variable is The life of instance variable is The life of local ]
Dat
[
present whenever whenever object running variable is whenever

45
application running in memory when object not in function in execution
memory use then JVM delete memory
of object automatically called
as garbage collection

Q. what is garbage collection?

Garbage collection is automatic memory management technique of JVM which


release or delete the memory of object when object not use in program.

Q. How JVM find object not in use?

when object not use any reference then JVM consider object is not in use and JVM
delete that memory of object called as garbage collection.

Here object get deleted by JVM whose address is 10000 because after emp1=null
object not use by any reference and static variable is not part of object and it is
common for all objects so JVM cannot delete static variable so the life of static
variable is present whenever object running in memory.

Array of objects

Array of object is used for store multiple object data in single name reference
]
called as array of objects. Dat
[

46
Syntax: classname ref [] = new classname [size]; //array of reference.
for(int i=0; i<ref.length;i++)
{ ref[i] = new classname(); //array of objects
}

Example: we want to create class name as Employee with field id, name and
salary and we want to create array of object of size 5 and store data in it and
display its data.

Example:
import java.util.*; class
Employee
{ private int id; private
String name; private int
sal; public void
setId(int id)
{ this.id=id;
}
public int getId()
{ return id;
}
public void setName(String name) ]
Dat
[
{ this.name=name;

47
}
public String getName(){
return name;
}
public void setSal(int sal)
{ this.sal=sal;
}
public int getSal()
{ return sal;
}}
public class EmployeeApplication
{
public static void main(String x[])
{
Employee emp[]= new Employee[5];
for(int i=0; i<emp.length;i++)
{ emp[i]= new Employee();
Scanner xyz = new Scanner(System.in);
System.out.println("Enter name id and salary");
String name=xyz.nextLine();
int id=xyz.nextInt(); int
sal=xyz.nextInt();
emp[i].setName(name);
emp[i].setId(id);
emp[i].setSal(sal);
}
System.out.println("Display all records\n");
for(int i=0; i<emp.length;i++){
System.out.println(emp[i].getId()+"\t"+emp[i].getName()+"\t"+emp[i].getSal());
}
}
}

]
Dat
[

48
How to create application by using eclipse
1) download and installed eclipse.
https://www.eclipse.org/downloads/download.php?file=/oomph/epp/202303/R/eclipse-
inst-jre-win64.exe

2) Open eclipse
Search menu ----- eclipse and click on finish.
3) Create Project using eclipse.
File ---- new ---- project ---- java project ---- click on next button --- give project name
---- click on next and click on finish.
4) create package under src folder
right click on src folder --- new ---- give package name --- click on finish button

5) Create class under package


Right click on created package ---- new ----- select class option --- give class name and
select main method if required --- if select main method check box then creates class
with main method otherwise create class without main method.

package org.techhub; import


java.util.Scanner;
class Employee{ private
int id; private String
name; public int
getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() { return
name;
[ Dat
]
e

}
43
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
}
public class FirstArrayOfObjApp { public
static void main(String[] args) {
Employee emp[]= new Employee[5];
Scanner xyz = new Scanner(System.in);
for(int i=0; i<emp.length;i++)
{ emp[i]= new Employee();
System.out.println("Enter name id and salary");
String name=xyz.nextLine();
int id=xyz.nextInt();
int sal=xyz.nextInt();
emp[i].setName(name);
emp[i].setId(id);
emp[i].setSal(sal);
xyz.nextLine();
}
System.out.println("Display all records\n");
for(int i=0; i<emp.length;i++)
{System.out.println(emp[i].getId()+"\t"+emp[i].getName()+"\t"+emp[i].getS
al());
} ]
Dat
[
}

50
}

3) PROVIDE ENCAPSULATION
Q. what is encapsulation?
Encapsulation means hide implementation detail from end user at implementation
level called as Encapsulation.
If we want to achieve encapsulation, we need to declare all class member as private
and access via public function. the goal of encapsulation is data security means if
we declare class variable as private and then we cannot access it outside of class
and if we want to access data or variable, we need to define function public and in
public function we have some logics they decide data is accessible or not called as
encapsulation.

Example: Suppose consider we have Library and we want to issue book to the
student but we want to issue book only students of techhub and we provide unique
id to every students and if any one ask to library for book then librarian first check
the student id in database if student id found in database then librarian can issue
book to student otherwise not if any one student try to access direct book data so
application not allow to access means we can say we restrict to access book of
library means we can say provide security to books in library so we can say it is
example of encapsulation shown in following code

Here we have not database connected with application so we can create temporary
array as database and store sample id of student in array which we consider as
database and when any student asks for book then librarian first cross verify its id
in array if found then application should issue book otherwise not.
package org.techhub;
class Library
{
[ Dat

private int id; private String bookName;


]
e

private String pub; private int[] tempDb=new int[]


{10,20,30,40,50}; public void addNewBook(int id,String
bookName,String pub) { this.id=id;
45
this.bookName=bookName;
this.pub=pub;
}
public boolean issueBook(int studentId) {
boolean b=false;
for(int val:tempDb) //inhance for loop
{if(val==studentId)
{b=true;
break;
}
}return b;
}
}
public class EncapsulationImplApplication {
public static void main(String[] args) {
Library l = new Library();
l.addNewBook(1,"Let Us C", "BPB");
boolean b=l.issueBook(200); if(b)
{System.out.println("Book can issue");
}
else {System.out.println("Invalid user");
}
}
}

]
Dat
[

52
CONSTRUCTOR IN JAVA

]
Date
[

47
]
Dat
[

54
Q. what is constructor?
Constructor is a function same name as class name without return type.

Syntax: class
classname{ cl
assname(){
write here your logics
}
}
Example: class
ABC {
ABC(){
System.out.println(“I am constructor”);
}
}

Q. Why use Constructor?


There are two benefits of constructor
1) Execute logic automatically when class object gets created means we can
say constructor call automatically when we create object of class.
2) To initialize object means we can initialize variable values declared within
class in constructor

[ Dat
]
e
48

TYPES OF CONSTRUCTORS
1) Default constructor: if we declare constructor without parameter called as
default constructor.
class ABC{
ABC(){
System.out.println("I am constructor");
}
}
class HelloWorld {
public static void main(String[] args) {
ABC a1 = new ABC();
}
}
2) Parameterized constructor: parameterized constructor means a constructor
with parameter called as parameterized constructor.
When we pass parameter to constructor then we need to pass parameter to object
because constructor calling point is object.

Example: we want to create class name as Square with parameterized constructor


and we want to design one method name as int get Square () this method can return
square of number
[ Dat
]
e
49

Example: WAP to Create class name as FindMin with parameterized constructor


and one method name as getMin() this method can find minimum value from
array and return it.
FindMin(int a []): this method can accept array as parameter int
getMin(): this method can return minimum value from array.

Source code: import


java.util.*; class
FindMin {
private int a[]; public
FindMin(int a[])
{ this.a=a;
}
public int getMin(){
int min=a[0];
for(int i=0; i<a.length;i++){
if(a[i]<min){
min=a[i];
} ]
Date
} [
return min;
}
50
}
class HelloWorld {
public static void main(String[] args)
{ Scanner xyz = new Scanner(System.in);
int a[]= new int[5];
System.out.println("Enter values in array");
for(int i=0; i<a.length;i++){
a[i]=xyz.nextInt();
}
FindMin fm = new FindMin(a);
int minValue=fm.getMin();
System.out.println("Minimum value from array "+minValue);

}
}
3) Overloaded Constructor: Constructor overloading means if we define same
name constructor with a different parameter with different sequence with a
different data type called as constructor overloading.
If we think about constructor overloading which member should be executed is
depend on how much parameter and its data type and its sequence as well as
number of parameter list pass to object Example:
import java.util.*;
class Area
{ private float radius;
private int len,wid;
public Area(float radius)
{
this.radius=radius;
}
public Area(int len,int wid){
this.len=len;
this.wid=wid; ]
Date
} [
public float getCircleArea(){
return radius*radius*3.14f;
51
}

public int getRectArea()


{ return len*wid;
}
}
class HelloWorld {
public static void main(String[] args)
{ Area a1 =new Area(3.0f);
float circleArea=a1.getCircleArea();
System.out.println("area of circle "+circleArea);

Area a2 = new Area(4,5);


int rectArea=a2.getRectArea();
System.out.println("Area of rectangle is "+rectArea);
}}
4) this() constructor: this() constructor is used for constructor chaining in OOP.

Q. what is constructor chaining?

Constructor chaining means we can call one constructor within another constructor
without creating its manual object.

WE HAVE TWO WAYS TO WORK WITH CONSTRUCTOR CHAINING [ Dat


]
e
a) Using this() constructor
b) Using super () constructor in java (we will discuss in inheritance) this():
if we want to perform constructor overloading using this() constructor we must be
work with constructor overloading concept and this() constructor maintain
execution sequence constructor in stack order means last called constructor
executed first and first call constructor execute last.

Note: this() constructor must be first line of code in calling constructor.

Some important points related with constructor


1) Constructor cannot have return type in java but if we give return type to
constructor then it is considered as method in java. class A

52
{public void A()
{ System.out.println("I am method");
}
}
class HelloWorld {
public static void main(String[] args) {
A a1 = new A();
a1.A();
}
}
If we think about above code we have void A() is method it is not a constructor
because it has return Type.

2) Cannot declare constructor as static in JAVA class


A
{ public static A()
{ System.out.println("I am method");
}
}
class HelloWorld {
public static void main(String[] args) {
A a1 = new A();
}
}
Above code generate compile time error to us because we try to declare
constructor as static and we cannot declare as static so compiler will generate
compile time error to us

Q. why we cannot declare constructor as static?

Because static member can allocate memory before creating object of class and
constructor cannot call without object so it is opposite behavior so we cannot
declare constructor as static.
[ Dat
]
e

53
3) Try to avoid mark constructor as private if it not overloaded
class A {private A()
{System.out.println("I am method");
}
}
class HelloWorld {
public static void main(String[] args) {
A a1 = new A();
}
}
Above code generate compile time error to us because we try to declare constructor
as private and when we declare constructor as private then we cannot access class
object outside of class or cannot create object of class because constructor with
object.
Note: when we want to declare SingleTone or Utility class in java then class
constructor must be private.

Q. what is Utility class?

Utility class means a class which cannot instantiated and which contains only static
methods and methods are public so it is accessible anywhere in application. So,
when we want to restrict utility class from object creation then we must be

[ Dat
]
declaring its constructor as private.

e
How we can create Utility class in Java
If we want create utility class in java then we must be creating its constructor as
private and define only public static method in it.
class TestUtility
{ private TestUtility()
{ System.out.println("I am utility class");
}
public static void show(){
System.out.println("Hey I am utility class method");
}
54

}
class HelloWorld {
public static void main(String[] args) {
TestUtility.show();
}
}

Q. What is SingleTone class?


Singleton class is a design pattern and which allow us to create object of class only
once in application.

Q. what is design pattern?


Design patterns represent the best practices used by experienced object-oriented
software developers. Design patterns are solutions to general problems that
software developers faced during software development. These solutions were
obtained by trial and error by numerous software developers over quite a
substantial period of time.

Q. how to create SingleTone class in java


Steps
1) Declare class with private constructor class Test{
private Test(){
System.out.println(“I am singleton”);
}
}
2) declare reference of same class in it with private
static and null class Test{
private static Test t=null;
private Test(){
System.out.println(“I am singleton”);
[ Dat
]
e
}}

55
3) Create one static method and return same class reference from it.
class Test{
private static Test t=null;
private Test(){
System.out.println(“I am singleton”);
}
public static Test getInstance(){
if(t==null) {
t = new Test();
}
return t;
}
}
Following diagram shows the working of singleton

Q. what is diff between singleton and utility class?

SingleTone class can create its object but create only one copy of object and Utility
class cannot create its object and contain only static methods

Q. what is diff between constructors and methods?

]
CONSTRUCTOR METHODS Dat
[

65
Function name and classname must be Function name and class name may be
same same not compulsory
Cannot have return type Function must have return type
Constructor call automatically when But function need to call manually
object create
Constructor cannot support to recursion Function can support to recursion
Constructor cannot declare as static Function can declare as static
Constructor cannot override Function can override
Constructor cannot declare as final Function can declare as final
Constructor cannot be abstract Function can abstract
Constructor can use constructor Function cannot use function chaining
chaining technique we need to perform nested calling
manually

]
Dat
[

66
INHERITANCE IN JAVA

]
Dat
[

67
]
Dat
[

68
Q. What is Inheritance in java?
Inheritance means to transfer properties of one class to another class called as
inheritance here property sender class called as parent class and property receiver
class called as child class.

A --- Parent or super or base


|
B --- Child or sub or derived

Q. Why use inheritance or what is benefit of inheritance?


THERE ARE TWO BENEFITS OF INHERITANCE
a) Reusability: Reusability means we can declare class only once and we can
reuse it more than one time without create its direct object we can reuse class by
using its child class.
b) Extensibility: extensibility means child class can acquire properties from
parent class and can add its own properties called as extensibility.

If we want to perform inheritance using java, we have extends keyword.

[ Dat
]
e
class A //A is parent
{}
class B extends A //B is child
{
}
Example: we want to design Calculator using inheritance where we have following
class Hierarchy
59

Source code of above diagram


class Value
{ protected int a,b; void
setValue(int x,int y){
a=x;
b=y;
}
}
class Add extends Value
{ int
getAdd()
{ return
a+b;
}
}
class Mul extends Value
{ int
getMul()
{ return
a*b;
}
} class HelloWorld
{ ]
public static void main(String[] args) { Date
[
Add ad = new Add();

60
ad.setValue(10,20); int
result=ad.getAdd();
System.out.println("Addition is "+result);

Mul m= new Mul();


m.setValue(10,20); result=m.getMul();
System.out.println("Multiplication is "+result);
}
}

Note: We cannot create any program in java without inheritance


Because in java we have Object class and Object class is parent of every class in
java and Object class is a member of java. lang package and java. lang is a default
package of java we not need to import it.

Q. why java provide Object class as parent class to every class?


Object class contain some inbuilt methods those required to every class in
java
[ Dat
]
e
1) int hashcode () 2) boolean equals () 3) String toString () 4) void wait () 5) void
wait(int) 6) void notify () 7) void notifyAll () 8) void finalize () 9) Object clone ()
10) Class getClass () 11) static block

Q. How we can say Java is pure object-oriented language?


There is some reason we can say java is pure object-oriented language
1) Cannot create application without class 2) Cannot create application without
inheritance

61

Q. Some people say java is not pure object oriented?


Because java support primitive data type, static keywords and wrapper classes so
some people say java is not pure object oriented.

CONSTRUCTOR IN INHERITANCE
When we have constructor in parent class and constructor in child class and when
we have default constructor in parent class and if we create object of child class
then by default parent constructor get executed before child constructor. class A
{
public A(){
System.out.println("I am parent constructor");
}
}
class B extends A
{
public B(){
System.out.println("I am child constructor");
}
}
class HelloWorld {
public static void main(String[] args) {
[ Dat
]
e
B b1 = new B();
}
}
Note: when we have parameterized constructor in parent class and if we create
object of child class then parent constructor not executed before child constructor
in this scenario we need to pass manually parameter to parent constructor and for
that we have super() constructor concept in java

We can say super () constructor is a part of constructor chaining which help us to


call parent class constructor from a child class.

62
Example: class
Value{
Value(int x) {
System.out.println("x is "+x);
}
}
class Test extends Value {
Test() {
System.out.println("I am child constructor");
}
}
class HelloWorld {
public static void main(String[] args) {
Test t = new Test();
}
}
Note: above code generates compile time error to us because we have parent
class name as Value which contain parameterized constructor and if we create
object of child class then we need to pass parameter from child class but in above ]
we not pass parameter to parent constructor from child class so compiler will Date
generate error to us [

So, if we want to solve this problem, we have to use super () constructor


Note: super() constructor must be first line of code in child class constructor. 63
Q. Can we use super() and this() constructor at a same time?
No because super() constructor must be first line of child class constructor and
this() constructor must be first line of calling constructor so both constructor
required first line and we cannot give same line to multiple calling so if we use
both() constructor at a same then it will generate compile time error to us
Source code
class Value
{ Value(int x) {
System.out.println("x is "+x);
}
}
class Test extends Value
{ Test() {
this("Good");super(100); //call parent constructor
System.out.println("\n I am child constructor");
}
Test(String s){
}
}
class HelloWorld {
public static void main(String[] args) {
Test t = new Test();
}
}
Note: above code generate compile time error to us because we use super() and
this() at same place and it is not possible.

final keyword in java


final is non access specifier in java which we can use with variable, function and
class

final variable: final variable means those variables cannot modify its value once
we assign it means we can say if we want to declare constant value in java or
constant variable in java, we have final keyword.
[ Dat
]
e

64
class HelloWorld {
public static void main(String[] args) {
final int a=100;
++a;
System.out.printf("A %d\n", a);
}
}
Above code generates compile time error to us because we cannot modify its value
once we assign it and we try to modify value of variable a because it is final.
final class: final class means a class cannot inherit in any another class means we
can final class avoid inheritance
Q. how we can avoid inheritance in java?
With the help of final keyword. final
class A{
}
class B extends A{
}
class HelloWorld {
public static void main(String[] args) {
B b1 = new B();
}
}
Note: above code will generate compile time error to us because we have two
classes name as A and B and we have A is parent class but we use final keyword
with variable A so we cannot inherit in class B because A is final class and try to
inherit class A in class B So compiler generate compile time error to us.

How we can avoid method overriding in java or final method in java


final method means a method cannot override in child class.

Q. what is method overriding?


method overriding means if we define method in parent class and redefine method
again in child class called as method overriding.
[ Dat
]
e

65
class
A{ void
show(){
System.out.println(“I am parent method”);
}
} class B extends
A
{ void show(){
System.out.println(“I am child method”);
}
}
Note: in the case of method overriding if we create object of child class and try to
call overridden method then by default child logics get executed. package
org.techhub; class A {
void show() {
System.out.println("Ima parent method");
}
}
class B extends A {
void show() {
System.out.println("I am child method");
}
}
public class InheritenceApp {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}
Output: I am child method
Here we create object of class B and call show () method then we get output I am
child method
Means by default child version get executed.
Q. why use method overriding or what is benefit of method overriding?
There are two benefits of method overriding
1) To customize logics of parent class in child class 2)
To achieve dynamic polymorphism.

To customize logics of parent class in child class


Example: Suppose consider we have one Banking Application and we are using
Inheritance in that application so we have some classes given below.

if we think about
above diagram we have three child classes name as State, Nationalize,
Cooperative and when we create object of any child class and call
setMaxInterest () then as per child logics get executed.

Q. Is Method overriding is beneficial in application or not?

]
Dat
[

78
it is depended on situation some time it is beneficial and sometime not means when

[ Dat
]
parent class logics want to modify by child class as per his requirement then

e
method overriding is beneficial as well as when programmer need to implement 67
dynamic polymorphism then method overriding is beneficial but if we want to
restrict parent logic modification by child class then overriding is not beneficial but
in the case of java, we can avoid method overriding by using final keyword

Example: Suppose consider we are working on BankingApplication we have four


types of classes name as RBI work as parent class and StateBank, NationalizeBank
and Cooperative these are the child classes of RBI and RBI contain two methods 1.
void setMaxInterest () 2. accOpeningDoc () so RBI class permit us we can modify

interest rate in every child class as per the bank expenses but RBI want to restrict
bank to modify accOpeningDoc () RBI set some standards of accOpeningDoc ()
and these standards or logics set by RBI must be use by child class not modify by
child classes so this case if we try to modify accOpeningDoc () method logics in
child class is not benefit so we can declare it as final and avoid method overriding.

package org. techhub;


class RBI { int
irate;
void setMaxInterest() {
irate=16;
}
final void accOpeningDoc() {
System.out.println("1:PASSPORT SIZE PHOTO\n2:Light
Bill/Adhar/Pan\n 3:Biomatric Scan");
}
public int getInterestRate() {
return irate;
}
} class State extends RBI{
void setMaxInterest() {
irate=7;
}
} class Nationalize extends RBI
{ void setMaxInterest() {
irate=6;
}
}
public class InheritenceApp {
public static void main(String[] args) {
State s = new State(); s.setMaxInterest();

System.out.println("State Bank Account Opening Document and Interest


Rate");
int result=s.getInterestRate();
System.out.println("Max Interest is "+result);
s.accOpeningDoc();
Nationalize n = new Nationalize();
System.out.println("Nationalize Bank
Account Opening Document and
Interest Rate");
n.setMaxInterest();
n.accOpeningDoc();
result=n.getInterestRate();
System.out.println("Max Interest is "+result);
}
}

Q. how we can avoid method overriding in java?


By declaring method as final

If we want to work with method overriding, we have some important points.


1) Signature of parent class method and child class method must be same
Means return type of method, name of method, parameter of method; arguments
]
list and its type must be same in parent class and in child class. Dat
[
Def: if we define same signature method in parent class and redefine same
[ Dat
]
e

80
signature method in child class called as overriding.
package org.techhub; class
A{
void show() {
System.out.println("I am A");
}
} class B extends A
{
void show() {
System.out.println("I am B");
}
69

}
public class InheritenceApp {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}

Note: if we have same return type and same method name with a different data
type or different parameter list or different parameter in parent and in child class
then it is considered as method overloading in inheritance shown in following
code. package org.techhub; class A {
void show(int x) {
System.out.println("I am A "+x);
}
} class B extends A
{
void show() {
System.out.println("I am B");
}
}
public class InheritenceApp {
public static void main(String[] args) {
B b1 = new B();
b1.show(6); //call show() in which integer parameter is present
}
}

2) If we define parent class method with a default access specifier then we can
override by protected or by using public but not vice versa.
package org.techhub; class
A{

]
Dat
[

82
void show() //internal meaning = default void show() {
System.out.println("I am A ");
}
} class B extends A
{
public void show() {
System.out.println("I am B");
}
}
public class InheritenceApp {
public static void main(String[] args) {
B b1 = new B();
b1.show(); //call show() in which integer parameter is present
}
}
if we think about above code, we have two classes name as A and B and we show
() method in class with a default access specifier and we override this method in
class B by using public access specifier it is allowed because public has higher
priority than default so public can override on default in child class so, there is
no compile time error.
package org.techhub;
class A {
void show() //internal meaning = default void show() {
System.out.println("I am A ");
}
} class B extends A
{
protected void show() {
System.out.println("I am B");
}
}
public class InheritenceApp {
public static void main(String[] args) { ]
Dat
[
B b1 = new B();
b1.show(); //call show() in which integer parameter is present

83
}
}
Note: if we think about above code, we define parent class method as default and
we override it as protected so it is possible in overriding because protected has a
higher execution priority than default.

Note: but if we define parent method as public or protected and we try to override
it as default then it is not possible and compiler will generate compile time error to
us because public and protected has higher priority than default so default cannot
override on public and protected in child class and if we try to change it then
compiler will generate compile time error.

Example:
package org.techhub; class
A{
protected void show() //internal meaning = default void show() {
System.out.println("I am A ");
}
}
class B extends A {
void show() {
System.out.println("I am B");
}
}
public class InheritenceApp {
public static void main(String[] args) {
B b1 = new B();
b1.show(); //call show() in which integer parameter is present
}
}
or
package org.techhub; class
A{ ]
Dat
[

84
public void show() //internal meaning = default void show()
{ System.out.println("I am A ");
}
}
class B extends A {
void show() {
System.out.println("I am B");
}
}
public class Inheritance {
public static void main(String[] args) {
B b1 = new B();
b1.show(); //call show() in which integer
parameter is present
}}
Q. How we can call parent logics in method overriding?
if we want to call parent logics by using a method overriding, we can use super keyword
or super reference

Q. what is super?
super is an inbuilt reference which is present in every child class and which points
to parent class from a child class and using super we can call parent member from
child class
Normally we refer super keyword in method overriding because in overriding if
we create object of child class and try to call overridden method then by default
child logic get executed if we want to call parent logic from overridden method
then we can use super package org.techhub; class A { public void show()
//internal meaning = default void show() { System.out.println("I am A ");

}
}
[ Dat
]
e

class B extends A {

73
public void show() {
super.show();//call parennt logics
System.out.println("I am B");
}
}
public class InheritenceApp {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}

Q. Can we override static method?


No, we cannot override static method in child class Note:
static method uses for method hiding purpose.

package org.techhub; class


A{
public static void show() //internal meaning = default void show()
{ System.out.println("I am A ");
}
}
class B extends A {
public static void show() {
System.out.println("I am B");
}
}
public class InheritenceApp {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}
[ Dat
]
e
74

Q. what is method hiding?


Before hiding concept, we need to know some important points related with
overriding
In the case of overriding if we create reference of parent class and object of its
child class and if we call overridden method by parent reference then parent
reference call method version from child class whose object stored in it

Example
package org.techhub; class
A{
public void show() //internal meaning = default void show()
{ System.out.println("I am A ");
}
}
class B extends A {
public void show() {
System.out.println("I am B");
}
}
public class InheritenceApp {
public static void main(String[] args) {
A a1 = new B();
a1.show();
}
}
if we think about above code we have statement A a1 = new B() here we create
object of class B and store its address In reference variable a1 which is reference of
parent i.e. class A and we call method using a1.show() so we get output I am B
because a1.show() call version of show() method from class B because a1 points to
B object it is called as method overriding.

Now we will discuss about method hiding.


[ Dat
]
e

method hiding means when we create reference of parent and object of child and
]
call overridden method using parent reference then parent logics get executed not Dat
[

88
75
child logics using parent reference means here can say child class object not
override own logic in parent class reference means parent hide its own logic from
child called as method hiding and it is possible by define same static method in
parent class and same static method in child class means we can say static method
help us to perform method hiding shown in following code.

package org.techhub;
class A {
public static void show(){ //internal meaning = default void show()
System.out.println("I am A ");
}
}
class B extends A {
Overloading is a compile time Overriding is a run time polymorphism
polymorphism
Overloading not required inheritance In Overriding inheritance is mandatory
every time we can perform overloading means we cannot perform overriding
within a same class or using an without inheritance
inheritance means for overloading
inheritance is not mandatory
public static void show() {
System.out.println("I am B");
}
}
public class InheritenceApp {
public static void main(String[] args) {
A a1 = new B();
a1.show();
}
}

Q. what is diff between overloading and overriding?

OVERLOADING OVERRIDING
In overloading method name must be In Overriding method name must be
same with a different signature or syntax same as well as signature of method
means we can pass different type of data, must be same means return type,
different type of parameter list or parameter type, parameter list must be
sequence in overloading same in parent class we all as in child
class
Poor performance due to compile time Better performance due to run time
polymorphism polymorphism
Private and final method can be overload Private and final method cannot be
override

]
Dat
[
ABSTRACTION IN JAVA

90
Q. what is abstraction?
Abstraction means hide the implementation details from end user at design level called
as abstraction.
Means in the case of abstraction we not provide the logic of method just we
provide its template and we can write its logic differently in every child class as per
the requirement of child called as abstraction.

HOW WE CAN ACHIEVE ABSTRACTION IN JAVA?


If we want to achieve abstraction in java then we have two
ways. 1) By using abstract class and abstract methods 2) By using
interface.

ABSTRACT CLASS AND ABSTRACT METHOD


Q. what is abstract class and abstract method?
Abstract class means a class cannot create its object and abstract method means
method cannot have logics

How to declare abstract class and abstract method in java


Syntax:
abstract class classname{ abstract return type
functionname(arguments); }

Example:
package org.techhub; abstract
class Vehicle{ abstract void
engine();
}
public class InheritenceApp {
public static void main(String[] args) {
Vehicle v = new Vehicle();
}
[ Dat

}
]
e

]
Dat
[

92
79
Q. why use abstract class and abstract method?
THE MAJOR GOAL OF ABSTRACT CLASS AND ABSTRACT METHOD
IS
1) Achieve abstraction
2) Achieve dynamic polymorphism

Note: if we want to write any logic of abstract method we need to override


abstract method in its child class and create object of child class and call it using
child object.

package org.techhub; abstract


class Vehicle{ abstract void
engine();
}
class Bike extends Vehicle{
void engine() {
System.out.println("I am Bike");
}
}
public class InheritenceApp {
public static void main(String[] args) {
Bike b = new Bike();
b.engine();
}
}
If we want to work with abstract class and abstract method, we have some
important rules
1) If we have abstract method in class then class must be abstract Note:
we cannot use abstract method in non-abstract class.
class Vehicle{ abstract void
engine(); }
If we think about above code, we get compile time error because we define abstract
method within non abstract class.
[ Dat
]
e
80

2. If we declare class as abstract then we cannot create its object and if we try
to create it then
We get compile time error.
abstract class Vehicle{
abstract void engine();
}
Vehicle v = new Vehicle(); if we think about above code, we get compile time
error because we try to declare object of abstract class and it is not possible.

Q. why we cannot create object of abstract class?

Because abstract class may be containing some abstract methods and abstract
method cannot have logic
And if java allows us to create object of abstract then using that object there is
possibility, we can call abstract method for method calling we required its
definition but abstract method cannot have so for avoiding this problem there is no
permission to create object of abstract class.

Example: abstract class ABC {


abstract void show();
}
ABC a1 = new ABC();
a1.show (); // it is not possible because show() does not have definition or logic
Example: suppose if java allow us to create object of class ABC then using that
object there is possibility we can call show() method of ABC but show() is abstract
and it has no definition so we cannot call it using object so we cannot create object
of ABC abstract class.

3) we can declare constructor within abstract


package org.techhub; abstract
[ Dat
]
e
class Vehicle{ abstract void
engine();

81

Vehicle(){
System.out.println("I am abstract class
constructor");
}}
class Bike extends Vehicle{
void engine() {
System.out.println("I am Bike");
}
}
public class InheritenceApp {
public static void main(String[] args) {
Bike b = new Bike();
}
}

Q. if we cannot create object of abstract class then how constructer get


executed?
because abstract may be non-abstract method, we not need to override non abstract
method in abstract child class and if we create object of child class of abstract then
abstract class constructor get executed

Q. what is major use of declare constructor in abstract class?


because if we have some variables in abstract class and if we create initialize it
when we create object of child then we can declare constructor within abstract
class so when we create object of its child then before child constructor parent
constructor get executed and abstract is always parent
[ Dat

Q. can we use abstract keyword with a variable?


]
e
We cannot use abstract keyword with a variable because the goal of abstract
keyword is to achieve abstraction and we can achieve abstraction by using method
not use variables so java not allow us to use abstract keyword with variable.
abstract datatype variablename=value;//it is wrong syntax and may be generate
compile time error.

82

Example:
abstract int a=100;

Q. can we declare abstract method as final?


No, we cannot declare abstract method as final because final method cannot
override in child class and abstract method must be override in child class so it is
complete opposite behavior so we cannot declare abstract method as final and if
we try to declare it then we get compile time error.

Example:
abstract class ABC { final abstract void show(); //it will raise
compile time error. }

Q. Can we declare abstract method as static?


No, we cannot declare abstract method as static because static keyword work with

[ Dat
]
compile time polymorphism or static binding but abstract method works with

e
dynamic binding or run time polymorphism so we cannot declare it as static and if
we declare it as static then compiler will generate compile time error to us.

abstract class Vehicle{ static


abstract void engine();
}
If we think about above code, we get compile time error because we declare
abstract method as static

Q. Can we declare abstract method as private?


No, we cannot declare abstract method as private because private member cannot
support to inheritance as well as private member cannot support to method
overriding and abstract must be override so we can say abstract and private has
opposite behavior with each other so it is not possible and if we try combination of
abstract and private then compiler will generate compile time error to us

83

abstract class Vehicle { private


abstract void engine();
}

Q. Can we declare abstract method as protected?


Yes, we can declare abstract method as protected and can override it as protected
or public because protected member can be use or override in child class and
abstract must be override so it is possible to declare abstract method as protected.

abstract class Vehicle {


protected abstract void engine();
}
class Bike extends Vehicle{

[ Dat
]
protected void engine() {

e
System.out.println("I am Bike");
}
}

Note: if abstract class contains more than one abstract method then all method
must be override where abstract class get inherit and if we not override any
method then compiler will generate compile time error. abstract class Vehicle{
abstract void engine(); abstract void color();
}
class Bike extends Vehicle{
void engine() {
System.out.println("I am Bike");
}
} if we think about above code we have two abstract method in Vehicle class
and which is our abstract class and we inherit Vehicle class in Bike class and
we override single method name as engine()

84

but the rules need to override all abstract method from abstract class we not
follow rule so compiler generate compile time error to us if we want to solve this
problem, we have two ways

1) Override all method as blank in child class


abstract class
Vehicle{ abstract void
engine(); abstract void
color();
} class Bike extends
[ Dat
]
e
Vehicle{ void engine()
{
System.out.println("I am Bike");
}
void color() {
}
}

2) Use Adapter class

Q. what is adapter?
Adapter is a design pattern and which is used for cover the limitation of abstract
class and abstract method
Basically, Adapter is intermediate class which contain all blank method of abstract
class and which is able to provide specific method to abstract class called as
adapter.

package org.techhub; abstract


class Vehicle{ abstract
void engine();
abstract void color();
}
class ADP extends Vehicle{
void engine() {

85
}
void color() {
}
}
class Bike extends ADP
{ void engine(){
System.out.println("I am Bike");
}
} if we think about above code, we have ADP is adapter class because ADP
inherit
Vehicle class and override it’s all blank method and provide specific method to
Bike means Bike use method from Vehicle but via ADP so we can say ADP is
adapter class.

Note: we cannot create object of abstract class but can create its reference. If we
want to create reference of abstract class, we need to create object of its child
class show in following code.

package org.techhub; abstract


class Vehicle { abstract
void engine(); abstract
void color();
}
class ADP extends Vehicle {
void engine() {
}
void color() {
}
}
class Bike extends ADP {
void engine() {
System.out.println("I am Bike");
}
}

]
Date
[

86
public class InheritenceApp {
public static void main(String[] args) {
Vehicle v = new Bike();
v.engine();
}
} if we think about above code we have Vehicle v = new Bike() is a statement
where new Bike() is an actual object of child of Vehicle and v is reference of
Vehicle class or abstract class

Q. Why we need to create reference of abstraction class or What


is benefit of abstract class reference?
or when we required or need to create reference of abstract class?

If we want to achieve dynamic polymorphism or loose coupling then we need to


reference of abstract class.

[ Dat
]
e

87
DYNAMIC POLYMORPHISM

Q. What is dynamic polymorphism?

Dynamic polymorphism means object bounded with functionality at program run


time called as dynamic polymorphism.

If we want to achieve dynamic polymorphism, we can achieve it by using method


overriding technique and normally we can implement dynamic polymorphism by
using abstract methods in java.

In the case of dynamic polymorphism, we can create reference of abstract class


and object of its child class. So, the benefit is when we call overridden method by
parent reference and call overridden method using parent reference whose child
object stored in it.

How to implement Dynamic polymorphism

]
Date
[

88
How to achieve loose coupling by using dynamic polymorphism and abstract class
reference

Q. what is coupling?

Coupling means if method of particular class is dependent on particular parameter


called as coupling or dependency injection.

THERE ARE TWO TYPES OF COUPLING

1) Tight Coupling

[ Dat
]
e
89

2)Loose Coupling

Q What is Tight Coupling?


Tight coupling means if method of particular class is 100% dependent on another
class object called as tight coupling.

Example: we want to design Calculator we have following classes in our


[ Dat
application

]
e
1. Value which is abstract class and it contain two methods one is void setValue(int
x, int y) non abstract method and public abstract int getResult() it is abstract
method.

Two more child classes name as Add and Mul and we can inherit Value class in
Add and Mul classes and override int getResult() method and write different logics
in every class and we have one more class name as Calculator which contain one
method name as void performOperation(Add ad)

Here we pass Add class object in performOperation () so here we can say it is tight
coupling example.

if we think about above code we have Calculator class in this class contain one
method name as performOperation(Add ad) this method contain reference of class

90
Add means this method calling is 100% dependent on Add class object without
Add class object we cannot call this method and if we try to pass reference of class
Mul in performOperation() is not possible and generate compile time error means
we must be pass Add class reference in performOperation() so we can say it is
called as tight coupling.

But tight coupling is not good approach in programming if we think about


calculator, we can say calculator can perform multiple operation not only Add
operation so it is not proper design of Calculator it is limitation of tight coupling

IF WE WANT TO SOLVE THIS PROBLEM, WE HAVE TWO WAYS

2) Loose Coupling: Loose coupling means method of particular class is


partially dependent on particular class object called as loose coupling and we
can achieve loo se coupling by using interface or abstract class.
1)Use Compile time polymorphism: we can use method overloading technique

If we think about above code we have two methods name as performOperation ()


with a different parameter but the limitation of method overloading is suppose
consider we have calculator with 100 different operation and if we write 100
[ Dat
]
e

91
different classes for every operation then we need to write 100 different
performOperation() method in Calculator class and it is not possible in real time
and very tedious and complicated task in real time scenario so if we want to solve
this problem we want to design only one method in Calculator class or we want to
design only one version of performOperation() method in Calculator class which
can accept 100 different parameter or can accept 100 different class object as
parameter in this scenario loose coupling using dynamic polymorphism comes in
picture.

2) Use Run time polymorphism or loose coupling

Example: WAP for loose coupling create abstract class name as Vehicle with one
abstract method name as abstract void engine() and we have two child classes
name as Bike and Car and we need to inherit Vehicle class in it and override
engine() method in Bike and Car class as well as we have one more class name as
ShowRoom and in ShowRoom class we have method name as void
saleVehicle(Vehicle v) case 1: to pass Bike reference to saleVehicle
case 2: to pass Car reference to sale vehicle

package org.techhub; import


java.util.Scanner; abstract
class Vehicle {
abstract void engine();
[ Dat
]
e
92
}
class Bike extends Vehicle {
@Override
void engine() {
System.out.println("I am bike");
}
} class Car extends Vehicle
{
@Override
void engine() {
System.out.println("I am Car");
}
}
class ShowRoom { void
saleVehicle(Vehicle vehicle) {
vehicle.engine();
}
}
public class VehicleLooseCouplingApp {
public static void main(String[] args) {
ShowRoom s=new ShowRoom();
Scanner xyz = new Scanner(System.in);
System.out.println("1: Bike");
System.out.println("2: Car");
System.out.println("Enter your choice");
int choice=xyz.nextInt();
Vehicle v;
switch(choice) {
case 1: v=new
Bike();
s.saleVehicle(v);
break; case
2: v=new Car(); ]
Dat
s.saleVehicle(v); [

109
break;
default:
System.out.println("Wrong choice");
}
}
}

]
Dat
INTERFACE IN JAVA [

110
]
Dat
[

111
Q. What is Interface?
interface is same like as abstract class in java. Q.
why use interface if we have abstract class?
THERE ARE THREE REASONS TO USE INTERFACE
1. Achieve multiple inheritances
2. Achieve 100% abstraction
3. Achieve Dynamic Polymorphism

Q. why java not use classes for multiple inheritance implementation?


Because of diamond problem Q.
what is diamond problem?
Multiple inheritance means there is more than one parent classes and single child
class so there is possibility main parent class may be containing same name
method so if create object of child class and try to call the parent then compiler
may be get confused called as diamond problem because child contain three
version of same name method from three different parent and for resolve this
problem java provide one solution to us name as interface.

if we think about
diagram we have three parent classes name as A B and C and we inherit this
parent class in D so D class contain three different methods with a same name i.e.
show() one from A ,one from B and one From C so when we create object of class
D and call show() method then compiler get confused for call show() it is called as
diamond problem. How to work with interface
[ Dat
]
e
96

if we want to work with an interface, we have to declare interface for declare


interface we have interface keyword.
Syntax:
interface interfacename {
returntype functionname(datatype variablename);
}
Example: interface ABC {
void show(); }
Note: interface method cannot have logics because they are by default public and
abstract and interface cannot create its object because it is internally abstract.

So, if we want to write logic of interface method, we must be implementing the


interface in some another user defined class and override its method and write its
logic so you can call interface method by object of its implementer class.
if we want to implement interface in user defined class, we have to use
implements keyword

Syntax: class classname implements interfacename {


//override method of interface
}

]
Date
[

97
SOME IMPORTANT POINTS TO WORK WITH AN INTERFACE
1) Interface cannot create its object.
2) Interface methods are by default public abstract so we cannot write its
logic need to override in child class.
3) Interface variables are by default public static final
The meaning is when we declare any variable within an interface, we must be

[ Dat
]
e
initializing some value to it.

Q. why interface variables are declaring as public static final?


because interface cannot create its object so if we want to use interface variables
without object then we can use it by using interface name so it is a declare as static
because static member can use without creating object of class or by using class
name and interface is same like as class so we can use interface variable without
creating its object because of static variable.

98

4. We cannot declare interface method as final?

if we think about interface its


method by default public abstract and abstract cannot declare as final because

[ Dat
]
abstract method must be override and final cannot override so if we try to declare

e
interface method as final then it may be generating compile time error.

5. We cannot declare interface method as static?


If we think about static method it is used for achieve compile time polymorphism
and interface method is used for achieve dynamic polymorphism so we cannot
declare it as static.

Q. can we declare interface method as protected?

99

No, we cannot declare interface method as protected


Q. If we declare abstract method within abstract class then we can declare it
as protected but when we declare abstract method within interface then why it
is not declared as protected?
because when we declare abstract method within abstract class then it use default
access specifier but when we declare it as protected then protected can override on
default so compiler not generate any problem at compile because compiler found only
access specifier with method i.e. protected but when we declare interface method as
protected then there is problem interface method is by default public abstract and
public has higher priority than abstract so when we declare interface method as
protected then protected access specifier try to override on public access specifier so
protected cannot override on public because it has less priority so compiler found two
access specifier at time with interface method i.e. protected public and in java there is
not protected public access specifier so compiler will generate compile time error to
us at compile time so we cannot declare interface method as protected event it is
abstract.

Shown in Following Diagram


[ Dat
]
e
100

Above code generates compile time error to us so we cannot declare interface


method as protected.

Q. Is it compulsory to override interface method as public?


Yes, it is mandatory interface method must be override as public because interface
method is by default public in interface and when we implement interface in any
another class and override it without public then it is considered as default in
implementer class so per the rule of overriding public to default overriding is not
possible.
[ Dat
]
e
Above code will generate compile time error because we try to override public to
default and it is not allowed so this major reason when we override interface
method it must be public in implementer class.

package org.techhub; interface


ABC
{ void show();//public abstract void show();
}
class MNO implements ABC
{ public void show() {
System.out.println("I am show");
}
} public class TestInterfaceProtectedApp
{ public static void main (String[] args)
{
MNO m = new MNO();
m.show ();

101

}
}
Note: if we want to perform inheritance between interface to interface, we have
extends keyword.
Interface to class use implements keyword
class to class use extends keyword interface
to interface use extends keyword class to
interface not allowed in java
Note: if interface contain more than one method then we must be overriding all
method where interface get implemented.

above screen shot show compile time error because we have interface PQR with
two abstract method name as void show () and void display() and we override
only

show() method in MNO class not display() and rule is need to override all methods
]
where interface get implemented so we get compile time error so if we want to solve Date
this problem we have two ways [

1. Define all interface method as blank. 102


2. Use Adapter class
Adapter class is intermediator class which contain all blank methods of interface or
abstract class and which is capable to provide specific method to its child class

Date
]

103

Note: we cannot create object of interface but can create its reference so if we want to
create reference of interface then we have to create object its implementer class.

Q. what is purpose of interface reference?


The major goal of interface reference is to achieve dynamic polymorphism.

How to achieve multiple inheritances using interface


If we want to achieve multiple inheritance using interface, we have rule is single
base class, single child class and more than one parent interfaces Syntax:
interface interfac1{
}
interface interface2 {
}
class parentclassname {
} class childclassname extends parentclassname implements interface1, interface
….
n{}

MULTIPLE INHERITANCE EXAMPLE

package org.techhub; interface


A{
void show();
}
[ Dat
]
e

interface B {void show();

104
} class C
{
void show() {System.out.println("I am C");
}}
class D extends C implements A, B { public
void show() {
System.out.println("I am D show");
}
}
public class MultipleInheritenceApp {
public static void main(String[] args) {
D d1 = new D();
d1.show();
}
}

Q. What is diff between abstract class and interface?

ABSTRACT INTERFACE
Abstract class is used for achieve partial Interface is used for achieve 100%
abstraction abstract

Need to use abstract keyword for Interface is internally abstract class by


declare abstract class default

Abstract class variable is not by default Interface variables are by default public
final static final

Abstract class may be containing non But interface every method is by default
abstract method public and abstract

Abstract class method is not by default But interface method is by default


public Abstract class need to use extends
keyword for inherit in another class
Abstract class cannot support multiple Interface need to use implements
inheritance keyword in another class

Abstract method in abstract class can Interface can support to multiple


declare as protected inheritance

Abstract class contain constructor But interface method cannot be


declared as protected

Interface cannot use constructor

public ]
Dat
[ Date
EXCEPTION HANDLING [

106
123
Q. what is exception handling?
Exception is events which occur at program run time and which is responsible for disturb
the normal flow of application called as exception.

Q. why use exception handling?


1. It Help programmer to detect error at run time
2. Skip the code in which exception may be occurs and executes remaining code
in safe zone.

There are three types of exception in java


1. Checked Exception: checked exception means those exceptions occur at
program compile time called as checked exception.
Compile time exception help us to generate exception warning at program compile time.
2. Unchecked Exception: Those exceptions occur at program run time called as
unchecked exception.
3. Error: Those exceptions never handle by programmer called as error.

Q. what is diff between error and exceptions?

Exception can handle by programmer but error cannot handle by programmer. Exception
may be generated at compile time or may be at run time but error always generate at run
time.

If we want to work with exception in java, we have some inbuilt classes provided by
java to us means java provide different classes to us for handle different type of
errors
]
Dat
[

125
[ Dat
]
e
108

if we want to
handle exception, we have some inbuilt keywords provided by java to us

try: try is a block which is used for write code in which exception may be occur
and when exception generate in code then JVM create one error object and hand
over to catch for further processing. catch: catch is a block which always execute
when exception generate in try block means we write logic in catch those want to
execute after exception or we can show exception in catch block.

Syntax:
try {
write here logics or code in which exception may be occur
}
catch(exceptiontype ref)
{write here logics want to execute after exception
}
Note: Single try can have more than one catch block.
try { }
catch(exceptiontype ref){
}
catch(exceptiontype ref){
}

]
Dat
[

127
finally: finally, is a block which always execute if exception generate in program
or not means finally block is used for write code which we want to execute in any
situation like as file close, database connection close etc.

try { }
finally {
} or try
{}
catch(Exceptiontype ref){
} finally
{
}

throw: throw is a clause which is used for handle the user defined exception and
throw clause can use with a function.

throws: throws are a clause in exception handling which is used for handle
checked exception and we can use with throws clause with a function definition
also and need to write try and catch at function calling.

Now we want to some exception and its possibility


]
Dat
[

128
1. NullPointerException: NullPointerException occur when we try to use any
reference without memory allocation or without new keyword means
normally this exception occur with array variable or reference variable.

if we think about above code get NullPointerException because we have array


static int a []; here we not allocated memory for reference variable a so its default
value is null and this variable not points to any memory address so when we use
the a[0]=100 means we try to store value on a[0] location but there is not memory
allocated for a[0] and a points to null value so JVM generate error at run time
NullPointerException. so, if we want to handle this type of exception at run time,
we have NullPointerException class.

Example with object

]
Dat
[

129
Above code generate NullPointerException at run time because we have static
ABC ab; here we have reference variable ab which has default value null means
we not created object of ABC class and we try to call ab.show() method and we
cannot call any member of class without object and ab contain null value so JVM
generate NullPointerException

Example:
import java.util.*;
class ABC {void
show()
{System.out.println("I am show");
}}
public class TestExeApp {static
ABC ab;
public static void main(String x[])

{ try
{
ab.show();
}
catch(NullPointerException ex)
{System.out.println("Problem for object creation"+ex);
}
}
]
} Dat
[

130
2. ArrayIndexOutOfBoundsException: this exception generates when we try to
store value more than size of array. Example:

if we think about this code we get ArrayIndexOutOfBoundsException because we


have array of size a[2] means we have two a[0] and a[1] and we try to use a[2] it is
out of size array so JVM found array limited crossed so JVM generate
ArrayIndexOutOfBoundsException at run time so, if we want to handle this
exception we need to use try and catch and need to write
ArrayIndexOutOfBoundsException in catch block.

3.NumberFormatException: this exception normally generates by JVM when we


try to convert string to primitive type some time if try to convert string to primitive
e.g., string to integer and if there is any non-numeric value present string then we
cannot convert it in integer so JVM generate error to us NumberFormatException

]
Dat
[

131
above code generate NumberFormatException to us because we try to convert
string to integer and in string contain alpha and it is not converted in integer so
JVM generate NumberFormatException to us
import java.util.*;
public class TestExeApp
{
public static void main(String x[])
{
try {
String s="12345";
int a=Integer.parseInt(s);
System.out.println(a);
}
catch(NumberFormatException ex)
{ System.out.println("Error is "+ex);
}
}
}
4.InputMismatchException: InputMismatchException occur when user provide
the wrong input from keyboard

Source code import


java.util.*; public ]
Dat
[
class TestIns

132
{ public static void
main(String x[])
{ Scanner xyz = new Scanner(System.in);
int a, b, c;
try{
System.out.println("Enter two values");
a=xyz.nextInt();
b=xyz.nextInt();
c=a+b;
System.out.printf("Addition is %d\n", c);
}
catch(InputMismatchException ex){
System.out.println(“Error is “+ex);
}
}
} finally block: finally, is a block in java which is used for execute code in
any situation means exception occur in program or not.
try {
write here logics
} finally
{
write here logics want to execute in any situation }

]
Dat
[

133
if we think about
above code, we have exception in program but finally get executed before
exception also means we can say finally execute always in program if
exception generate or not.

Q. what is diff between finally and catch?


finally, is always execute in program if exception generate or not and catch execute
only when exception generate in program. finally, cannot handle exception but
catch can handle exception.

Q. can we write try without catch?


Yes, we can write try without catch using finally block means if we use finally
block with try then there is no compulsion to use catch block but you can use try,
catch and finally at a same time try { }
catch(exceptiontype ref){
}
finally {
} or
try {
}
finally {
}
Q. what is diff between finally, final and finalize?

finally, is a block which is used for in exception handling and execute always in program
if exception generate or not
[ Dat
]
e
116
final is a keyword we can use with variable, method and class means when we use
final keyword with variable then we cannot modify its value, when we use final
keyword with method then method cannot override and when we use final
keyword with class then class cannot inherit in any another class finalize() is a
method of java.lang.Object class and which is used for perform cleaning
operation at the time of garbage collection and this method call automatically
when we have reference is null and call System.gc() method

Note: when we use try, catch and finally at a same time then first catch block get
executed and after that finally if exception occur and if we use try and finally and
if exception occur then first finally get executed and after that exception occur.

Source code import java.util.*; public


class TestIns { public static void
main(String x[]) {
Scanner xyz = new Scanner(System.in);
int a,b,c;
try {
System.out.println("Enter two values");
a=xyz.nextInt();
b=xyz.nextInt();
c=a/b;
System.out.printf("division is %d\n", c);
} catch(ArithmeticException
ex){
System.out.println("Error is "+ex);
}
finally {
System.out.println("I can execute always");
} ]
Dat
[
System.out.println("Logic1");
System.out.println("Logic2");

135
System.out.println("Logic3");

}
}

throw and throws clause

Q. what is throw?
throw is a clause in exception handling which is used for handle user defined
exceptions.

Q. what is user defined exceptions?


User defined exception means those exceptions design by user for handle own
error or exceptions
Or user defined exception means those exception created by user called as user
defined exceptions.

Q. why user needs to create user defined exceptions?


THERE ARE TWO REASONS
1. If user want to create custom exception as per his project requirement
2. If user has some error but java not provides some inbuilt API for handle that
error then user can create own exception class and handle it
These are two major reasons user can create own exception class called as user
defined exceptions.

How to create user define exceptions in java


If we want to create user defined exceptions in java, we have to create own class
[ Dat
]
e
and inherit exception class in it.

118

]
Dat
[

137
class userclassname extends exceptiontypeclass{ }
When we use user defined exception then we need to create object user exception
manually and throw it. When we use throw keyword then we need to write try and
catch at function calling point not need to write in function definition.
Example: we have application or we want to design Voter application and our
condition is if voter age is below 18 then system should generate error at run time
and show the error message you are invalid voter.

Q. what is throws?

throws are also clause in exception handling which is used for handle checked
exceptions
Normally throws clause use with a function definition and return exception object
where function gets called.
Means when we use throws with a function definition and handle checked
exception then we must write try and catch at function calling point.
Syntax: return type functionname(arguments)throws exception type{
write here your logics
}

class Div
{ int z;
void calDiv(int x, int y)throws Exception
{ z=x/y;
System.out.printf("Division is %d\n", z);
[ Dat
]
e
119
} } public class
DivApp
{
public static void main(String x[])
{ try{
Div d = new Div();
d.calDiv(10,0);
}
catch(Exception ex)
{ System.out.println("Error is "+ex);
}
}
}

Q. what is diff between throw and throws?

THROW

Throw is keyword
which is used for
handle user defined
exception
Throw is keyword THROWS
need to create
Throws is keyword
manually exception
which is used for
class object and
handle checked
throw it
exception
In the case of throws
keyword JVM create
Throw keyword
internally object of
can work with
exception class and
single exception at
throw it programmer
time
not need to create
manually object of
Throws can work
exception class with multiple
exception at 0time.
INTRODUCTION OF COLLECTION
FRAMEWORK

]
Date
[

121
Q. What is collection?
Collection is inbuilt API in java which is used for store different type of data as
well as can store unlimited data as per user requirement and provide some inbuilt
data structure implementation to us called as Collection.
Collection is a readymade implementation of data structure provided by java to us.
Q. why java introduce a collection framework?
Because if we want to work with a data structure, we required using array but the
major limitation of array is
1. We cannot modify size of array at run time.
2. If we want to implement data structure, we required to write manual
logics of every algorithm.
Note: In the case of Java, we if we create array of Object class then we can store
different type of data in it.
package org.techhub;
public class ObjArrApplication { public
static void main(String[] args) {
Object obj [] = new Object[] {10,5.4,"good",new
java.util.Date(),false};
System.out.println("Display array data");
for(int i=0; i<obj.length;i++) {
System.out.println(obj[i]);
}
}
}
[ Dat

If we think about above code there is two limitations.


]
e
1. We cannot modify the size of object class array.
2. If we want to perform data structure operation like as sorting, searching,
insertion of element,
Deletion of element etc. then we need to write manual logics of data structure
means programmer need to write or develop algorithm as per the data structure.
So, java provides some facility to us to avoid this problem called as Collection. If
we want to work with Collection in java, we have some readymade interfaces
and classes provided by java to us shown in following diagram.

122

If we think about above diagram we have top most interface name as java.lang.Iterable.
Q. what is purpose of java.lang.Iterable interface?
Iterable is an interface which is used for travel or fetch data from a collection and
for this purpose this interface provides three methods to us. Iterator iterator()
below two methods we will discuss at the time of JDK 1.8 version of java.
void forEach(Consume)
java.util.SplitIterator splitIterator()
Iterator iterator() : iterator() is a method from java.lang.Iterable interface and this
method return reference of java.util.Iterator interface.
Syntax:
interface Iterable{
Iterator iterator(); }
void remove(): this method remove data from collection at the time of data fetching.

[ Dat
]
e
123

public interface java.util.Iterator<E> {


public abstract boolean hasNext();
public abstract E next(); public void
remove();
public void forEachRemaining(java.util.function.Consumer<? super E>); }
The benefit we can fetch any type of collection data using an Iterator
The second interface from above collection hierarchy is java.util.Collection Here
Collection interface contain some inbuilt methods those required for perform daily
and regular operation on collection framework like as adding element on collection,
removing element from collection, search element from a collection etc.
INBUILT METHODS OF COLLECTION FRAMEWORK

public abstract int size(): this method can return size of collection or return number
of element present in collection.

public abstract
boolean isEmpty(): this method can check collection is empty or not if empty
return true otherwise return false.
public abstract boolean contains(java.lang.Object): this method check element
present in collection or not if present return true otherwise return false means we can
say this method help us to search element in collection.

[ Dat
]
e
124
public abstract java.util.Iterator<E> iterator(); : this method can fetch data from
collection using Iterator

public abstract boolean add(E): this method can add new element in collection and
return true if element added successfully otherwise return false.

public abstract boolean remove(java.lang.Object): this method can remove data


from collection and return true if element removed successfully otherwise return
false.

public abstract boolean containsAll(java.util.Collection<?>): this method check


multiple element present in collection or not if present return true otherwise return
false. ]
Dat
[

145
public abstract boolean addAll(java.util.Collection<? extends E>): this method can add
more than one element at a time in collection if element added return true otherwise
return false.

public abstract boolean removeAll(java.util.Collection<?>);


public boolean removeIf(java.util.function.Predicate<? super
E>); public abstract boolean retainAll(java.util.Collection<?>);
public abstract void clear();

THERE ARE THREE TYPES OF COLLECTION


1. List: List Collection can store any type of data in it can allow duplicated
element and manage data using indexing technique.

2. Set: Set Collection can store unique data means not allow duplicated data and
manage data using hashing technique and may be generate data randomly.

3. Queue: Queue collection can store data duplicate and manage data using index
and arrange data in first in first out format

NOW WE WANT TO DISCUSS ABOUT LIST COLLECTION


Methods of List Collection
public abstract E get(int): this method helps us to return data from
collection using its index and if index not found.
IndexOutOfBoundsException i) For retrieve data from collection

public abstract E set(int, E): this method can replace data in collection using a some
specified index.
[ Dat
]
e
126

public abstract void add(int, E): this method help us to add new data on specified
index in collection.

public abstract E remove(int): this method can remove data from collection
using its index and if index not present then this method returns
IndexOutOfBoundsException at run time.

public abstract int index Of(java.lang.Object): this method can return index of
element and return -1 when element not found in collection we can this method
for search element from collection when we get -1 we consider element not
present and when we get value except -1 we consider element present in
collection.

]
Dat
[

147
public abstract java.util.ListIterator<E> listIterator(int): this method is used
for fetch data from a list collection in backward direction as well as in forward
direction. public abstract java.util.List<E> subList(int, int): this method help
us to retrieve data between specified index using a List Collection.

]
Date
[

VECTOR CLASS IN COLLECTION


128
]
Dat
[

149
Q. What is Vector class?
Vector is implementer class of List Collection.

SOME IMPORTANT POINTS OF VECTOR CLASS


1. Vector is legacy collection or legacy class: legacy classes mean those classes
are not a part of collection in previous version but later they are added as part of
collection called as legacy collection.
If we think about Vector, it is added as part of collection from JDK 1.2 version of
JAVA but in JDK 1.0 version of JAVA vector work as dynamic array so this is major,
we can say Vector is legacy collection.

2. Vector is thread safe collection: thread safe collection means all methods of
Vector are synchronized means Vector object use by single thread at a time means
multiple thread object cannot use vector object simultaneously.

3. Vector occupies double memory than its current capacity when Capacity
cross: Means the default Capacity of Vector is 10 so when we add values more than
10 in Vector then vector allocate double memory than its current capacity.

CONSTRUCTOR OF VECTOR CLASS


THERE ARE FOUR CONSTRUCTORS OF VECTOR CLASS.

]
Dat
[

151
1. Vector()
2. Vector(int initialCapacity)
3. Vector(int initialCapacity,int incrementalCapacity)
4. Vector(Collection)

1. Vector(): this constructor help us to create vector with default capacity i.e. 10
means when we use this constructor then java internally create array of object class of
size 10

Date
]

[
130
if we want to see the capacity of vector then we have method name as
int capacity(): this method return capacity of vector
Source code package org.techhub; import
java.util.*; public class Vectograph { public
static void main(String[] args) { Vector
v = new Vector(); int c=v.capacity();
System.out.println("Capacity of vector is "+c);
}
}
Note: when we add element more than capacity then vector occupy double capacity
than its current capacity.
]
Dat
[

153
2. Vector(int initialCapacity): this method is used for create vector with a initial
capacity as per the user choice. package org.techhub; import java.util.*;
public class ObjArrApplication {
public static void main(String[] args) {
Vector v = new Vector(5);
System.out.println("Initial capacity "+v.capacity()); v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(10);
v.add(20);
v.add(30);
System.out.println("total values present in vector "+v);
System.out.println("Now size of vector is "+v.size());
System.out.println("Incremented Capacity "+v.capacity());
}
}
Output:

]
Date
[

132
Note: if we use the above two constructor’s then vector occupy double memory than
its current capacity when current capacity gets cross.
But if user want to set incremental capacity of vector as per his choice, then we have
constructor given below.

3. Vector(int initialCapacity,int incrementalCapacity): int initialCapacity: this


parameter decides the initial capacity of vector int incrementalCapacity: this
parameter decides the incremental capacity of Vector. package org.techhub; import
java.util.*; public class ObjArrApplication {
public static void main(String[] args) {
Vector v = new Vector(5,2);
System.out.println("Initial capacity "+v.capacity());
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(10);
v.add(20);
v.add(30);
v.add(90);
System.out.println("total values present in vector "+v);
System.out.println("Now size of vector is "+v.size());
System.out.println("Incremented Capacity "+v.capacity());
}
}

4. Vector(Collection): this constructor help us to copy data from another collection


in vector object.
package org.techhub; import
java.util.*; public class
ObjArrApplication {
public static void main(String[] args) {
ArrayList al = new ArrayList(); ]
Dat
al.add(10); [

al.add(20); al.add(30);

155
Vector v =new Vector(al);
System.out.println(v);

}
}
Example: We want to store 5 values in Vector and display it.
package org.techhub; import java.util.*; public class
TestCollApp {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
v.add(40);
System.out.println(v);
}
}
If we think about above code, we display data of collection but we cannot use it so
if we want to use
Collection data then we need to retrieve or fetch data from collection.
Q1. what are threads hold of Vector?

Threads hold of vector is 1 because when vector cross its capacity then it will
increase its capacity by 100% means double so as per the probability it is 1

Q2. What is logic of Vector double capacity allocation?


newCapacity = size>currentCapacity?
currentCapacity+currentCapacity:currentCapacity;
[ Dat
]
e
134

FETCH DATA FROM COLLECTION

]
Dat
[

157
HOW TO FETCH DATA FROM COLLECTION OR HOW TO RETRIEVE DATA
FROM COLLECTION
1. Using a for loop
2. Using Enumeration
3. Using Iterator
4. Using ListIterator
5. Using for each from JDK 1.5 version of java and for each using JDK1.8
version of java

1. USING A FOR LOOP


1.Fetch Data from collection using for loop

if we think about above code we have for loop and we start it from 0 to n we get data
from Vector class using get() method so get() method return data using its index.
Note: if we think about Collection then Collection return data in the form of
Object class because Object class is parent class of every class in java it has ability
to store any kind of data in it.
Example: WAP to store 5 values in Vector calculate its sum.
[ Dat
]
e
136

If we think about above code, we get compile time error because we get data in
Object class format and we try to perform sum with Object class
Note: Object class can store any type of data in it but we cannot perform any
operation on Object class like as addition, subtraction , multiplication, comparison
etc. if we want to perform any operation on Object class we must be convert it in its
original format means as per our example we have value 10 , 20 , 30 , 40 , 50 in
Vector class but they are in the form of Object class in Vector but its original type is
integer so we need to convert data in int format if we want to proper answer

]
Dat
[

159
Example: WAP to store 5 values in Vector and find maximum value without
using any inbuilt function

Example: WAP to store 5 values in vector and arrange in ascending order


without using sort() function? package org.techhub; import java.util.*; public
class TestCollApp {
public static void main(String[] args) { Vector v=new Vector();
v.add(6);
v.add(3);
v.add(4);
v.add(3);
v.add(2);
System.out.println("Before Sort "+v); for(int i=0; i<v.size();i++) {
for(int j=(i+1);j<v.size();j++) {
if((int)v.get(i)>(int)v.get(j)) {
Object temp=v.get(i);
v.set(i, v.get(j)); //swapping
v.set(j, temp);
}

]
Dat
[

161
}
}
System.out.println("After Sort "+v);
}
}
If we fetch data using a for loop then there is limitation it will take more time for data
fetching if we have large number of data present in collection because in for loop
every time initialization, condition and increment and decrement happen so it will
take more time in ALU unit in CPU so better we can use Iterators provided by java to
us.
Now we want to discuss about Enumeration iterator or cursor.

2.ENUMERATION.
Enumeration is a cursor in java which is used for fetch data from collection Some
Important points related with Enumeration

1. Enumeration can work with legacy Collection e.g., Vector


2. Enumeration is read only cursor means we can fetch data using Enumeration but
we cannot modify any data in Collection using Enumeration.
If we want to work with Enumeration we have elements() method of Vector and
this method return reference of Enumeration interface to us Syntax:
Enumeration ref = collref.elements ();

METHODS OF ENUMERATION INTERFACE


boolean hasMoreElements(): this method is used for check element present in
collection or not if present return true otherwise return false.
Object nextElement(): this method can fetch data from collection and move cursor
on next element.
Example: we want to Create one Vector store 5 values in it and display it using
Enumeration.
[ Dat
]
e
139

]
Dat
[

163
Example: fetch data from Collection using Enumeration
package org.techhub; import java.util.*;
public class ObjArrApplication {
public static void main(String[] args) {
Vector v = new Vector(); v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
Enumeration enm = v.elements();
while(enm.hasMoreElements())
{ Object obj = enm.nextElement();
System.out.println(obj);
}
}
}

3. ITERATOR.
Q. How to Fetch data from a Collection using Iterator
If we want to fetch data using a Iterator we have to call iterator() method of
Iterable interface.
METHODS OF ITERATOR INTERFACE
[ Dat
]
e

140
boolean hasNext(): Check element present in collection or not if present return
true otherwise return false.
Object next(): fetch element from a Collection and move cursor on next element
void remove(): This method can remove element from a collection by using
Iterator at the time of data fetching.

Source code delete element from Vector using Iterator


package org.techhub; import java.util.*;
public class ObjArrApplication {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
System.out.println("Before Delete "+v);
Iterator i = v.iterator();
while (i.hasNext()) {
Object obj = i.next();
if((int)obj==30) {
i.remove();
}
}
System.out.println("After delete “+v); ]
Dat
[

165
}
}
Q. what is diff between Enumeration and Iterator?

ENUMERATION ITERATOR
It works with only legacy collections It can work with legacy as well as
nonlegacy collection
It is read only cursor or use for fetch It can fetch data as well as can remove
data only from collection data from collection
Enumeration provide methods boolean Iterator provide method to us boolean
hasmoreelements(), nextelement() hasNext(),Object next() and void
remove()

4. LISTITERATOR.

ListIterator is used for fetch data from collection in forward direction as well as in
backward direction and it works with only List Collection not other.
METHODS OF LISTITERATOR

boolean hasNext(): check element present in collection or not in forward direction


fetching
Object next(): fetch element from collection and move cursor on next element
boolean hasPrevious(): method check element present in collection or not in
backward direction
Object previous(): fetch element from collection and move cursor on backward
direction
void remove(): this method can remove element from collection
void add(E): this method can add new data in collection at the time of fetching
void set(E): this method can replace data in collection etc.
if we want to create reference of ListIterator we have listIterator (int index) method
of List Collection and return reference of ListIterator Syntax: ListIterator ref =
collef.listIterator(int index) ]
Dat
[

166
Source code package
org.techhub; import java.util.*;
public class ObjArrApplication {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.adda(50);
ListIterator li = v.listIterator(v.size());
while( li.hasPrevious() )
{
Object obj = li.previous();
System.out.println(obj);
}
}
}
Example: Add element using ListIterator in Collection
package org.techhub; import java.util.*;
public class ObjArrApplication { public
]
static void main(String[] args) { Dat
[

167
Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
ListIterator li = v.listIterator(v.size());
System.out.println("Before Adding "+v);
while( li.hasPrevious() ) { Object
obj = li.previous();
if((int)obj==40) {
li.add(300);
}
}
System.out.println("After Adding "+v);
}
}

Q. what is diff between Iterator and ListIterator?

ITERATOR LISTITERATOR
Iterator can fetch data in forward ListIterator can fetch data in forward as
direction. well as well backward direction.
Iterator can remove data from collection. ListIterator can remove, add, replace
data in collection at the time of data
fetching.
Iterator can work with any collection. ListIterator can work with only List
Collection.
Iterator reference can create by using ListIterator reference can create by using
iterator() method of iterable interface. listIterator () method of List interface.

Iterator provide following methods to ListIterator provide following method to ]


Dat
[
us. us.

168
boolean hasNext() Object boolean hasNext() boolean
next() hasPrevious()
Void remove() Object next()
Object previous() etc.

5. FOR EACH.
Q. How to fetch data using for each?

JDK 1.5 version of java provide one special type of for loop called as enhance for
loop or for each it is specially design for fetch data from collection or array but it
works with only in forward direction and not need to provide manual initialization,
condition or increment or decrement
Syntax: for(datatype variable:array or collection){
write here logics
}

package org.techhub; import


java.util.*;
public class ObjArrApplication {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
for (Object obj : v) // for(int i=0; i<v.size();i++)
{ System.out.println(obj);
}
}
} or
we can use forEach() from JDK 1.8 version of java package
org.techhub; ]
Dat
[

169
import java.util.*; public class
ObjArrApplication {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
v.forEach(value->System.out.println(value));
}
}
Example: we want to create Employee class with field id , name and salary and
store 5 employee objects in Vector collection and display it.
package org.techhub;
import java.util.*; class
Employee { private
int id; private String
name; public int
getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal; ]
Dat
} [

170
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
}
public class ObjArrApplication {
public static void main(String[] args) {
Vector v = new Vector(); Employee
emp1 = new Employee();
emp1.setId(1);
emp1.setName("ABC");
emp1.setSal(10000); Employee
emp2 = new Employee();
emp2.setId(2);
emp2.setName("MNO");
emp2.setSal(20000); Employee
emp3 = new Employee();
emp3.setId(3);
emp3.setName("PQR");
emp3.setSal(30000); Employee
emp4 = new Employee();
emp4.setId(4);
emp4.setName("PQR");
emp4.setSal(40000); Employee
emp5 = new Employee();
emp5.setId(5);
emp5.setName("STV");
emp5.setSal(60000); v.add(emp1);
//
v.add(emp2);
v.add(emp3);
v.add(emp4);
v.add(emp5); ]
Dat
for(Object obj:v) { [

171
Employee
e=(Employee)obj;
System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getSal());
}
}
}
Example: we want to create Vector and store 5 Product detail in it and search
product by using Its id and delete it. package org.techhub;
public class Product {
private int id; private
String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
private int price;

}
package org.techhub; ]
Dat
[

172
import java.util.*; public class
CollectionProdApplication{
public static void main(String[] args) {
Vector v = new Vector();
Scanner xyz = new Scanner(System.in);
Product p[]=new Product[5]; //array of reference.
int prodId;
for(int i=0; i<p.length;i++) {
p[i]=new Product(); //array of object
System.out.println("enter name id and price of product");
String name=xyz.nextLine();
int id=xyz.nextInt();
int price=xyz.nextInt();
xyz.nextLine();
p[i].setName(name);
p[i].setId(id);
p[i].setPrice(price); v.add(p[i]);
}
System.out.println("Before Deletion of Product");
for(Object obj:v) { Product pd=(Product)obj;
System.out.println(pd.getId()+"\t"+pd.getName()+"\t"+pd.getPrice());
}
System.out.println("Enter id for search");
prodId=xyz.nextInt();
boolean flag=false; for(Object
obj:v) { Product
prod=(Product)obj;
if(prod.getId()==prodId) {
v.remove(prod); flag=true;
break;
}

]
Dat
[

173
}
if(flag) {
System.out.println("Product Deleted
Success....");
}
else {
System.out.println("Some problem is
there.........");
}
System.out.println("After Deletion of Product");
for(Object obj:v) {
Product pd=(Product)obj;
System.out.println(pd.getId()+"\t"+pd.getName()+"\t"+pd.getPrice());
}
}
}
Example: WAP to Create Vector and store 5 product object in it and search product
and update its price.

Example:
Now we want to create mini project using Collection and we want to use Collection
as temporary database.
SHOPKEEPER

]
[ Dat
e
150
1. New Product Add in Stock
2. View All Products
3. Search Product by Name
4. Sort Product by Price
5. Sort Product by Company Name
6. Count Product by Company
7. Count Product by Category
8. Delete Product by Id
9. Search Product by Id

In This Application we are using three types of classes.


1. Model class or POJO class
2. Repository class
3. Driver class or Client Application

1. Model class or POJO class: Model class means class with a setter and
getter methods where we can store data in object
Here we use Product class as model class where we can store all information of
product.

2. Repository class means a class can perform database operation like as insert
record in database, delete record from database etc. and here we use Collection as
temporary database

3. Driver class: driver class means a class with main method where user can
provide input and get results normally in Driver class, we create object of model
]
Dat
[

175
and store data in it as well as create object of repository class and perform database
operation on it.

Product Application
package org.product.model;
public class Product {
private int id; private
String name;
public Product() {
}
public Product(int id,String name,String compName, String category,int
price) {
this.id=id;
this.name=name;
this.company=compName;
this.category=category;
this.price=price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
]
Dat
[

176
}
public void setPrice(int price) {
this.price = price;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
private int price;
private String company;
private String category;
}
package org.product.repository; import
java.util.*; import
org.product.model.Product; public class
ProductRepository { //here we perform all
operation on collection
Vector v = new Vector(); // 1: Add
New Product"); public boolean
isAddProduct(Product p) {
boolean b = v.add(p);
return b;
}
// 2: View All Products public
Vector<Product> getAllProducts() { ]
Dat
[

177
return v;
}
// 3: Search Product By Name
public Product getProductByName(String prodName) {
boolean b = false;
Product p = null; for
(Object obj : v) {
p = (Product) obj;
if (p.getName().equals(prodName)) {
b = true; break;
}
}
if (b) {
return p;
} else { return null;
}
}
// 4: Sort Product By Name
public void sortProductByName() {
Vector str = new Vector(); for
(Object o : v) { Product p
= (Product) o;
str.add(p.getName());
}
Collections.sort(str);
System.out.println("ID\tNAME\tCOM\tCAT\tPRICE");
for (int i = 0; i < v.size(); i++) {
String pqr = (String) str.get(i);
for (int j = 0; j < v.size(); j++) {
Object obj = v.get(j);
Product p = (Product) obj;
if (pqr.equals(p.getName())) {
]
Dat
[

178
System.out.println(p.getId() + "\t" + p.getName() +
"\t" + p.getCompany() + "\t" + p.getCategory()
+ "\t" + p.getPrice());
}
}
}
}
// 5: Sort Product By Company Name
public void sortProductByCompName() {
Vector str = new Vector(); for (Object o :
v) {
Product p = (Product) o;
str.add(p.getCompany());
}
Collections.sort(str);
System.out.println("ID\tNAME\tCOM\tCAT\tPRICE");
for (int i = 0; i < v.size(); i++) {
String pqr = (String) str.get(i);
for (int j = 0; j < v.size(); j++) {
Object obj = v.get(j);
Product p = (Product) obj; if
(pqr.equals(p.getCompany())) {
System.out.println(p.getId() + "\t" + p.getName() +
"\t" + p.getCompany() + "\t" + p.getCategory()
+ "\t" + p.getPrice());
}
}
}
}
// 6: Count Product By Company
public int getProductCountByCompName(String compNameCount)
{ int count = 0; for (Object obj : v) {
Product p = (Product) obj; ]
Dat
[

179
if (p.getCompany().equalsIgnoreCase(compNameCount)) {
count++;
}
}
return count;
}
// 7: Count Product By Category
public int getProductCountByCategory(String categoryNameCount) {
int count = 0;
for (Object obj : v) {
Product p = (Product) obj;
if (p.getCategory().equalsIgnoreCase(categoryNameCount)) {
count++;
}
}
return count;
}
// 8: Delete Product by Id
public boolean isDeleteProductById(int prodId) {
boolean flag = false;
for (Object obj : v) {
Product p = (Product) obj;
if (p.getId() == prodId) {
v.remove(p);
flag = true;
break;
}
}
return flag;
}
// 9: Search Product By ID

]
Dat
[

180
public Product getProductById(int prodId) {
boolean b = false; Product p = null;
for (Object obj : v) { p=
(Product) obj; if (p.getId() ==
(prodId)) {
b = true;
break;
}
}
if (b) {
return p;
} else { return
null;
}
}
// 10: Sort by product price.
public void sortProductByPrice()
{
for(int i=0;i<v.size();i++)
{
for(int j=i+1;j<v.size();j++)
{
Object obj1=v.get(i);
Product a1=(Product)obj1;
Object obj2=v.get(i);
Product a2=(Product)obj2;

if(a1.getPrice()>a2.getPrice())
{
Object ob=v.get(i); v.set(i, v.get(j));
v.set(j, (Product)ob);
}
]
Dat
[

181
}
}
for(Object ob: v)
{
Product pv=(Product)ob;
System.out.println(pv.getId()+"\t"+pv.getName()+"\t"+pv.getCompany()+"\t
"+pv.getCategory()+"\t"+pv.getPrice());
}
}
}
DriverApplication.java package
org.techhub.driverapp; import
java.util.*;
import org.product.model.Product;
import org.product.repository.ProductRepository;
public class ProductDriverApplication {
public static void main(String[] args) {
ProductRepository pRepo = new ProductRepository();
do {
Scanner xyz = new Scanner(System.in);
System.out.println("1:Add New Product");
System.out.println("2:View All Products");
System.out.println("3:Search Product By Name");
System.out.println("Enter your choice");
int choice = xyz.nextInt();
switch (choice) {
case 1:
System.out.println("Enter id name company and category
and price\n");
int id = xyz.nextInt();
xyz.nextLine();
String name = xyz.nextLine();
]
Dat
[

182
String compName = xyz.nextLine();
String category = xyz.nextLine();
int price = xyz.nextInt();
Product p1 = new Product(id, name, compName,
category, price);
boolean b = pRepo.isAddProduct(p1);
if (b) {
System.out.println("Product Added
Successfully.............");
}
else {
System.out.println("Some problem is there................");
}
break;
case 2:
Vector v = pRepo.getAllProducts();
for (Object obj : v) {
Product p = (Product) obj;
System.out.println(p.getId() + "\t" + p.getName() + "\t" + p.getCompany() + "\t" +
p.getCategory()
+ "\t" + p.getPrice());
}
break;
case 3:
xyz.nextLine();
System.out.println("Enter product name");
String prodName = xyz.nextLine();
Product p = pRepo.getProductByName(prodName);
if (p != null) {
System.out.println("Product Found");
} else {
System.out.println("Product Not Found");
} ]
Dat
[

183
break;
case 4:
// 4:Sort Product By Name
pRepo.sortProductByName();
break;
case 5:
// 5:Sort Product By Company Name
pRepo.sortProductByCompName();
break;

case 6:
// 6:Count Product By Company
xyz.nextLine();
System.out.print("Enter Company Name To Count
Product: ");
String compNameCount = xyz.nextLine();
int companyCount =
pRepo.getProductCountByCompName(compNameCount);
System.out.println("Products of " + compNameCount +
": " + companyCount);
break;
case 7:
// 7:Count Product By Category
xyz.nextLine();
System.out.print("Enter Category Name To Count
Product: ");
String categoryNameCount = xyz.nextLine();
int categoryCount =
pRepo.getProductCountByCategory(categoryNameCount);
System.out.println("Products of " + categoryNameCount
+ ": " + categoryCount);

]
Dat
[

184
break;
case 8:
// 8:Delete Product By Id
System.out.print("Enter Product Id to Delete: ");
int prodId = xyz.nextInt();
boolean result = pRepo.isDeleteProductById(prodId);
if (result) {
System.out.println("Product Deleted
Successfully..............");
} else {
System.out.println("Product Not Deleted...........");
}
break;
case 9:
// 9:Search Product By Id
xyz.nextLine();
System.out.print("Enter Product Id: ");
prodId = xyz.nextInt();
Product p3 = pRepo.getProductById(prodId);

if (p3 != null) {
System.out.println("Product Found..........");
} else {
System.out.println("Product Not Found..........");
}
break;
case 10:
// 10:Sort Product By Price
pRepo.sortProductByName();
break;
case 11:
System.exit(0);
]
Dat
[

185
break;
default:
System.out.println("wrong choice");
}
} while (true);
}
}

ARRAYLIST IN COLLECTION

]
Dat
[

186
ArrayList

ArrayList is same like as Vector with some major differences.

Q. what is diff between Vector and ArrayList is?

VECTOR ARRAYLIST
Vector is legacy collection ArrayList is non legacy collection
Vector is thread safe means methods of ArrayList is not thread safe.
vector are synchronized ]
Dat
[

187
Vector occupy double memory than its ArrayList occupy half memory than
current capacity its current capacity when capacity
cross.
Vector threashold value is 1 ArrayList threashold is 0.5
Logic of double memory increment is Logic of half memory increment is
Newcapacity=size>currentcapacity? NewCapacity=size>currentCapacity?
Currentcapacity+creentcapacity:currentcap currentCapacity+currentCapacity>>1:
acity; currentCapacity;

Q. what is Similarity between Vector and ArrayList?

1. Both are type of list collection means both are implementer classes of List
Collection
2. Both works as dynamic array
3. Vector and ArrayList default capacity is 10
4. Both manage data using index

CONSTRUCTOR OF ARRAYLIST

1. ArrayList()
2. ArrayList(int initialCapacity)
3) ArrayList(Collection)
1. ArrayList(): this constructor help us to create ArrayList Collection with default
capacity i.e. 10
2. ArrayList(int initialCapacity): Here user can pass initial capacity as per his
choice but if user pass negative capacity then it will throws
IllegalArgumentException.
package org.techhub; import
java.util.*; public class ArrayListApp {
public static void main(String x[]) {
ArrayList al = new ArrayList();

]
Dat
[

188
al.add(10);
al.add(20); al.add(30);
al.add(40);
for(Object obj:al) {
System.out.println(obj);
}
}
}
3) ArrayList(Collection): this method is used for copy data from another
collection and pass in ArrayList.
package org.techhub; import
java.util.*; public class ArrayListApp
{ public static void main(String x[])
{ Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
ArrayList al = new ArrayList(v);
for(Object obj:al) {
System.out.println(obj);
}
}
}
Example: WAP to Store 5 values in ArrayList and search element present in
ArrayList or not package org.techhub; import
java.util.*; public class TestArrList { public
static void main(String[] args) { Scanner
xyz = new Scanner(System.in);
ArrayList al = new ArrayList();
al.add(10); al.add(20); al.add(30);
al.add(40); al.add(50);
System.out.println("Enter value for search");
int value = xyz.nextInt(); ]
Dat
[

189
boolean b = al.contains(value);
if (b) {
System.out.println("Value found");
} else {
System.out.println("value not found");
}
}
}

LINKEDLIST IN COLLECTION

]
Dat
[

190
Q. What is LinkedList?

LinkedList is an implementer class of List Collection which is by default double


LinkedList

Q. what is diff between ArrayList and LinkedList?

ARRAYLIST LINKEDLIST
ArrayList work as dynamic array LinkedList work as by default double
LinkedList
ArrayList use o(n) time complexity for LinkedList use O (1) time complexity ]
Dat
[

191
deletion and updation of element Means for deletion and updation of record or
when we perform deletion and updation element.
operation on ArrayList we required to Means when we delete element from
perform multiple iteration so it will take LinkedList it will never perform
more time for perform operation so we iteration for element shifting purpose so
can say ArrayList is slower than we can say LinkedList is faster than
LinkedList for deletion and updation ArrayList for deletion and updation
purpose purpose.
For data fetching purpose ArrayList is LinkedList store its data in the form of
faster than LinkedList because node and every node connect with other
ArrayList stored its data sequentially in node by using its addresses so when we
the form dynamic object array so we fetch data from LinkedList first need to
fetch data by using its index faster find address location of node and after
that we can fetch its data so we can say
LinkedList is slower than ArrayList for
data fetching and searching purpose.

CONSTRUCTORS OF LINKEDLIST

1. LinkedList()
2. LinkedList(Collection)

1. LinkedList(): this is the default constructor without logics


2. LinkedList(Collection): this constructor help us to copy data from another
collection and stored in LinkedList object.
package org.techhub; import
java.util.*;
public class LinkedListApplication {
public static void main(String[] args) {
LinkedList lst = new LinkedList();

]
Dat
[

192
lst.add(100);
lst.add(200); lst.add(300);
lst.add(400);
lst.addFirst(600);
for (Object obj : lst) {
System.out.println(obj);
}
}
}

Example: WAP to Create LinkedList and store 5 employee objects in it and count
employee
Whose salary is same?
package org.techhub; import
java.util.*;
public class LinkedListApplication {
public static void main(String[] args) {
LinkedList list = new LinkedList();
Employee emp1 = new Employee(1, "ABC", 10000);
Employee emp2 = new Employee(2, "MNO", 20000);
Employee emp3 = new Employee(3, "STV", 10000);
Employee emp4 = new Employee(4, "PQR", 20000);
Employee emp5 = new Employee(5, "XYZ", 40000);
list.add(emp1);
list.add(emp2); list.add(emp3);
list.add(emp4); list.add(emp5);
System.out.println("Display all employees");
for (Object obj : list) {
Employee emp = (Employee) obj;
System.out.println(emp.getId() + "\t" + emp.getName() + "\t" +
emp.getSal());
}
// sorting logics ]
Dat
[

193
for (int i = 0; i < list.size(); i++) {
for (int j = (i + 1); j < list.size(); j++) {
Employee prev = (Employee) list.get(i);
Employee next = (Employee) list.get(j);
if (prev.getSal() > next.getSal()) { list.set(i, next);
list.set(j, prev);
}
}
}
System.out.println("Display all employees Sorted By
Salary"); int count = 0; Employee e2 = null;
try {
for (int i = 0; i < (list.size()); i++) {
Employee e1 = (Employee) list.get(i); // 3==4
e2 = (Employee) list.get(i + 1);// 4+1-
IndexOutOfBoundsException
if (e1.getSal() == e2.getSal()) {
++count;
}
else {
++count;
System.out.println(e1.getSal() + "-------->" +
count);
count = 0;
}
}
} catch (Exception ex) {
++count;
if (count > 1) {
System.out.println(e2.getSal() + "----------->" + count);
}
}
]
Dat
[

194
}
}

Example: WAP to create LinkedList and store five player records in display the
player whose
age between 20 to 25 and if run of player more than 30000 then give five start to
them

package org.techhub;

import java.util.*;

public class PlayerListCollectionApp { public


static void main(String[] args) { LinkedList
list = new LinkedList(); list.add(new
Player("ABC", 1, 22, 2000)); list.add(new
Player("PQR", 3, 25, 30000)); list.add(new
Player("STV", 2, 38, 40000)); list.add(new
Player("XYZ", 4, 28, 34000));
list.add(new Player("MNO", 5, 29, 29000));

System.out.println("display all players");


for (Object obj : list) {
Player p = (Player) obj;
System.out.println(p.getId() + "\t" + p.getName() + "\t" + p.getRun() + "\t" +
p.getAge());
}

System.out.println("Best Player ");


for (Object obj : list) {
Player p = (Player) obj;
if (p.getAge() >= 22 && p.getAge() <= 25) {
if (p.getRun() >= 30000) { ]
Dat
[

195
System.out.println(p.getId() + "\t" + p.getName() + "\t" + p.getRun() + "\t" +
p.getAge()+"*****");

} else {
System.out.println(p.getId() + "\t" + p.getName() + "\t" + p.getRun() + "\t" +
p.getAge());
}
}
}
}
}

STACK IN COLLECTION

]
Dat
[

196
]
Dat
[

197
Q. What is Stack?
Stack is an implementer class of List Collection and child of Vector class and it is
used for manage data in last in first out format

Stack provide some inbuilt method to us which help us to manage data in last in
first out

void push(E): this method is used for push data in stack


Object pop(): this method is used for remove top most data from stack. boolean
isEmpty(): this method is used for check string is empty or not if empty return
true otherwise return false.

package org.techhub; import


java.util.*;
public class StackApplication {
public static void main(String[] args) {
Stack s = new Stack();
do {
Scanner xyz = new
Scanner(System.in);
System.out.println("1:PUSH");
System.out.println("2:POP");
System.out.println("3:Display");
System.out.println("Enter your choice");
int choice = xyz.nextInt();
switch (choice) {
case 1:
System.out.println("Enter data in stack");
int data = xyz.nextInt();
s.push(data);
break;
case 2:
boolean b = s.isEmpty();
[ Dat

if (b) {
]
e
System.out.println("Stack is
empty"); 173

}
else {
Object obj = s.pop();
System.out.println("Deleted data is " + obj);
}
break;
case 3:
ListIterator li = s.listIterator(s.size());
while (li.hasPrevious()) {
Object obj = li.previous();
System.out.println(obj);
}
break;
default:
System.out.println("Wrong choice");
}
} while (true);
}
}

]
Date
[

174
SET IN COLLECTION

]
Date
[

175
Q. What is set collection?
Set Collection cannot store duplicated data in it and not maintain index for data
storing and maintain a hashcode as well as it is responsible for generate data
randomly.

[ Dat
THERE ARE THREE TYPES OF SET COLLECTION

]
e
1. HashSet.
2. LinkedHashSet.
3.TreeSet.

1. HashSet: HashSet Collection can store unique data in collection but generate
random sequence of data at run time. package org.techhub; import java.util.*;
public class HashSetApplication {
public static void main(String[] args) {
HashSet hs = new HashSet();
hs.add(10);
hs.add(5);
hs.add(33);
hs.add(22);
hs.add(33);
hs.add(45);
hs.add(300);
hs.add(60);
hs.add(5);
for(Object obj:hs) {
System.out.println(obj);
}
}
}

CONSTRUCTOR OF HASHSET COLLECTION

176
HashSet(): this constructor create empty set with a default capacity 16 and load
factor 0.75 and internally HashSet use HashMap in background
Q. what is load factor?
The Load factor is a measure that decides when to increase the HashTable capacity
to maintain the search and insert operation complexity of O(1)
HashSet(int initialCapacity,float loadFactory): if programmer use this
constructor then programmer can set initial capacity and load factor as per his
choice public HashSet(Collection<? extends E> c) : this constructor help us to
copy the content from another collection in HashSet and the default capacity is
16 and load factor is 0.75%
Example: WAP to store 10 values in ArrayList and remove the duplicated values.
package org.techhub; import java.util.*;
public class HashSetApplication { public
static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10); al.add(20);
al.add(10); al.add(20);
al.add(30); al.add(40);
al.add(10);
HashSet hs = new HashSet(al);
for(Object obj:hs) {
System.out.println(obj);
}
}
}
2. LinkedHashSet: LinkedHashSet Collection can store unique data but arrange
data sequence as per user sequence.
package org.techhub; import java.util.*;
[ Dat
]
e

177
public class HashSetApplication {
public static void main(String[] args) {
LinkedHashSet hs = new LinkedHashSet();
hs.add(10);
hs.add(20); hs.add(30);
hs.add(10);
hs.add(40); hs.add(50);
for(Object obj:hs) {
System.out.println(obj);
}
}
}
CONSTRUCTOR OF LINKEDHASHSET
LinkedHashSet (): create LinkedHashSet with a default capacity provided by java and
default load factor
the default capacity of LinkedHashSet is 16 and load factor of LinkedHashSet is 0.75
LinkedHashSet(int initialCapacity): here user can set initial Capacity as per his choice
with default load factor 0.75
LinkedHashSet(Collection): this constructor is used for create LinkedHashSet
with existing collection data and avoid duplicated values.
3.TreeSet: TreeSet Collection can store data in ascending order and not allow duplicated
data and TreeSet not accept null value also.
package org.techhub; import
java.util.*;
public class HashSetApplication {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(5); ts.add(2); ts.add(3); ts.add(1);

[ Dat
]
e
178
ts.add(10);
ts.add(12); ts.add(11);
Iterator i=ts.iterator();
while(i.hasNext()) {
Object obj=i.next();
System.out.println(obj);
}
}
}
if we want to arrange TreeSet data in descending order then we have method name
as
descendingSet() and this method return reference of NavigableSet interface and
NavigableSet interface arrange data in descending order
package org.techhub; import java.util.*;
public class HashSetApplication {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(5);
ts.add(2); ts.add(3);
ts.add(1); ts.add(10);
ts.add(12);
ts.add(11);
NavigableSet navSet=ts.descendingSet();
Iterator i=navSet.iterator(); while(i.hasNext()) {
Object obj=i.next();
System.out.println(obj);
}
}
}
Q. what is diff between TreeSet, LinkedHashSet and HashSet

FEATURE HASHSET LINKEDHASHSET TREESET ]


Dat
[

206
Internal working HashSet use LinkedHashSet uses TreeSet uses a
internally LinkedHashMap TreeMap for
HashMap for internally for storing storing data
storing objects objects
When to use When we want to When we want When we want to
maintain insertion maintain insertion arrange data in
order then order then we can ascending order
HashSet is not use LinkedHashSEt then we can use
beneficial TreeSet
Order Does not maintain Maintain element Maintain order in
element order order ascending order
Complexity HashSet gives O LinkedHashSet gives TreeSet use Time
(1) for insertion, insertion, removing, complexity O
remove and operation time (long (n));
retrieve complexity required
O (1)
Performance HashSet perform is LinkedHashSet TreeSet
better than slower than Tree performance is
LinkedHashSet because it maintains better than
and TreeSet doubly linked list LinkedHashSet
internally except insertion
and remove
Null elements HashSet allow LinkedHashSEt allow TreeSet not allow
only one null value only one null value null value.

Example: Write a Program to create LinkedHashSet and store book information in


it and display we have Book as pojo class and store 5book inform in
LinkedHashSet and display it and book contain id, name, author and price.
package org.techhub.bookapp;
import java.util.*; class
Book{ private int id;
private String name; ]
Dat
[
private String author;

207
public Book() {
}
public Book(String name,String author,int id,int price) {
this.name=name;
this.author=author; this.id=id;
this.price=price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
private int price;
} ]
Dat
[

208
public class BookSetApplication { public
static void main(String[] args) {
LinkedHashSet hs = new LinkedHashSet();
hs.add(new Book("ABC","MNO",1,100)); hs.add(new
Book("PQR","STV",2,200)); hs.add(new
Book("XYZ","POS",3,200)); for(Object obj:hs) {
Book b=(Book)obj;
System.out.println(b.getId()+"\t"+b.getName()+"\t"+b.getAuthor()+"\t"+b.g
etPrice());
}
}
}

COLLECTIONS CLASS

]
Dat
[

209
]
Dat
[

210
Collections class
Collections class is a Utility class in java which is used for perform operation on
Collection framework
Like as perform sorting of collection, reverse collection, find max value from collection,
finding min value from collection etc.

Q. what is utility class?

]
Dat
[

211
utility class means a class cannot create its object means it contain private constructor
without logic and it contain some static methods which perform some tasks called as
utility class.
Example: Create ArrayList and store 5 values in it and perform sorting on it.
package org.techhub.bookapp; import
java.util.*;
public class SortCollectionApp {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(5);
al.add(10); al.add(9);
al.add(22); al.add(7);
System.out.println("Before Sorting");
for(Object obj:al) {
System.out.println(obj);
}
Collections.sort(al);
System.out.println("After Sorting");
for(Object obj:al) {
System.out.println(obj);
}
}
}

[ Dat
]
e
184
Example: Create ArrayList and find max value from ArrayList using Collections
class.
If we want to find max value using ArrayList we have Collections.max() method
Syntax: Object data= Collections.max (Collection):

package org.techhub; import java.util.*;


public class FindMaxApp { public static
void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10); al.add(20);
al.add(30); al.add(40);
al.add(50); al.add(500);
al.add(40);
Object obj = Collections.max(al);
System.out.println("Max value from collection is "+obj);
}
}
Example: WAP to reverse the Collection using Collections class package
org.techhub;
import java.util.*; public class FindMaxApp
{ public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10); al.add(20);
al.add(30); al.add(40);
al.add(50); al.add(500);
al.add(40);
System.out.println("Before Reverse");
for(Object obj:al) {
System.out.println(obj);
}
Collections.reverse(al);
System.out.println("After Reverse");
for(Object obj:al) {
System.out.println(obj);
}
}
}
Example: WA to create class name as Employee with id, name and salary and
store 5 employee details in ArrayList collection and sort employee data
package org.techhub; import java.util.*; class Employee { private int ]
Dat
id; [
private String name;

213
public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {

return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
public Employee(int id, String name, int sal) {
this.id = id;
this.name = name;
this.sal = sal;
}
}
public class EmployeeSortApplication {
public static void main(String[] args) {
]
ArrayList al = new ArrayList(); al.add(new Date
Employee(1,"ABC",10000)); al.add(new [
Employee(2,"PQR",20000)); al.add(new
Employee(4,"STV",10000)); al.add(new 186
Employee(3,"MNO",40000));
System.out.println("Before Sorting");
for(Object obj:al) {
Employee e=(Employee)obj;
System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getSal());
}
Collections.sort(al);
System.out.println("After Sorting");
for(Object obj:al) {
Employee e=(Employee)obj;
System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getSal());
}
}
} if we think about above code, we get Runtime exception i.e.,
ClassCastException because if we think Collections.sort() method then this
method cannot sort

collection if collection contain user defined object means as per our example
Collections contain Employee object and Employee object contain three types of
data i.e. id, name and salary so Collections.sort() method cannot predicate sorting
apply on which field means by id or by salary or by name so this is major
Collections.sort() method generate ClassCastException at run time when we try
to sort Collections with user defined object. so, if we want to solve this problem,
we have two interfaces
1. COMPARABLE
2. COMPARATOR

1.Comparable interface.
Comparable interface is used for sort the user defined objects using a particular
field by Collections.sort() method
Steps to work with Comparable interface
]
Dat
1. add java.lang package in application [
import java.lang.*; note: java.lang is a default package of java
[ Dat
]
e

215
so we not need to import it.

2. Create class and implements Comparable interface in it class


Employee implements Comparable {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;

188

} public int getSal()


{
return sal;
} public void
setSal(int sal) { this.sal
= sal;
}
private int sal;
public Employee(int id, String name, int sal) {
this.id = id;
this.name = name;
this.sal = sal;
}
}
3. Override its compareTo() method and perform object comparison: int
compareTo(Object obj): this method is used for perform comparison if we
want to work with compareTo() method we have some following rules.
1. if first object is greater than second object value then return 1
2. if first object is less than second object then return -1
3. if first is equal with second then return 0

package org.techhub;
import java.util.*;
class Employee implements Comparable {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;

]
Dat
[

217
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
public Employee(int id, String name, int sal) {
this.id = id;
this.name = name;
this.sal = sal;
}
@Override
public int compareTo(Object o) {
Employee e=(Employee)o;
if(this.id>e.id) {
return 1;
}
else if(this.id<e.id) {
return -1;
}
else {
return 0;
}
}
}

]
Dat
[

218
public class EmployeeSortApplication { public
static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Employee(1,"ABC",10000));
al.add(new Employee(2,"PQR",20000));
al.add(new Employee(4,"STV",10000));
al.add(new Employee(3,"MNO",40000));
System.out.println("Before Sorting");
for(Object obj:al) {
Employee e=(Employee)obj;
System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getSal());
}
Collections.sort(al);
System.out.println("After Sorting");
for(Object obj:al) {
Employee e=(Employee)obj;
System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getSal());
}
}
}
Example: WAP to create class name as Player with id, name and run and store 5
player object in ArrayList collection and sort player by using its run.

import java.util.*;
class Player implements Comparable {
private int id;
private String name;
public Player(String name,int id,int run) {
this.name=name;
this.id=id; this.run=run;
}
]
Dat
[

219
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRun() {
return run;
}
public void setRun(int run) {
this.run = run;
}
private int run;
@Override
public int compareTo(Object o) {
Player p=(Player)o;
if(this.run>p.run) {
return 1;
}
else if(this.run<p.run) {
return -1;
}
else {
return 0;
}
]
Dat
[

220
}
} public class PlayerSortingApplication {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Player("a",1,3000));
al.add(new Player("b",2,2000));
al.add(new Player("c",3,1000));
al.add(new Player("e",4, 4000));

]
Dat
[

221
al.add(new Player("f",5,2500));
System.out.println("Display player without
sorting");
for(Object obj:al) {
Player p=(Player)obj;
System.out.println(p.getId()+"\
t”+e.getName()+"\t"+p.getRun());
}
Collections.sort(al);
System.out.println("Display player After
sorting");
for(Object obj:al) {
Player p=(Player)obj;
System.out.println(p.getId()+"\
t”+e.getName()+"\t"+p.getRun());
}
}
}
2.Comparator interface.
Comparator is same like as Comparable interface which is used for sort collection with
user defined object but the major diff between Comparable and Comparator is used for
perform sorting using a multiple attributes of class

Steps to Comparator
1) add the java.util package in application
import java.util.*;
2) Create class and implement Comparator interface in it.
Here we want to sort Player by using id and run means we required player sorting
by two attributes one is by id and one is by run so here we required to create two
different classes one class for SortById and one class for SortByRun and we have
to implement Comparator interface in it.

class SortById implements Comparator{


}
class SortByRun implements Comparator{
}

[ Dat
]
e
3) override its compare() method

193

compare() method is a member of Comparator interface which accept two


parameters
int compare(Object obj1,Object obj2) Rules
of compare() method
1) if first object is greater than second object then return 1
2) if first object is less than second object then return -1
3) if first object is equal with second object then return 0 4) use
Collections.sort() method in given fashion Collections.sort(List, Comparator):
List: pass list or its implementor collection
Comparator: pass Comparator reference or its implement class object
Complete Source code. package org.techhub; import
java.util.Comparator;
public class SortById implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Player p1 = (Player) o1;
Player p2 = (Player) o2;
if (p1.getId() > p2.getId()) {
return 1;
}
else if (p1.getId() < p2.getId()) {
return -1;
} else {
return 0;
}
}
}
[ Dat
]
e
import java.util.Comparator;
public class SortByRun implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Player p1=(Player)o1;

194
Player p2=(Player)o2;
if(p1.getRun()>p2.getRun()) {
return 1;
}
else if(p1.getRun()<p2.getRun()) {
return -1;
}
else {
return 0;
}
}
} package
org.techhub; import
java.util.*; class
Player {
private int id; private String name;
public Player(String name,int id,int run) {
this.name=name;
this.id=id;
this.run=run;
}
public int getId() {
return id;
}
]
public void setId(int id) { Date
this.id = id; [
}
public String getName() { 195
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRun() {
return run;
}
public void setRun(int run) {
this.run = run;
}
private int run;
} public class PlayerSortingApplication
{
public static void main(String[] args) {
ArrayList al = new ArrayList(); al.add(new
Player("a",1,3000)); al.add(new
Player("b",5,2000)); al.add(new
Player("c",3,1000)); al.add(new
Player("e",2, 4000)); al.add(new
Player("f",4,2500));
System.out.println("Display player without sorting");
for(Object obj:al) {
Player p=(Player)obj;
System.out.println(p.getId()+"\t”+e.getName()+"\t"+p.getRun());
}
System.out.println("Display player Sorted by Id ");
SortById sid= new SortById();
Collections.sort(al,sid);
for(Object obj:al) {
Player p=(Player)obj;
System.out.println(p.getId()+"\t”+e.getName()+"\t"+p.getRun());
}
System.out.println("Display player Sorted by Run");
SortByRun sr = new SortByRun();
Collections.sort(al,sr);
for(Object obj:al) {
Player p=(Player)obj; ]
Dat
System.out.println(p.getId()+"\t”+e.getName()+"\t"+p.getRun()); [

226
}
}
}
Q1. WAP to create class name as Product with field id, name, price and store
5 product info in ArrayList sort it by using id and price
case 1: sort by id case 2: sort by price

package Comparator; import


java.util.Comparator;
public class SortById implements Comparator<Object>
{ public int compare(Object o1, Object o2) {
Product pc1 = (Product) o1;
Product pc2 = (Product) o2;
if (pc1.getId() > pc2.getId()) {
return 1;
} else if (pc1.getId() < pc2.getId()) {
return -1;
} else {
return 0;
}
}
}
package Comparator; import java.util.Comparator;
public class SortByPrice implements Comparator {
public int compare(Object o1, Object o2) {
Product pc1 = (Product) o1;
Product pc2 = (Product) o2; if
(pc1.getPrice() > pc2.getPrice()) {
return 1;
} else if (pc1.getPrice() < pc2.getPrice()) {
return -1; } else {
return 0;
[ Dat
]
e

197
}
}
} package Comparator
import java.util.*; class
Product { private int id;
private String name;
private int price;
public Product(int id, String name, int price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
public class ProductApp {
]
Dat
[

228
@SuppressWarnings("unchecked")
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
ArrayList<Product> al = new ArrayList<Product>();
int id = 0, price = 0;
String name = null;
Product[] pc = new Product[5];
for (int i = 0; i < pc.length; i++) {
System.out.println("Enter Product id, name, price");
pc[i] = new Product(id, name, price);
pc[i].setId(id = sc.nextInt()); pc[i].setName(name =
sc.next());
pc[i].setPrice(price = sc.nextInt());

al.add(pc[i]);
}
System.out.println("Display player without sorting");
for (Object obj: al) {
Product p = (Product) obj;
System.out.println(p.getId() + "\t" + p.getName() + "\t" +
p.getPrice());
}
System.out.println("1. Sort by id");
System.out.println("2. Sort by price");
System.out.println("Enter choice");
int choice = sc.nextInt(); switch
(choice) { case 1:
System.out.println("Display player Sorted by Id");
SortById sid = new SortById();
Collections.sort(al, sid); for (Object obj:
al) {
]
Dat
[

229
Product p1 = (Product) obj;
System.out.println(p1.getId() + "\t" + p1.getName() +
"\t" + p1.getPrice());
}
break;
case 2:
System.out.println("Display player Sorted by price");
SortByPrice sp = new SortByPrice();
Collections.sort(al, sp); for
(Object obj: al) { Product p2 =
(Product) obj;
System.out.println(p2.getId() + "\t" + p2.getName() +
"\t" + p2.getPrice());
}
break;
default:
System.out.println("wrong choice");
}
}
}
Example: WAP to create student class and store 5 student objects in Collection
and arrange sorting using id and per.
package org.techhub.student; import
java.util.Comparator;
public class SortById implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.getId()>s2.getId()){
return 1;
}
]
Dat
[

230
else if(s1.getId()<s2.getId()) {
return -1;
}
else {
return 0;
}
}
}
package org.techhub.student; import
java.util.Comparator;
public class SortByPer implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.getPer()>s2.getPer()) {
return 1;
}
else if(s1.getPer()<s2.getPer()) {
return -1;
}
else {
return 0;
}
}
} Student.java package
org.techhub.student; public
class Student { private
int id; private String
name;
public Student(String name,int id, float per) {

]
Dat
[

231
this.name=name;
this.id=id;
this.per=per;
} public int getId()
{ return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPer() {
return per;
}
public void setPer(float per) {
this.per = per;
}
private float per;
}
package org.techhub.student; import
java.util.*; public class
StudentSortingApplication { public static
void main(String[] args) {
ArrayList al = new ArrayList();
Student s1 = new Student("Ram",1,90.5f);
Student s2 = new Student("Ganesh",3,70.5f);
Student s3 = new Student("Rajesh",2,60.5f);

]
Dat
[

232
Student s4 = new Student("Sandeep",4,50.5f);
Student s5 = new Student("Sangram",5,76.5f);
al.add(s1); al.add(s2); al.add(s3); al.add(s4);
al.add(s5);

]
Dat
[

233
System.out.println("Student Record without sorting"); for(Object
obj:al) {
Student s=(Student)obj;
System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getPer());
}
System.out.println("Student Record
using sorting");
SortById si = new SortById();
Collections.sort(al,si);
System.out.println("Student Record Sorted using id"); for(Object
obj:al) {
Student s=(Student)obj;
System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getPer());
}
SortByPer sp = new SortByPer();
Collections.sort(al, sp);
System.out.println("Student Record Sorted using Per"); for(Object
obj:al) {
Student s=(Student)obj;
System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getPer());
}
} }

Date
]
[

203
GENERICS IN COLLECTION

]
Dat
[

236
Q. what is generics?
Generics are a concept launched in JDK 1.5 version of java which is used for to avoid
ClassCastException at run time.

Note: when we use Collection then we store data in the form of Object as well as we
retrieve data in the form of Object and when we want to perform any operation on
Object then we need to convert object in its original format then there is possibility
of ClassCastException at run time.

Example:
package org.techhub.genapp; import
java.util.*; public class GenTestApp {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10); al.add(20);
al.add(30);
al.add(5.4f); //ClassCastException may be
occur here
al.add(new java.util.Date());
al.add(false);
al.add("good");
al.add(50);
Integer sum=0;
for(Object obj:al) {
sum = sum+(int)obj;
}
System.out.printf("Sum of all values is
%d", sum);
}
} if we think about above code, we get exception at run time ClassCastException
at run time because we have ArrayList and it contain different kind of data and we
try
Object class in to integer when we retrieve data from collection so first 10 ,20 and 30
[ Dat
]
e

can convert in Integer but we have fourth member i.e., 5.4 cannot convert in

205
integer so JVM generate ClassCastException at run time so if we want to solve this
problem, we have two solutions.

WE WANT TO SOLVE CLASSCASTEXCEPTION WE HAVE TWO


SOLUTIONS.
1) Use instanceof operator
2) Use Generics

What is instanceof operator?


instance of operator is used for check object belongs with a particular type or not if
object belongs with a specified type, then return true otherwise return false.
package org.techhub.genapp; import
java.util.*; public class GenTestApp {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10); al.add(20);
al.add(30);
al.add(5.4f); //ClassCastException may be
occur here
al.add(new java.util.Date());
al.add(false);
al.add("good"); al.add(50);
Integer sum=0; for(Object
obj:al) { if(obj instanceof
Integer) {
sum = sum+(int)obj;
}
}
System.out.printf("Sum of all values is
%d", sum);
}
}

[ Dat
]
e
206

Q. What is generics?
generics help us to apply restrictions on collection to work with a particular type
at compile time so it 100% avoid ClassCastException at run time and generics can
denoted by using < > bracket. package org.techhub.genapp; import java.util.*;
public class GenTestApp {
public static void main(String[] args) {
ArrayList<Integer> al = new
ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(50);
Integer sum=0;
for(Integer obj:al) {
sum = sum+obj;
}
System.out.printf("Sum of all values is
%d", sum);
}
}
If we think about above code, we lost the main feature of Collection i.e., ability to
store different type of data. if we want to store a different type of data in
Collection using a generic then we can create POJO class and store different type
of data in POJO class and use generics with collection of POJO type shown in
following code
Suppose we want to store integer, string and float type of data in Collection using a
Generics not other type

package org.techhub.genapp;
import java.util.*; class
Data {
private int id;
private String name; public int getId() {
[ Dat
]
e
207
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPer() {
return per;
}
public void setPer(float per) {
this.per = per;
}
private float per;
public Data() {
}
public Data(String name,int id,float per) {
this.name=name;
this.id=id;
this.per=per;
}

}
public class GenTestApp {
public static void main(String[] args) {
ArrayList<Data> al = new ArrayList<Data>();
Data d1 = new Data("ABC",1,50.5f);
Data d2 = new Data("MNO",2,45.5f);
Data d3 = new Data("PQR",3,50.4f);
al.add(d1);

]
Date
[

208
al.add(d2);
al.add(d3); for(Data
d:al) {
System.out.println(d.getId()
+"\t" +d.getName()+"\t"+ d.getPer());
}
}
}

TYPES OF GENERICS IN JAVA


1. Class with Generics
2. Integer with Generics
3. Wild Card Generics
a) bounded generics
b) Unbounded generics

If we think about above types means user can create own class as generic class,
own interface as generics interface etc.
If we want to create own class as generic class and own interface as generic
interface, we have some inbuilt generics classes provided by java to us.

E: E stands generic element


T: T stands for generic type
K: K stands for Generic Key V:
V stands Generic value.

How to create user class as Generic class


[ Dat
]
e
if we want to create user class as generic class, we have following syntax class 209
classname<E> {
}
package org.techhub.genapp;
class Test<E>{ void
add(E e) {
System.out.println("Value is "+e);
}

}
public class ClassWithGenericApp { public
static void main(String[] args) { Test
<Integer>t1 = new Test<Integer>();
t1.add(100);
t1.add(200);
//ArrayList<Integer> al = new
ArrayList<Integer>();
}
}

How to create user interface as Generic interface


Syntax: interface
interfacename<E> { return
type methodname(E e);
}
The benefit of interface with generics is we can customize interface
method parameter type in every implementer class package
org.techhub.genapp; interface Area<E> {
void setRadius(E e);
}
class Circle implements Area<Integer> {
@Override
[ Dat
]
e
public void setRadius(Integer e) {
System.out.println("Integer radius is "+e);
}
}
class Cirm implements Area<Float> {
@Override
public void setRadius(Float e) {
System.out.println("Float radius is "+e);
}
}
public class InterfaceWithGenApp {

210
public static void main(String x[]) {
Circle c = new Circle();
c.setRadius(5); Cirm cm = new
Cirm();
cm.setRadius(5.4f);
}
}

]
Date
[

211
OBJECT CLASS IN COLLECTION

Q. What is Object class?


Object class is parent class of every class in JAVA
Q. Why Object class is parent of every class in JAVA?
Because it contains some methods those required in daily operations so Object class
is parent class of every class in JAVA.

1.int hashCode() 2.boolean equals() 3.String toString() 4.void wait() 5.void


notify() 6.void notifyAll()
7. Object clone() 8) Class getClass() 9. static{ } 10. void finalize()
Important of equals() and hashCode() method of Object class
Example: we want to create class name as Test with one parameterized
constructor and we want to create two objects of Test class and compare them and
check objects are equal or not if objects are equal then we want to show message
object are equal otherwise show message objects are not equal. package
org.techhub.genapp;
class Test {
int no;
Test(int no) {
this.no = no;
}
}
public class TestApp {
public static void main(String[] args) {
Test t1 = new Test(100);
Test t2 = new Test(100);
if (t1 == t2) {
System.out.println("Objects are equal");
}
else {
System.out.println("Objects are not
equal");

[ Dat
]
e
}

212

}
} if we think about above code, we have two objects name as t1 and t2 with
values 100 means value of t1 object is 100 and value of t2 object is 100 and we
have statement t1==t2 but we get answer objects are not equal even we have
values of objects are equal or similar.
How it is possible?
[ Dat
]
e
Because in the case of java object comparison not perform by value. Object
comparison perform by using its hash code. Q. what is hash code?

Hash code is unique integer number provided by JVM to every memory block and
it is like as address means every object has its own hash code and JVM not
generate same hash code for different object so as per our example we have two
objects t1 and t2 and internally JVM generate different hash code for t1 and
different hash code for t2 so when we compare t1 and t2 with each other than
JVM compare its hash code not value and internally they have a different hash
code so we get answer objects are not equal.

Q. Can we see the hash code of object generated by JVM?


Yes, we can see the hash code of Object generated by JVM and for that we have
method name as
System.identityHashCode(object)

Q. How we can compare objects in java if JVM not generate same hashcode?
if we want to perform object comparison using Java, we have solution java provide
two methods to us from Object class name as

213
int hashCode(): this method can generate same hash code when two objects are
equal and if not then generate a different hash code so developer need to override
this method. boolean equals(Object): this method is used for perform
comparison of two objects using their values just we need to override from
Object class Before work with equals () and hashCode() method we have some
thumb rules provided by java.
1. If two objects are equal then their hash code must be equal 2. If
values of two objects are same then their hash code must be same.

Output
Hash code of t1 1227229563
Hash code of t2 971848845
Objects are equal

if we think about above code we have output Objects are equal because we
override equals() methods from Object class and we compare the values of t1 and
t2 manually and we found values of t1 and t2 same so this method return true at
function calling point means in if block so we get output Objects
are equal.

Note: if we think about above output so above code not satisfy any thumb rule
because the thumb rule is if we have two object values same then their hash code
must be same but in above output, we have different hash code even we have
same objects.

]
Date
[

214
Note: JVM always generate different hash code for every object if we have same
values or different values
So In this case Java suggest us override one more method from Object class name
as int hashCode() and satisfy above thumb rule if values of object same then hash
code must be same so we need to override hashCode() method and generate same
hash code when object values are same otherwise generate different hash code
show in following example.

Example: package
org.techhub.genapp;
class Test extends java.lang.Object {
int no;
Test(int no) {
this.no = no;
}
public boolean equals(Object obj) {
Test t=(Test)obj;
if(this.no==t.no) {
return true;
}
else {
return false;
}
}
public int hashCode() {
return no*1000;
}
}
public class TestApp { public static void
main(String[] args) {
Test t1 = new Test(100);
Test t2 = new Test(100);
System.out.println("JVM HashCode"); ]
Dat
[
System.out.println("Hash code of t1 "+System.identityHashCode(t1));

249
System.out.println("Hash code of t2 "+System.identityHashCode(t2));
if (t1.equals(t2)) {
System.out.println("Objects are equal ");
System.out.println("User Hashcode is ");
System.out.println("Hashcode with
t1 "+t1.hashCode());
System.out.println("Hashcode with
t2 "+t2.hashCode());

} else {
System.out.println("Objects are not equal");
System.out.println("User Hashcode is ");
System.out.println("Hashcode with
t1 "+t1.hashCode());
System.out.println("Hashcode with
t2 "+t2.hashCode());

}
}
}
Output:
JVM HashCode
Hash code of t1 942731712
Hash code of t2 971848845
Objects are equal
User Hashcode is
Hashcode with t1 100000
Hashcode with t2 100000

If we think about above code, we have two types of hash code one hash code
generated by JVM and one hash code generated by developer so, we have t1 and
t2 has same value so developer generate same hash code for t1 and t2 for satisfy
thumb rule of java but JVM generate the different hash code for t1 and t2 even
we have same values of object.

Q. Why developer need to generate own hash code and why developer need to
satisfy thumb rule of java?

[ Dat
]
e
216
Developer needs to generate user defined hash code for cover the limitation of Set
collection
Because when we store the user defined objects in Set Collection then Set
collection can store duplicated data.

package org.techhub.bookapp;
import java.util.*; class
Book{ private int id;
private String name;
private String author;
public Book() {
}
public Book(String name,String author,int id,int price) {
this.name=name;
this.author=author; this.id=id;
this.price=price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name; ]
Dat
[
}
public String getAuthor() {

251
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
private int price;
}
public class BookSetApplication { public
static void main(String[] args) {
LinkedHashSet hs = new LinkedHashSet();
hs.add(new Book("ABC","MNO",1,100)); hs.add(new
Book("ABC","MNO",1,100)); hs.add(new
Book("ABC","MNO",1,100)); hs.add(new
Book("ABC","MNO",1,100)); hs.add(new
Book("ABC","MNO",1,100)); hs.add(new
Book("PQR","STV",2,200)); hs.add(new
Book("XYZ","POS",3,200));
for(Object obj:hs) {
Book b=(Book)obj;

System.out.println(b.getId()+"\t"+b.getName()+"\t"+b.getAuthor()+"\t"+b.g
etPrice());
}
}
}
Output
1 ABC MNO 100

]
Dat
[

253
Note: if we think about above code we have LinkedHashSet Collection and we
store user defined objects in it so LinkedHashSet allow duplicated data because
when we work with Set Collection and when we add data in set collection then set
first check its hash code and if set collection found the same hash code then set
consider object is duplicated but if we think about object then JVM generate
unique hash code for every object when we add the object in set collection then set
found different hash code with every object so there is possibility set can store
duplicated data.
means when user not generate own hash code then set collection compare object
with hash code generated by JVM and JVM generate different hash code for ever
object even values of object are same so set can store duplicated data.

in above
diagram we have multiple object with same data but different hash code generate
by JVM so Set collection compare hash code not data and set not found duplicated
hash code so set consider data is unique even values of object are same so if we
want to solve this problem Java suggest us override equals() and hashcode()
method. boolean equals(): using equals() method we can compare object data and
return true if two object data found same int hashCode(): this method can generate
same hash code if two objects are equal Note: internally equals() and hashCode()
has bond they call with each other so, when user generate own hash code then set
not compare object using JVM hash code.
package org.techhub.bookapp;
import java.util.*; class
Book { private int
id; private String
name; private ]
Dat
[
String author;

254
public Book() {
}
public Book(String name, String author, int id, int price) {
this.name = name;
this.author = author; this.id
= id;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
private int price; ]
Dat
[
public int hashCode() {

255
return id;
}
public boolean equals(Object obj) {
Book b = (Book) obj;
if (this.id == b.id && this.price == b.price &&
this.name.equals(b.name)) {
return true;
}
else {
return false;
}
}
}
public class BookSetApplication { public
static void main(String[] args) {
LinkedHashSet hs = new LinkedHashSet();
hs.add(new Book("ABC", "MNO", 1, 100));// 1562557367 - hash code generated
JVM
hs.add(new Book("ABC", "MNO", 1, 100));// 942731712 - hash code generated
JVM
hs.add(new Book("ABC", "MNO", 1, 100));// 971848845 - hash code generated
JVM
hs.add(new Book("ABC", "MNO", 1, 100));// 1910163204 - hash code generated
JVM
hs.add(new Book("ABC", "MNO", 1, 100));// 305623748- hash code generated
JVM
hs.add(new Book("PQR", "STV", 2, 200));// 758529971-hash code generated
JVM
hs.add(new Book("XYZ", "POS", 3, 200));// 2104457164-hash code generated
JVM
for (Object obj : hs) {

]
Dat
[

256
Book b = (Book) obj;
System.out.println(b.getId() + "\t" + b.getName() + "\t" + b.getAuthor() + "\t" +
b.getPrice() + "\t”+ System.identityHashCode(b));
}
}
}
Object clone() method : clone() method is used for create duplicated copy of objects.

Q. why we required performs object cloning?


Sometime if we apply multiple references on single object and if we try
performing change on object using any one reference then object previous content
may be lost so if we want to avoid this problem, we can use object cloning concept.

if we think about above code we have statement Square s1 = new Square() here we
created object and store its address in s1 reference i.e., 10000 in s1 reference and we
have statement s1.setValue(10) means we store 10 value in s1 object whose address is
10000 and we have one more statement i.e., Square s2=s1 means we assign s1 reference
object in s2 reference means s2 has own address space i.e., 10000 and when we call
statement s2.setValue(5) means we store 5 value on object whose address is 10000 and
we have one more statement s1.showSquare() means we call 10000.showSquare() so
10000 has last value i.e., 5 so we get finally output Square is 25 means we lost 10 value
of object stored by s1 reference means s2 reference override object previous value

[ Dat
]
e
222

So, if we want to solve this problem, we can use object cloning concept.

How to perform Object clone in JAVA?


If we think about object cloning in java, we have following steps.

1.Create class and implement Cloneable interface in it.


Note: Cloneable is marker interface in java.

Q. What is marker interface?


A marker interface is an interface that doesn't have any methods or constants inside
it. It provides run-time type information about objects, so the compiler and JVM have
additional information about the object. A marker interface is also called a tagging
interface.
class Square implements Cloneable {
int no;
void setValue(int x) {
no=x;
}
void showSquare() {
System.out.printf("Square is %d\n", no*no);
}
}
2. Define method in class and return same class reference from it.
class Square implements Cloneable
{ int no;
void setValue(int x) {
no=x;
}
void showSquare() {
System.out.printf("Square is %d\n",no*no);
}
public Square getInstance() throws CloneNotSupportedException
[ Dat
{ //Object obj=this.clone();
]
e

223
//Square s=(Square)obj;
//return s;
return (Square)this.clone();
}
} if we think about above code we have getInstance() method which return clone
of object and handle the CloneNotSupportedException.
3. Call method which return object clone.

Note: if we think about Object cloning, we have two types of copy created in
memory.
1. Shallow copy: here shallow copy means duplicated copy of object
2. Deep copy: deep copy means original copy of object which is created by
new keyword.

Here we create object by using clone () method

Q. what is diff between object creation by new keyword and by clone()


method?
If we create object by a using a new keyword then JVM call constructor and if we
create object by using clone() method then JVM not call constructor.

String toString() method


This method is used for convert your object into string format so if we want to
convert your object with content in string format we have to override toString()
method of Object class and convert your object in string format.
[ Dat
]
e

224
package org.techhub.bookapp;
import java.util.ArrayList;
class Employee{ private int
id; private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;

public String toString() { return


"["+id+","+name+","+sal+"]";
}
}
public class ToStringApplication
{
public static void main(String[] args)
{ Employee emp = new Employee();
emp.setId(1); emp.setName("ABC"); ]
emp.setSal(10000); Date
[
System.out.println(emp); //emp.toString() - object class
}
225
}
Example of toString() with collection
package org.techhub.bookapp;
import java.util.ArrayList; class
Employee{ private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;

public String toString() {


return "["+id+","+name+","+sal+"]";
}

]
Date
[

226
}
public class ToStringApplication
{
public static void main(String[] args)
{ Employee emp = new Employee();
emp.setId(1);
emp.setName("ABC");
emp.setSal(10000);
Employee emp1 = new Employee();
emp1.setId(2);
emp1.setName("MNO");
emp1.setSal(20000);
Employee emp2 = new Employee();
emp2.setId(2);
emp2.setName("MNO");
emp2.setSal(20000);
ArrayList<Employee>al = new ArrayList<Employee>();
al.add(emp); al.add(emp1); al.add(emp2);
System.out.println(al);
}
}
static block and instance block

static block is a member of Object class and it is executed very first in program
means before main method also. package org.techhub.statapp;
public class StatApplication {
static {
System.out.println("I am static block");
}
public static void main(String[] args) {
System.out.println("I am main method");
[ Dat
]
e

227
} static block executes only once in application but instance block executes
every time.
when we create new object of class and instance block execute before constructor
of class.
package org.techhub.statapp; class
ABC {
//constructor
ABC() {
System.out.println("I am constructor");
}
//static block
static {
System.out.println("I am static block");
}//instance block
{
System.out.println("I am instance block");
}
}
public class StatApplication {
public static void main(String[] args) {
ABC a1 = new ABC();
ABC a2 = new ABC();
ABC a3 = new ABC();
ABC a4 = new ABC();
}
}
void finalize(): this method help us to perform garbage collections means this
call automatically when we perform garbage collection manually in code
means when
we call System.gc() method then JVM delete object memory package
org.techhub.statapp;
class ABC{
ABC(){ ]
Date
[

System.out.println("I am constructor"); 228


}
public void finalize() {
System.out.println("I am finalize method");
}

}
public class StatApplication { public static
void main(String[] args) {
ABC a1 = new ABC();
a1=null;
System.gc();
}
}

]
Date
[

229
QUEUE IN COLLECTION

Q. What is Queue?
Queue is a interface from java.util package and extends Collection interface and it
is used for manage data in FIFO order and it is ordered list of objects with use of
limited to inserting element and Queue use two points for inserting and deleting
element using rear we can insert data in queue and using front we can delete data
from Queue.

package org.techhub.statapp; import


java.util.*;
public class QueueApplication {
public static void main(String[] args) {
Queue<Integer> q = new PriorityQueue<Integer>();
int choice;
do {
Scanner xyz = new Scanner(System.in);
int value=xyz.nextInt();
q.add(value);
System.out.println("Do you
want to more elements");
choice=xyz.nextInt();
}
[ Dat

while(choice!=2);
]
e

230
for(Integer i:q) {
System.out.println(i);
}
}
}

]
Date
[

231
WRAPPER CLASSES IN JAVA
Q. What is wrapper classes?
Wrapper classes are some inbuilt classes which is used for perform conversion

THERE ARE TWO TYPES OF CONVERSION IN JAVA?


1) Primitive Type of conversion
2)Reference Type of conversion

1) Primitive Type of conversion


primitive conversion means those conversions perform between simple data type called
as primitive conversion.

THERE ARE TWO TYPES OF CONVERSION IN PRIMITIVE DATA TYPE

i) Implicit conversion: implicit conversion means those conversion perform


automatically by compiler called as implicit conversion.
Implicit conversion possible when we have larger type value at left hand side and
smaller type value at right hand side then compiler is able to perform conversion
automatically called as implicit conversion.

Example:
long a; int
b=100;
a=b;//implicit conversion

ii) Explicit conversion: those conversions perform manually by programmer


called as explicit conversion.
Explicit conversion means if we put larger value at right hand side and smaller value
at left hand side then compiler is unable to perform conversion then programmer
need to perform conversion force fully called as explicit conversion long a=100;
int b; b=(int)a; // explicit conversion Example:
[ Dat
]
e

]233
Dat
[

270
package org.techhub; public class TestConversionApp { public static void
main(String[] args) {
int a=100;
long b=a;//implicit conversion

int c;
long d=200;
c=(int)d;//explicit conversion

System.out.printf("B = %d\n", b);


System.out.printf("C = %d\n", c);
}

} sometime implicit or explicit conversion get failed if we have reference type of value
and if we want to convert this value in to primitive type and if we have primitive value
and if we want to convert that value in to reference type then implicit or explicit
conversion get failed and if we want to solve this problem then java provide us some
inbuilt classes called as wrapper classes.

package org.techhub; public class TestConversionApp {


public static void main(String[] args) {
String str="12345"; int a=(int)str;
System.out.println("a is "+a);
}
}
If we think about above code, we have statement name as String str=”12345” and we
have statement int a=(int)str; here we try to convert reference variable str in to primitive
type of integer and it is not possible so compiler will generate compile time error to us
so if we want to resolve this problem, we have to use wrapper classes
If we want to work with wrapper classes, we have following class hierarchy.

If we think about above diagram, it indicates it is wrapper classes

THERE ARE TWO TYPES OF CONVERSION IN WRAPPER CLASSES


1)Auto boxing
2)Auto unboxing

1)Auto boxing: Autoboxing means if we convert primitive type of value in


to reference type called as autoboxing. int a=100;
Integer b=a; //auto boxing

If we think about code, we have statement int a=100 here a is primitive of variable
and b is reference type of variable so here a convert automatically b means primitive
type of value convert in reference type of value so it is auto boxing

2)Auto unboxing: Auto unboxing means if we convert reference value to primitive


type called as auto unboxing.
package org.techhub;
public class TestConversionApp { public
static void main(String[] args) {
int a=100;
Integer b=a; //auto boxing
[ Dat
]
e

]
Dat
[

235

272
Integer d=200; int c=d; //auto unboxing System.out.println("B is "+b);
System.out.println("C is "+c);
}
}
Auto boxing and auto unboxing get failed if we have different type of primitive and
different type of reference. package org.techhub; public class TestConversionApp {
public static void main(String[] args) { Float a=5.4f;
int b=a;//auto un boxing not work
}
}
if we think about above code auto unboxing not working because we have a float type
reference and integer type of primitive value so auto unboxing not work if we want to
perform conversion in this case then we have some inbuilt methods provided by
Number class to us called as xxxValue()

Number is abstract class and it is parent of all numeric classes in Wrapper class and it
contain some abstract methods those help us to perform conversion between reference
type to primitive type called as xxxValue()
public abstract int intValue(): This method help us to convert any Number reference
value to numeric primitive type integer
public abstract long longValue(): This method is used for convert any numeric
reference value to numeric primitive type of long public abstract float floatValue():
This method is used for convert any numeric reference value to numeric float value.
public abstract double doubleValue(): This method is used for convert any numeric
reference value to double value
public byte byteValue(): This method is used for convert any numeric reference
value to byte value
public short shortValue(): This method is used for convert any numeric
reference value to short value Example:
package org.techhub; public class TestConversionApp {
public static void main(String[] args) { Float a=5.4f;
int b=a.intValue();//convert floating reference value in to integer primitive
type.
System.out.println("Integer b is "+b); long d=a.longValue();
System.out.println("Long d is "+d);
}
}
valueOf() method: This method help us to convert primitive type to reference type and it
is a static method present in every wrapper class.
Example:
package org.techhub; public class TestConversionApp { public static void
main(String[] args) {
int a=100;
String s=String.valueOf(a); //convert integer primitive to type string reference
System.out.println("String s "+s);
Integer b=Integer.valueOf(a);//convert integer primitive to type Integer reference.
System.out.println("B is "+b);
Float c=Float.valueOf(a); //convert integer primitive to type float reference
System.out.println("C is "+c);
}
}

]
Dat
[

274
String toString(): this method is used for convert any reference to string . package
org.techhub;
public class TestConversionApp {
public static void main(String[] args) {
Integer a=10000;
String s=a.toString();//we convert integer value in to string value
System.out.println("String s "+s);
}
}
Q. what will be output of given code?
package org.techhub;
public class TestConversionApp {
static int a;
static Integer b;
public static void main(String[] args) {
System.out.println("A is "+a);
System.out.println("B is "+b);
}
}

String StringBuffer and StringBuilder


Q. What is String?
String is an immutable class of java.

Q. what is immutable class?


Immutable means once we initialize value cannot change later called as immutable
means when we initialize string, we cannot change its value later or cannot modify string
object so we can say string is immutable object of java.

IF WE WANT TO WORK WITH STRING, WE HAVE TWO WAYS.


i) By using initialization Example: String s=” Abc”; ii) By using new keyword

[ Dat
]
e
238

String s = new String(“ABC”); Example:


package org.techhub;
public class TestConversionApp {
public static void main(String[] args) {
String s="good";
String s1 = new String("good");
System.out.println("S is "+s);
System.out.println("S1 is "+s1);
}
}
Q. what is diff between string initialization by using a new keyword and by
using initialization technique?

[ Dat
]
e
When we use string by using an initialization technique then JVM create string
object in string pool constant and when we use new keyword then JVM create
string object in heap section of memory
Means when we initialize string and if two or more than two string has same
value then internally JVM create only one object in memory and share its
common reference in it and we use string by using a new keyword and if we have
string with same then JVM create different object every time for every string in
memory.

Source code

239
package org.techhub;
public class TestConversionApp {
public static void main(String[] args) {
String s1="good";
String s2="good";
System.out.println("Hashcode of s1 "+System.identityHashCode(s1));
System.out.println("Hashcode of s2 "+System.identityHashCode(s2));
}
}
if we think about above code, we have two string s1 and s2 with value good and
both references point to s1 and s2
OUTPUT:
Hashcode of s1 123961122
Hashcode of s2 123961122

Hashcode of s1 and s2 is same so the conclusion is we can say s1 and s2 points to


same memory. Example

package org.techhub;
public class TestConversionApp {
public static void main(String[] args) {
String s1=new String("good");
String s2=new String("good");
System.out.println("Hashcode of s1 "+System.identityHashCode(s1));
System.out.println("Hashcode of s2 "+System.identityHashCode(s2));
}
}
Output:
Hashcode of s1 123961122
Hashcode of s2 942731712

Here s1 and s2 has a different hash code so we can say we have two different
objects in memory with a different address space.
[ Dat
]
e

240
Q. what is string constant pool?
A Java String Pool is a place in heap memory where all the strings defined in the
program are stored. A separate place in a stack is there where the variable storing the
string is stored. Whenever we create a new string object, JVM checks for the
presence of the object in the String pool, If String is available in the pool, the same
object reference is shared with the variable, else a new object is created.

METHODS OF STRING CLASS


int length(): this method is used for calculate length of string char
charAt(int index): this method is used for return character using a some
specified string index. package org.techhub;
public class TestConversionApp {
public static void main(String[] args) {
String s="good"; int
len=s.length(); for(int i=0; i<len;i++) {
char ch=s.charAt(i);
System.out.printf("ch[%d] ----->%c\n", i, ch);
}
}
}
Example
WAP to input string and separate digit from a string calculate its sum
Example: abc123mno456
Output: 1+2+3+4+5+6 = 21
package org.techhub; import
java.util.*;
public class TestConversionApp {
public static void main(String[] args) {
Scanner xyz = new Scanner(System.in);
System.out.println("Enter string value"); String s=xyz.nextLine();

[ Dat
]
e
241
int sum=0;
for(int i=0; i<s.length();i++) {
char ch=s.charAt(i);
if(ch>=48&&ch<=57) {
sum = sum +((int)ch-48);
}
}
System.out.println("Sum of all digit is "+sum);
}
}
String concat(String): this method is used for combine two strings and generate
new third string from it.

if we think about above code, we have two string s=”abc” and s1=” mno” and we
have statement s2=s1.concat(s) here s1 and s both combine string and generate
new third string from it i.e., s2 means here s and s1 not change its value so we can
say string is immutable object of java.
String trim (): trim () method is used for remove the white spaces at beginning
and ending of string. package org.techhub; import java.util.*;
public class TestConversionApp {
public static void main(String[] args) {
String s=" abc";
// String s1=s.trim();
//System.out.println(s1);
System.out.println(s.trim());
]
} Dat
[

281
} int indexOf(String): this is used for search string data and if data found return
its index otherwise return -1. package org.techhub; import java.util.*;
public class TestConversionApp { public
static void main(String[] args) {
String s ="good morning india";
int index=s.indexOf("morning");
if(index!=-1) {
System.out.println("Data found");
}
else {
System.out.println("data not found");
}
}
}
String substring(int startindex,endindex): this method is used for extract data
between two specified index.
package org.techhub; import
java.util.*;
public class TestConversionApp { public
static void main(String[] args) {
String s ="good morning india";
String newData=s.substring(5,12);
System.out.println(newData);
}
}
String [] split(String): this method is used for split the large string in to substrings
using a some specified letters or characters.

]
Dat
[

282
boolean endsWith(String): this method is used for search string using a some
specified data and compare only last character of string or ending data of string
if data found return true otherwise return false.
Example: we want to find the words which ends with ing from good morning
india I am Indian string package org.techhub; import java.util.*;
public class TestConversionApp { public
static void main(String[] args) {
String s="good morning india i am indian good evening
india"; String words[]=s.split(" "); for(int i=0;
i<words.length;i++) { if(words[i].endsWith("ing")) {
System.out.println(words[i]);
}
}
}
}

String toUppercase(): this method is used for convert lower case string in to
upper case string. package org.techhub; public class ToUpperCaseApp {
public static void main(String[] args) {
String s="good";
String s1=s.toUpperCase();
System.out.println(s1);
}
}
]
Dat
[

283
Example: WAP to convert lower case string to upper case without using
toUpperCase() method

int compareTo(String): this method is used for compare two strings with each
other by using lexicol/alphabet order and if two strings are equal return 0 otherwise
return first mismatch ascii code difference.

package org.techhub; public


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

String s="abc";
String s1="abec";
int result = s.compareTo(s1);
if(result==0) {
System.out.println("String are equal");
}
else {
System.out.println("Strings are not equals "+result);
}
}
}

boolean equals(String): this method compare two strings by using its hashcode if
two string hashcode is same then return true otherwise return false.
package org.techhub; public
class ToUpperCaseApp {
public static void main(String[] args) {
String s="abc";

]
Dat
[

284
String s1="abce";

[ Dat
]
e
boolean b=s.equals(s1);
if(b) {
System.out.println("Strings are
equal");
System.out.println("Hashcode
of s "+s.hashCode());
System.out.println("Hashcode of s
"+s1.hashCode());
}
else {
System.out.println("Hashcode
of s "+s.hashCode());
System.out.println("Hashcode
of s "+s1.hashCode());
System.out.println("Strings are not
equal");
}
}
}
int compareToIgnoreCase(String): this method is used for compare two strings
with each other
Without checking its case sensitiveness.
package org.techhub; public class
ToUpperCaseApp {
public static void main(String[] args) {
String s="abc";
String s1="Abc";
int result =s.compareToIgnoreCase(s1);
if(result==0) {
System.out.println("Strings are
equal");
}
else {
System.out.println("Strings are not
equal");
}
}
}
STRINGBUFFER AND STRINGBUILDER CLASSES
Q. what is StringBuffer and StringBuilder classes?
StringBuffer and StringBuilder are mutable classes of java

246

Mutable means once we initialize value can modify later called as mutable classes.

Note: we cannot use StringBuffer or StringBuilder by using initialization technique


we can create its object by using a new keyword.
Because StringBuffer and StringBuilder objects only created in heap section of ram not
in string constant pool.

STRINGBUFFER AND STRINGBUILDER CONTAIN SOME ADDITIONAL


METHODS AS COMPARE WITH STRING.
1)void append(int),void append(float),void append(double) ,void
append(long),void append(object): this method is overloaded method of
StringBuffer or StringBuilder class we can append any type of data at the end of
string means it is overloaded with all types of data. void insert(int index, int
data),void insert(int index, boolean data),void insert(int index, float data)etc.
this method can insert any type of data in string using a its specified index and
move other data on next index automatically it is also overloaded method with
all data type means we can insert any type of data in it.

2)void delete(int startindex, int endindex):this method is used for delete data between
two specified index.

package org.techhub; public


class ToUpperCaseApp {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer ("Good
Morning india “);
System.out.println("Before Append "+sb);
sb.append(2023);
System.out.println("After append "+sb);
sb.insert(13, " welcome ");
System.out.println("After insert "+sb); sb.delete(5, 12);

[ Dat
]
e
System.out.println("Delete Data "+sb);

247

}
}
Q. what is diff between StringBuffer and StringBuilder?
StringBuffer is synchronized class and thread safe and StringBuilder is asynchronized
and not thread safe class.
Means methods of StringBuffer are synchronized internally and methods of
StringBuilder are not synchronized as well as StringBuffer object can use at a time
multiple threads but StringBuilder cannot use at time by multiple threads so the
StringBuffer is slower than StringBuilder
StringBuffer class present in java from JDK 1.1 version and StringBuilder class present
in Java from JDK 1.5 version of class.

2) Reference Type of Conversion


Those conversions perform between objects called as reference type of conversion.
[ Dat
]
e
248
MULTI-THREADING IN JAVA
Q. What is multi-threading?
Threads allows a program to operate more efficiently by doing multiple things at
the same time.
Threads can be used to perform complicated tasks in the background without
interrupting the main program.

TYPES OF THREADING
1.Thread
2. Runnable interface

Example:
package org.techhub; class
A extends Thread {
public void run() {
try {
for(int i=1; i<=5; i++) {
System.out.println("First
Thread "+i);
[ Dat
]
e
Thread.sleep(10000);
}
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
}
class B extends Thread {
public void run() {
try {
for(int i=1; i<=50; i++) {
System.out.println("Second
Thread "+i);
Thread.sleep(1000);
}
} catch (Exception ex) {
System.out.println("error is " + ex); 250
}

}
}
public class ThreadingApplicationTest {
public static void main(String[] args) {
A a1 = new A(); a1.start(); B b1 = new B();
b1.start();
}
} public void join(): join() method can hold thread execution whenever running
thread is not completed when we use join() method we must be handle
InterruptedException. public void stop(): this method can stop the thread
execution or terminate the thread execution. public boolean isAlive(): this
method can check thread is running or not if running return true otherwise return
false.
Example package org.techhub; class A extends Thread {
public void run() {
try {
for(int i=1; i<=5; i++) {
System.out.println("First Thread "+i+"\t"+ isAlive());
if(i==3) { stop();
}
Thread.sleep(10000);
}
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
}

class B extends Thread {


public void run() {
try {
for(int i=1; i<=50; i++) {
System.out.println("Second Thread
"+i);
Thread.sleep(1000);
}
} catch (Exception ex) {
System.out.println("error is " + ex);
}
}
}
public class ThreadingApplicationTest {
public static void main(String[] args)throws
InterruptedException {
A a1 = new A(); a1.start();
a1.join();
System.out.println("Now Status of
first thread is "+a1.isAlive());
B b1 = new B();
b1.start();
}
}

SYNCHRONIZATION AND ASYNCHRONIZATION IN THREADS


Q. what is synchronization?
Synchronization means if two or more than two threads use the single
resource/object one by one sequentially called as synchronization.

Q. what is Asynchronization?
Asynchronization means if two or more than two threads use single resource/object
simultaneously called as asynchronization. Q. what is resource?

Here resource indicate object of class in java

[ Dat
]
e
252
if we think about above diagram, we have Table class object and we share table class
object in Two and Three threads so JVM execute table object simultaneously by two
thread and by Thread threads called as asynchronization.

HOW TO PERFORM SYNCHRONIZATION


If we want to perform synchronization, we have to use synchronized keyword.

package org.techhub;
class Table{
synchronized public void showTable(int x) {
try
{
for(int i=1;i<=10;i++) {
System.out.printf("%d X %d = %d\
n", i, x, i*x);
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
[ Dat
]
e

253
class Two extends Thread

[ Dat
]
{ Table table;

e
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(2);
}
}
class Three extends
Thread{ Table table;
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(3);
}
}
public class SyncAsyncApplication {
public static void main(String[] args) {
Table t1 = new Table();
Two tw = new Two();
tw.setTable(t1);
tw.start();

Three th = new Three();


th.setTable(t1);
th.start();
}
}

wait(), notify() and notifyAll():


Q. What is the purpose of wait()methods?

254

void wait(): this method can hold the thread execution for a specified time period and
it is a member of Object class.

THERE ARE TWO TYPES OF wait()


1) Conditional wait: conditional wait means if thread re-execute
automatically after some specified time period called as conditional wait.
Syntax: void wait(int milliseconds);

2) Unconditional wait: unconditional wait means thread not re-execute


after specified time period we need to send request to thread for re-execution
purpose and for that we have notify() and notifyAll() methods. Syntax: void
wait():

Q. what is the purpose of notify() and notifyAll() methods?


The main goal of notify () and notifyAll() method is to send request to waited
thread for re-execution purpose. void notify(): This method can call only one
waited thread at time in first in first out format void notifyAll(): This method
can call all waited threads at a time in last in first out format.
Note: wait(), notify() and notifyAll() these method only execute in
synchronized block. class Table {
synchronized public void showTable(int x) {
try
{
for(int i=1; i<=10; i++) {
System.out.printf("%d X %d = %d\
n", i, x, i*x);
if(i==5) {
wait();
}
Thread.sleep(1000);
} }

[ Dat
]
e
255
catch(Exception ex) { System.out.println("Error is
"+ex);
}
}
public synchronized void recall() {
try {
notifyAll();
}
catch(Exception ex) { System.out.println("Error is
"+ex);
}
}
}
class Two extends Thread {Table table;
public void setTable(Table table) { this.table=table;
}
public void run() {
table.showTable(2);
}
}
class Three extends Thread{
Table table; public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(3);
}
}
public class SyncAsyncApplication {
public static void main(String[] args) { Table t1 = new Table();

Two tw = new Two();


tw.setTable(t1);
tw.start();

Three th = new Three();


th.setTable(t1);
th.start();
do {
java.util.Scanner xyz = new
java.util.Scanner(System.in);
String msg=xyz.nextLine();
if(msg.equals("restart")) {
t1.recall();
}
}while(true);//infinite loop
}
}
Q. what is diff between wait () and sleep ()?
1. wait() method is a member of java.lang.Object and sleep() method is a static
member of Thread class.
2. wait() method can work with conditional as well as unconditional wait but
sleep() always work with conditional wait.
3. wait() method must be use in synchronized block and sleep() method can
work in synchronized as well as asynchronized block.

Thread priority
Thread priority decide the execution priority thread when we call start() method.

THERE ARE THREE TYPES OF THREAD PRIORITY.


1. Min priority: min priority is lower priority of thread means when we set
[ Dat
]
e
min priority on thread then thread start it execute at last
2. Norm priority: norm priority is a default priority of thread
3. Max priority: max priority means thread has higher execution priority
means when we set max priority on thread then thread start its execution very first.

257

IF WE THINK ABOUT PRIORITY OF THREAD THEN JAVA PROVIDE THE


SOME FIX CONSTANT VALUES TO US OF TYPE INTEGER

If we want to apply priority on thread we have method name as void setPriority(int


priority)
this method can set priority on thread

Syntax: void setPriority(int priority);

if we want to get thread priority we have method name as int getPriority() int
getPriority(): this method is used for get thread priority which we apply on thread.
Example: Thread priority values package
org.techhub;
public class TestThreadPriorityApp { public
static void main(String[] args) { int
maxPriority=Thread.MAX_PRIORITY;
System.out.printf("\nMax priority is %d\n", maxPriority); int
normPriority=…...Thread.NORM_PRIORITY;
System.out.println("\nNormal priority “+normPriority); int

[ Dat
]
minPriority=Thread.MIN_PRIORITY;

e
258
System.out.println("\nMinimum priority "+minPriority);
}
}
Note: We cannot run java program without thread.
Because every java program has one default thread called as main thread and
which is created by JVM internally when we run program and normal this thread
presents in class where main method is defined.
package org.techhub; public class TestThreadPriorityApp {
public static void main(String[] args) throws InterruptedException
{
Thread t=Thread.currentThread();
String name=t.getName();
System.out.println("Thread name is "+name);
int priorityValue=t.getPriority();
System.out.println("\nNormal priority "+priorityValue);
}
}
Example: Thread priority class A extends Thread
{
public void run()
{
try {
for (int i = 1; i <= 5; i++) {
System.out.println("First Thread " + i);
}
} catch (Exception ex) {
System.out.println("error is " + ex);
}
}
} class B extends Thread { public void run() {

try {
for (int i = 1; i <= 5; i++) {
System.out.println("Second
Thread " + i);
}
} catch (Exception ex) {
System.out.println("error is " + ex);
}
}
}
class HelloWorld {
public static void main(String[] args) {
A a1 = new A();
a1.setPriority(Thread.MIN_PRIORITY);
a1.start(); B b1 = new B();
b1.setPriority(Thread.MAX_PRIORITY);
b1.start();
}
}

HOW TO CREATE THREAD BY USING A RUNNABLE INTERFACE

Q. why we need to create threads using a Runnable interface?


If we use Thread class for thread implementation purpose then there is possibility
of multiple inheritances

Example
abstract class A {
[ Dat
]
e
}
class B extends A, Thread
{
}
If we think about above code we have class B with two parent classes name as A
and Thread but as per the rule of java single class cannot have more than one
260

parent classes because it situation of multiple inheritance and java not support to
implement multiple inheritance by using classes so we have one more approach to
implement multiple inheritance i.e., interface in the case of thread we have
Runnable interface so avoid this type of situation for thread implementation
purpose we have to use Runnable interface.

STEPS TO IMPLEMENT THE THREAD USING A RUNNABLE


INTERFACE
1. Add java.lang package in application
import java.lang.*;
2. Create class and implement Runnable interface in it.
class ABC implements Runnable {

[ Dat
3. override its run() method and write its logic
]
e
class ABC implements Runnable {
@Override
public void run() {
try {
for(int i=1; i<=10; i++) {
System.out.printf("I = %d\n", i);
Thread.sleep(10000);
}
} catch (Exception ex) {
System.out.println("error is " + ex);
}
}
}
4. Create object of thread class and pass Runnable implementer class
reference in its thread constructor
When we use thread using a Runnable interface, we have to use thread given
constructor.

261
Thread(Runnable): means here we have Runnable reference as parameter in thread
constructor means here we can pass object of its implementer class in thread
constructor.
package org.techhub; import
java.lang.*;
class ABC implements Runnable {
@Override
public void run() {
try {
for(int i=1; i<=10; i++) {
System.out.printf("I = %d\n", i);
Thread.sleep(10000);
}
} catch (Exception ex) {
System.out.println("error is " + ex);
}
}
}
public class ThreadUsingRunnableApp {
public static void main(String[] args) {
ABC a1 = new ABC();
Thread t1 = new Thread(a1);
}
}
5. Use thread methods to work with thread
package org.techhub; import
java.lang.*;
class ABC implements Runnable {
@Override
public void run() {
try {
for(int i=1; i<=10; i++) {
System.out.printf("I = %d\n", i);
[ Dat
]
e

Thread.sleep(1000);

262
}
} catch (Exception ex) {
System.out.println("error is " + ex);
}
}
}
public class ThreadUsingRunnableApp { public static void main(String[]
args) {
ABC a1 = new ABC();
Thread t1 = new Thread(a1);
t1.start();
}
}
Note: you can create thread using Runnable interface by using Anonymous inner
class technique.
Anonymous inner class is a local inner class where we can create object of class
or interface as well as can define its body and override its method. Example:
Runnable r = new Runnable(){
public void run(){
}
};
Example:
package org.techhub; import java.lang.*; public class
ThreadUsingRunnableApp { public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() { for(int i=1;
i<=5;i++) { System.out.println(i);
}
}
};

]
Date
[

263
Thread t = new Thread(r);
t.start();
}
}

Q. What is Daemon thread?


Daemon thread is a service provider thread that provides services to the user thread.
Means daemon thread life is dependent on user threads when all users thread gets
terminated then JVM automatically delete the daemon threads.
Example:
Daemon threads: gc, finalizer etc.
GC MEANS GARBAGE COLLECTION

USER CAN CREATE OWN THREAD AS DAEMON THREAD AND FOR


THAT WE HAVE METHOD NAME AS
void setDaemon(boolean): this method is used for decide user thread can work as
daemon thread or not if we set true value then user thread can work as daemon
thread and if we set false then user thread can work as normal thread. boolean
isDaemon(): this method can cross verify user thread is daemon thread or not if
user thread is daemon thread then this method return true otherwise return false.
package org.techhub;
import java.lang.*; class
Test extends Thread {
public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.printf("I=%d\n", i);
Thread.sleep(1000);
}
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
[ Dat
]
e

264
}
public class ThreadUsingRunnableApp {
public static void main(String[] args) {
Test t=new Test();
t.setDaemon(true);
t.start();
}
}
Thread Life cycle
Thread life cycle means to decide how thread will create in memory and how they
will destroy means we can thread life cycle is process where we decide the complete
thread execution from creation to destruction

THE FOLLOWING DIAGRAM SHOWS THE THREAD LIFE CYCLE.

THREAD LIFE CYCLE CONTAIN FOLLOWING STATE


1. New State
2. Runnable State
3. Blocked State
[ Dat
]
e
4. Waiting State

265
5. Timed waiting State
6. Terminated State

New State: New State means when thread is created. it is the new state. the thread
has not yet started
to run when thread is in this state. means when we create object of thread class but
not call start method
called as new state

Example:
class A extends Thread
{
}
A a1 = new A (); //new state

Runnable State: A thread that is ready to run is moved to Runnable state. In this
state, thread might actually be running or it might be read to run any instant of time
and it is responsibility of thread scheduler to thread time to run.
class A extends Thread
{
}
A a1 = new A() ;//new state
A a2=new A();
a1.start(); a2.start();
here we have two threads one is a1 and one is a2 so when we call a1.start() method
then a1 is running and a2 is ready for running means a2 can run instant by thread
scheduler

Blocked or waiting state: When thread is temporary inactive then it is one of the
following states.
1. Blocked
2. Waiting
]
Dat
[

308
Timed Waiting: A thread lies in timed waiting state when it calls a method a time
out parameter. means when we call wait() method in conditional format or sleep()
method then it is called as timed waiting

Terminated stage: when we want to stop execution of thread force fully or it may
be some problem at run time called as terminated state means when user clock the
stop() then we can terminate thread.
REMAINING THREADING IN JDK 1.8:
1. Executer services
2. Thread pool constant
3. Concurrency API

]
Dat
[

309
IOSTREAM OR FILE HANDLING

]
Dat
[

310
Q. What is IOStreams?
IOStreams stands input and output streams. If we send data from one place to another
place called as IOStreams.
Means if we send data from one memory to another memory or one machine to another
machine called as iostream.
If we want to work with iostream using java we have package name as java.io
This package provides some classes and some interfaces to us those help us to send
data from one memory to another memory or one machine to another machine. if
we want to send data at any where we required to know the destination path and if
we want to work with path in java, we have File class.

File class: File class help us to create folder, create file, delete folder, delete file, get
drive list, get list of files and folder from specified drive as well as get total space of
driver, free space of drive etc.

Q. How to get drive list from computer using a File class?


If we want to get drive list using a File class we have listRoots() method of File class
and this method return reference of File class array.

Syntax: File ref[]=File.listRoots() : this method return array of File class and return
list of drive names.
long getTotalSpace(): this method return space of drive using bits or means
return size of drive in bits. import java.io.*;
public class GetDriveListApp {
public static void main(String x[]) {
File f[]= File.listRoots();
for(int i=0; i<f.length;i++) {
long totalSpace=(f[i].getTotalSpace()/1073741824);
long freeSpace=(f[i].getFreeSpace()/1073741824);
System.out.println(f[i]+"\t"+totalSpace +"
GB\t"+freeSpace+" GB");
}
}}

[ Dat
]
e
269

[ Dat
]
Q. How to create folder using a File class?

e
If we want to create folder using a File class we have boolean mkdir() method of
File class this method return true if folder created successfully otherwise return
false.
Syntax: boolean mkdir()

boolean exists(): this method is used for check folder or file is present or not if
present return true otherwise return false.

Example: we want to create folder name as filehandling in feb2023 on D drive.


import java.io.*; public class
GetDriveListApp { public static
void main(String x[]) {
File f = new File("D:\\feb2023\\filehandling123");
boolean b1=f.exists();
if(b1) {
System.out.println("folder is present");
}
else {
boolean b=f.mkdir();
if(b) {
System.out.println("folder created successfully..........");
}
else {
System.out.println("some problem is
there..........");
}
}
}}
Q. How to get all files and folder from a specified drive?
if we want to get all files and folder from a specified driver we have listFiles()
method.

270
Syntax: File [] listFiles();
File [] listFiles(): this method help us to fetch all files and folder from specified
path.

import java.io.*; public class


GetDriveListApp { public static
void main(String x[]) {
File f = new File("D:\\feb2023");
File list[] =f.listFiles();
for(int i=0; i<list.length;i++)
{ System.out.println(list[i]);
}
}
} boolean isDirectory(): this method help us to check path is folder or file
if path is folder return true otherwise return false.

Example: we want to fetch only sub folder of feb23 import


java.io.*;
public class GetDriveListApp
{ public static void main(String x[])
{
File f = new File("D:\\feb2023");
File list[] =f.listFiles();
for(int i=0; i<list.length;i++) {
if(list[i].isDirectory()) {
System.out.println(list[i]);
}
}
}
}

boolean isFile(): this method help us to fetch files from specified path if path is
file return true otherwise return false. import java.io.*;
]
Date
[

271
public class GetDriveListApp
{ public static void main(String x[])
{
File f = new File("D:\\feb2023");
File list[]=f.listFiles();
for(int i=0; i<list.length;i++)
{ if(list[i].isFile()) {
System.out.println(list[i]);
}
}
}
}
Q. How to create file using a File class?
If we want to create file using a File class, we have method name as. boolean
createNewFile(): this method can create new file and return true if file created
successfully otherwise return false.

import java.io.*;
public class GetDriveListApp { public static void
main(String x[])throws IOException { File f = new
File("D:\\feb2023\\filehandling\\resume.doc"); boolean
b=f.createNewFile();
if(b) {
System.out.println("Success............");
}
else {
System.out.println("Fail.............");
}
}
}

Q. How to work with file using JAVA?


IF WE WANT TO WORK WITH FILE USING JAVA, WE HAVE TWO
WAYS
[ Dat
]
e
272

1. Using Text Format: if we want to work with a text format, we have two
types of classes i.e., Writer and Reader class means those classes ends with Writer
or Reader then they work with text format and when we want to work with text file,
word file etc. then we can use text format.
2. Using Byte format: if we want to work with audio, video etc. then we have
byte format and for that we have stream classes means those classes ends with
stream they work with a byte format.

Q. Writer classes in java?


Writer classes help us to write data in file using text format if we want to work with
a Writer class have following class hierarchy.

If we think about above diagram, we have Writer class and it is abstract class from
java.io package and it contain some abstract method those help us to write data in file.

void write(char): this method helps us write single character data at time in file.
void write(String data): this method can write string data in file. void
write(char[]): this method can write character array data in file. void
write(char[],int offset, int length): This method can write character array data
in file using a specified length.

char[]: This parameter is actual parameter where data is present.


int offset: Means index from data want to write file. int
length: Decide how much data want to write file.
[ Dat

void write(String data, int offset, int length): This method can write character
]
e
array data in file using a specified length.

273

String this parameter is actual parameter where data is present.


int offset: means index from data want to write file. int
length: decide how much data want to write file.

FileWriter class
FileWriter class is used for write data in file using a string format.
CONSTRUCTOR OF FILEWRITER
FileWriter (String path): this constructor helps us to accept file path using a string
format.
FileWriter (File path): this constructor is used for accept file path using file class
reference.
FileWriter(String path, boolean mode):
String path: this parameter accepts the file path using a string format. boolean
mode: This parameter decide which kind of mode file use means there two modes
in active when we write data in file. write: write mode means if file is not present
then create new file and add data in it and if file is present then override previous
data of file and add new data in file.
append: append mode means if file is not present then create new file and add
data in it and if file is present then add new data at the end of file. FileWriter (File
path, boolean mode)
String path: this parameter accepts the file path using a string format.
boolean mode: this parameter decide which kind of mode file use means there two
modes in active when we write data in file.
write: write mode means if file is not present then create new file and add data in it
and if file is present then override previous data of file and add new data in file.
append: append mode means if file is not present then create new file and add data in
it and if file is present then add new data at the end of file.

Now we want to create file using a FileWriter class and write data in it.
package org.techhub; import java.io.*;

[ Dat
]
e
274

import java.util.Scanner;

[ Dat
]
public class FileWritingApplication {

e
public static void main(String[] args)
throws IOException {
try {
Scanner xyz = new
Scanner(System.in);
FileWriter fw = new
FileWriter("D:\\feb2023\\filehandling\\abc.txt",true);
String data;
System.out.println("Enter data in file\
n");
data = xyz.nextLine();
fw.write(data);
fw.close();

System.out.println("SAVE..................");

} catch (Exception ex) {


System.out.println("error is " + ex);
}
}
} if we think about FileWriter class then FileWriter can add data on same
line in file not on new line if we want to add data on new line in file, we
have BufferedWriter class.

CONSTRUCTOR OF BufferedWriter
BufferedWriter(Writer): if we think about BufferedWriter class then its
constructor contain Writer class reference means we can pass reference of any
child class of Writer class in BufferedWriter class constructor. means here we
can pass reference of FileWriter class because it is child of Writer

BufferedWriter class contain newLine() method which is used for add data on
new line in file

newLine(): this method write or create new line in file package


org.techhub;

275

[ Dat
]
import java.io.*;

e
import java.util.Scanner;

public class FileWritingApplication {


public static void main(String[] args)
throws IOException {
try {
Scanner xyz = new
Scanner(System.in);
FileWriter fw = new
FileWriter("D:\\feb2023\\filehandling\\abc123.txt", true);
BufferedWriter bw = new
BufferedWriter(fw);
String data;
System.out.println("Enter data in file\
n");
data = xyz.nextLine();
bw.write(data);
bw.newLine();
bw.close();
fw.close();

System.out.println("SAVE..................");

} catch (Exception ex) {


System.out.println("error is " + ex);
}
}
}
Reader
Reader classes help us to read data from file using character format of string
format

276
if we think about above diagram, we have Reader class it is abstract class from
java.io package and it contain some abstract methods those help us to read data from
file.

METHODS OF Reader CLASS


int read(): this method is used for read single single character data from file and
return -1 when file is end or when file has no data. int read(char[]): this method
is used for read complete data from file and store in character array and return its
length when file has no data return -1

int read(char[],int offset, int length): this method help us to read specified length of
data from file
THERE ARE THREE PARAMETER IN read() METHOD
char []: this parameter contains complete data from file int offset: this
parameter indicates from data want to read int length: this parameter is
used for read specified length of data from file.

FileReader: FileReader class is used for read data from file character by character.

CONSTRUCTOR OF FileReader CLASS


FileReader(String path): this method helps us to read file path using a string
format.
[ Dat
]
e

FileReader(File path): this method help us to read file path using file class
reference.

277
If we think about FileReader class then we can read data single character at time
but if your file is larger than it will take more time for file reading purpose.
So better way you can use BufferedReader class for file reading purpose. if we
use BufferedReader class then we have readLine() method and this method help
us to read line by line data from file and return null when file is end or when file
has no data.

String readLine(): this method can read line by line data and return null value if
file has no data.

CONSTRUCTOR OF BufferedReader CLASS


BufferedReader(Reader): if we think about BufferedReader class we have
Reader as parameter means we can pass reference of any child of Reader class in
BufferedReader constructor.

package org.techhub; import


[ Dat
]
e

java.io.*;
public class FileReadingApplication {
public static void main(String[] args) throws IOException,
InterruptedException {
FileReader fr = new FileReader("D:\\feb2023\\filehandling\\abc123.txt");
BufferedReader br=new BufferedReader(fr);
String data;
while ((data = br.readLine()) != null) {
278

System.out.println(data);
Thread.sleep(1000);
}
}
}
STREAM CLASSES
Q. What is Stream classes?
Stream classes works with byte format

THERE ARE TWO TYPES OF STREAMS CLASSES


OutputStream: OutputStream help us to write data in file using byte format.
InputStream: InputStream help us to read data from file using a byte format.
Now we want to discuss about OutputStream classes

If we think about above diagram, we have OutputStream class and it is abstract


class and it contain some abstract method those help us to write data in file.

void write(byte): write single byte data in file at time. void write(byte[]):
write more than one byte array data in file. void write(byte[],int offset, int
length): this method help us to write specified length of data in file using byte
array format.

NOW WE WANT TO DISCUSS ABOUT FileOutputStream CLASS


FileOutputStream(String path): this method can accept file path using a string
format.
[ Dat
]
e
FileOutputStream(File path): this method can accept file path using file class
reference.
FileOutputStream(String path, boolean mode):
279

String path: this parameter is used for accept file path using a string format
boolean mode: these parameters indicate file can work with append mode or
write mode if we pass true then file can work with append mode otherwise not
FileOutputStream(File path, boolean mode):
File path: this parameter is used for accept file path using a file class reference
boolean mode: this parameter indicate file can work with append mode or not if
pass true then file can work with append mode otherwise not.

package org.techhub; import java.io.*; import java.util.*;


public class StreamApplication {
public static void main(String[] args) throws IOException {
FileOutputStream fout = new FileOutputStream("D:\\feb2023\\filehandling\\
s.txt");
Scanner xyz = new Scanner(System.in);
System.out.println("Enter data"); String data=xyz.nextLine();
byte b[]=data.getBytes(); fout.write(b); fout.close();
System.out.println("Success..................");
}
}
InputStream class: if we work with InputStream class then we can read data
from file using a byte format.
We have following class hierarchy for InputStream class.
If we think about InputStream class it is a abstract class and it contain some
abstract method which is used for read data from file.

]
Date
METHODS OF InputStream CLASS
int read(): this method is used for read single byte data at time int read(byte[]):
this method can read complete data from file and store in byte array format and
return its length if file has no data then return -1. int read(byte[],int offset, Int
length): this method can read specified size of data from file.

CONSTRUCTOR OF FileInputStream CLASS

FileInputStream (String path): this constructor helps us to accept file path using
a string format.
FileInputStream (File path): this constructor helps us to accept file path using a
file class reference.

package org.techhub; import


java.io.*;
public class ReadFileData {
public static void main(String[]
args)throws IOException {
FileInputStream finf = new FileInputStream("D:\\feb2023\\filehandling\\s.txt");
int data;
while((data=finf.read())!=-1) {
char ch=(char)data;
System.out.print(ch);
}
}
}
Example: we want to perform copy and paste operation on Image
package org.techhub; import java.io.*;
public class ImageCopyPasteApp { public static void
main(String[] args) throws Exception {
FileInputStream fr = new FileInputStream("D:\\dec\\er.jpg");
FileOutputStream fw = new FileOutputStream("D:\\feb2023\\er.jpg");
[ Dat

int data;
]
e
while ((data = fr.read()) != -1) {

281

fw.write(data);
}
fw.close();
fr.close();
System.out.println("Success....................");
}
}
Serialization and Deserialization
Q. What is Serialization?
Serialization is a process where we store object data in file called as Serialization.
Means when we want to store object data in file then object must be serialized.
When we serialize object then JVM encrypt object content internally and store
in file.
STEPS TO WORK WITH SERIALIZATION

1. Add java.io package in application import java.io.*;


2. Create POJO class and implements Serializable interface.
class Employee implements Serializable {
private int id;
private String name;
private int sal;
//setter and getter methods
}
3. Create Object of ObjectOutputStream class
ObjectOutputStream class is used for write object data in file
Syntax: ObjectOutputStream ref= new ObjectOutputStream(OutputStream); Here
ObjectOutputStream has constructor and it contain
reference of OutputStream class means we can pass reference of any child of
OutputStream class. class Employee implements Serializable {
private int id; private String name;
[ Dat
]
e
282

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} public int getSal()
{
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
}
4. Call writeObject () method of ObjectOutputStream class
void writeObject (Object): this method helps us to write object data in file and
encrypt file internally. package org.techhub; import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Employee implements Serializable {
private int id;
private String name;
[ Dat
]
e
public int getId() {
return id;
}
public void setId(int id) {

283

this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
}
public class SerializationApplication {
public static void main(String[] args)
throws Exception {
FileOutputStream fout = new
FileOutputStream("D:\\feb2023\\filehandling\\emp.txt");
ObjectOutputStream out = new
ObjectOutputStream(fout);
Employee emp1 = new Employee();
emp1.setId(1);
[ Dat

emp1.setName("ABC");
]
e
emp1.setSal(10000);
out.writeObject(emp1);
out.close();
System.out.println("Success.................");

}
}
DeSerialization
Q. What is DeSerialization?
Deserialization means when we read object data from file called as deserialization.

284

If we want to read object data from file, we have ObjectInputStream class.

CONSTRUCTOR OF ObjectInputStream CLASS


ObjectInputStream(InputStream): ObjectInputStream class constructor accept
InputStream class reference as parameter means here we can reference of any
InputStream class child here.
Object readObject(): this method can read object data from file and if object not found
return null.

EXAMPLE OF Deserialization
package org.techhub; import
java.io.*;
public class DeserializationApplication {
public static void main(String[] args) throws
IOException,
ClassNotFoundException{
FileInputStream finf = new
FileInputStream("D:\\feb2023\\filehandling\\emp.txt");
ObjectInputStream oinf = new
ObjectInputStream(finf);
Object obj=oinf.readObject();
if(obj!=null) {
Employee emp=(Employee)obj;
System.out.println(emp.getId()+"\t"+emp.getName()+"\t"+emp.getSal());
}
else {
System.out.println("Object not found");
}
}
}

[ Dat
]
e
285
MAP INTERFACE

]
Date
[

286
Q. What is Map interface?
Map interface is used for store data in the form of key and value pair. Key is unique
identity of Map and value is actual data present in Map Means key cannot be
duplicate and value may be duplicate. using key, we can store data in map as well
as retrieve data from map and delete data from map etc. in short, we can say Map is
a combination of set and list collection set work as key and list work as value. Map
helps us to maintain the duplication of data with some unique identity.

If we want to work with map, we have following interface and class hierarchy

If we think about above hierarchy we have top most interface name as


java.util.Map and Map interface provide some inbuilt methods to us which help us
to perform operation on map interface.

METHODS OF MAP INTERFACE


public abstract int size(): this method is used for return size of map or return number
of element present in map.

public abstract boolean isEmpty(): this method is used for check map is empty or
not if empty return true otherwise return false.

public abstract V put(K, V): this method can store data in map in the form of key and
value pair.
[ Dat
]
e

287
public abstract V get(java.lang.Object): this method can fetch data from map using
its key and if key not found return null.
You can use this method for two purposes.

1) For data retrieval purpose

2) For data searching purpose.

public abstract boolean containsKey(java.lang.Object): this method help us to check


data present in map using its key if key found return true if key not return false.
[ Dat
]
e

288
]
Date
[

289

public abstract boolean containsValue(java.lang.Object): this method help us to


check data present in map or not using its value if found return true otherwise
return false.

public abstract V remove(java.lang.Object): this method can remove data from


map using its key and return value which we removed if key not found return null.
public abstract void putAll(java.util.Map<? extends K, ? extends V>): this is
used for copy the data from another map.
public abstract void clear(): this method help us remove all data from maps.

public abstract java.util.Set<K> keySet(): this method return all keys from map
and return reference of Set Collection normally this method help us to fetch all
data from map using its key.

public abstract java.util.Collection<V> values(): this method return only values from
map collection

public
abstract java.util.Set<java.util.Map$Entry<K, V>> entrySet(): this method
specially design fetch all keys and values from map and return reference of
Map.Entry is a interface which return key and value to us

METHODS OF Map.Entry INTERFACE


public abstract K getKey(); public abstract V getValue();
[ Dat
]
e

290
public abstract V setValue(V);

THERE ARE THREE TYPES OF MAP INTERFACE


HashMap: HashMap is used for store data in key and value pair but generate key
sequence randomly
LinkedHashMap: LinkedHashMap is used for store data in the form of key and value
pair and generate key sequence as per user sequence.
TreeMap: TreeMap can store data in key and value pair and arrange all keys in
ascending order.

HashMap and its constructor


HashMap(): This constructor creates HashMap () with a default capacity i.e., 16 and
with default load factor which 75%.
HashMap(int initialCapacity, float loadFactory): Using this constructor user can set
initial capacity as per his choice as well as set load factor as per his choice.
HashMap(Map): This constructor is used for copy the data from another map and save
in HashMap object.

Example: We want to create program to store data in HashMap and display it.
package org.techhub;
import java.util.*; public
class HashMapApp {
public static void main(String[] args) {
[ Dat
]

HashMap<Integer, String> map =


e
new HashMap<Integer, String>();

291

map.put(1, "ABC");
map.put(2, "MNO");
map.put(3, "STV");
map.put(44, "XYZ");
map.put(98, "SSSS");
map.put(76, "TTTTT");
Set<Map.Entry<Integer, String>> m = map.entrySet();
for (Map.Entry<Integer, String> d : m) {
System.out.println(d.getKey() + "\t" +
d.getValue());
}
}
}

LinkedHashMap: LinkedHashMap
package org.techhub;
import java.util.*; public
class HashMapApp {
public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(1, "ABC"); map.put(2, "MNO");
map.put(3, "STV"); map.put(44, "XYZ");
map.put(98, "SSSS"); map.put(76, "TTTTT");
Set<Map.Entry<Integer, String>> m = map.entrySet();
for (Map.Entry<Integer, String> d : m) {
System.out.println(d.getKey() + "\t" +
d.getValue());
}
}
}

[ Dat
]
e
292

TreeMap: TreeMap can arrange keys in ascending order.


package org.techhub;
import java.util.*; public
class HashMapApp {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "ABC"); map.put(2, "MNO");
map.put(3, "STV"); map.put(44, "XYZ");
map.put(98, "SSSS"); map.put(76, "TTTTT");
Set<Map.Entry<Integer, String>> m = map.entrySet();
for (Map.Entry<Integer, String> d : m) {
System.out.println(d.getKey() + "\t" + d.getValue());
}
}
}
Example: WAP to create array of integer of size 10 and find the occurrence of
every element by using a LinkedHashMap.
[ Dat
]
e
293

package org.techhub; java.util.*;

[ Dat
]
e
import HashMapApp {
public class static void main(String[] args) {
public int a[] = new int[5];
Scanner xyz = new Scanner(System.in);
System.out.println("Enter values in array");
for(int i=0; i<a.length;i++) {
a[i]=xyz.nextInt();
}
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<Integer,

Integer>(); for(int i=0;i<a.length;i++) {


Integer count=map.get(a[i]);
if(count==null) {
count = new Integer(0);
}
++count;
map.put(a[i],count);
}
Set<Map.Entry<Integer, Integer>> s=map.entrySet();
for(Map.Entry<Integer, Integer> d:s) {
System.out.println(d.getKey()+"\
t"+d.getValue());
}
}
}

Example: WAP to input string from keyboard and count the repetitive words
good morning india good afternoon india.
package org.techhub; import
java.util.*;
public class FindDuplicateWordsApp {

294

public static void main(String[] args) {

[ Dat
]
e
LinkedHashMap<String, Integer> map = new
Integer>(); LinkedHashMap<String,

Scanner xyz = new Scanner(System.in);


System.out.println("Enter string value\n");
String msg=xyz.nextLine();
String words[]=msg.split("
"); for(int i=0;
i<words.length;i++) {
Integer count=map.get(words[i]);
if(count==null) {
count = new Integer(0);
}
++count;
map.put(words[i], count);
}
System.out.println("Show the word counts");
Set<Map.Entry<String, Integer>>
s=map.entrySet(); for(Map.Entry<String, Integer>
} d:s) { if(d.getValue()>1)
}
System.out.println(d.getKey()+"\
t"+d.getValue());
How to store}

user defined objects in Map collection


Sometime if we want to store different type of data with single key then we can
use Map with POJO class.

295
}
package org.techhub;
private int sal; import java.util.*;
public class Employee{
Employee(String name,int sal) {private String
name; public String getName() { this.sal=sal;
this.name=name;
}

} MapWithUserObjectApp {

[ Dat
]
e
public class static void main(String[] args) {
public LinkedHashMap<Integer, Employee> map = new
Integer, Employee>();
LinkedHashMap<Employee emp1 = new Employee("Ram",10000);
Employee emp2 = new
Employee("Shyam",20000); Employee emp3 =
new Employee("Ganesh",30000); map.put(1,
emp1); map.put(2, emp2); map.put(3, emp3);
Set<Map.Entry<Integer, Employee>> s=map.entrySet();
for(Map.Entry<Integer, Employee> e:s) {
Integer empId=e.getKey(); ]
Employee emp= e.getValue(); Date
[
System.out.println(empId+"\t"+emp.getName()+"\
t"+emp.getSal());
} 296

}
}

Example
package org.techhub; import
java.util.*;
public class MapWithinMap
{
public static void main(String[] args) {
LinkedHashMap<String, LinkedHashMap<Integer, String>> map;
map= new LinkedHashMap<String, LinkedHashMap<Integer,
String>>();
LinkedHashMap<Integer, String> cse = new LinkedHashMap<Integer,
String>();
cse.put(1, "Ram");

29
7
cse.put(2, "Shyam");
cse.put(3, "Ganesh");
LinkedHashMap<Integer, String> it = new
LinkedHashMap<Integer,String>();
it.put(1,"Rajesh");
it.put(2, "Sandeep");
it.put(3, "Mangesh");
map.put("CSE”, cse);
map.put("IT", it);
Set<Map.Entry<String, LinkedHashMap<Integer, String>>>
data=map.entrySet();
for(Map.Entry<String,
LinkedHashMap<Integer,String>>d:data) { String
deptName=d.getKey();
LinkedHashMap<Integer, String>
value=d.getValue();
System.out.println("Department Name "+deptName);
Set<Map.Entry<Integer, String>> imap=value.entrySet();
for(Map.Entry<Integer, String> in:imap) {
System.out.println(in.getKey()
+"----------->"+in.getValue());
}
}
}
}

Map using ArrayList


package org.techhub; import
java.util.*; public class
MapWithCollection {
public static void main(String[] args) {
LinkedHashMap<String, ArrayList<String>> map = new
LinkedHashMap<String, ArrayList<String>>();
[ Dat
]
e
ArrayList <String>alInd=new ArrayList<String>();
alInd.add("Rohit");
298

alInd.add("Virat");
alInd.add("Dhoni");
ArrayList<String>alAus=new ArrayList<String>();
alAus.add("steve"); alAus.add("warner");
alAus.add("Finch"); map.put("India",
alInd); map.put("Aus", alAus);
Set<Map.Entry<String, ArrayList<String>>> al =map.entrySet();
for(Map.Entry<String, ArrayList<String>> s:al) {
System.out.println("Player list from "+s.getKey());
ArrayList<String> avalue=s.getValue();
for(String s1:avalue) {
System.out.println(s1);
}
}
}
}

]
Date
[

299

You might also like