Core Java All Notes
Core Java All Notes
INDEX
SR.NO CHAPTER PAGE NO
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
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.
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.
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
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
[ Dat
]
e
System.out.println("Enter five values in array");
for (int i=0; i<a. length; i++)
10
Output: 10 100 30 40 50
11
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];
= 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
}
}
20
[ 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.
[ 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.
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)
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
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[])
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();
}
}
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
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;
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");
l.addNewBook(b,b1,b2);
l.showBook();
}
}
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();
}
}
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
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
}
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
]
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”);
}
}
[ 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.
}
}
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
}
Constructor chaining means we can call one constructor within another constructor
without creating its manual object.
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.
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.
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();
}
}
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
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
]
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.
[ 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
60
ad.setValue(10,20); int
result=ad.getAdd();
System.out.println("Addition is "+result);
61
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
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 [
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.
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.
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.
]
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
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.
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();
}
}
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.
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();
}
}
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.
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
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.
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.
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();
}
}
82
Example:
abstract int a=100;
Example:
abstract class ABC { final abstract void show(); //it will raise
compile time error. }
[ 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.
83
[ 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
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.
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.
]
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
[ Dat
]
e
87
DYNAMIC POLYMORPHISM
]
Date
[
88
How to achieve loose coupling by using dynamic polymorphism and abstract class
reference
Q. what is coupling?
1) Tight Coupling
[ Dat
]
e
89
2)Loose Coupling
]
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.
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.
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
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
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
]
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.
98
[ 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.
99
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 [
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.
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();
}
}
ABSTRACT INTERFACE
Abstract class is used for achieve partial Interface is used for achieve 100%
abstraction abstract
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
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.
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.
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.
]
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:
]
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
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.
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.
135
System.out.println("Logic3");
}
}
Q. what is throw?
throw is a clause in exception handling which is used for handle user defined
exceptions.
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);
}
}
}
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
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 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.
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.
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
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
[
149
Q. What is Vector class?
Vector is implementer class of List 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.
]
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.
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
]
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
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
]
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
]
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.
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
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);
}
}
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.
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
}
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
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
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;
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?
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)
]
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.*;
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
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);
}
}
}
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
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.
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.
]
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):
213
public int getId() {
return id;
}
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.
188
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.
[ Dat
]
e
3) override its compare() method
193
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
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.
[ 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());
}
}
}
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.
}
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>();
}
}
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
[ 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. 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.
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.
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.
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;
]
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
[
}
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.
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
Example:
long a; int
b=100;
a=b;//implicit conversion
]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
} 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.
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
]
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);
}
}
[ Dat
]
e
238
[ 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
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.
[ 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.
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.
2)void delete(int startindex, int endindex):this method is used for delete data between
two specified index.
[ 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.
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);
}
}
}
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?
[ 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.
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();
254
void wait(): this method can hold the thread execution for a specified time period and
it is a member of Object class.
[ 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();
Thread priority
Thread priority decide the execution priority thread when we call start() method.
257
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();
}
}
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.
[ 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();
}
}
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
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.
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.
270
Syntax: File [] listFiles();
File [] listFiles(): this method help us to fetch all files and folder from specified
path.
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.............");
}
}
}
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.
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.
void write(String data, int offset, int length): This method can write character
]
e
array data in file using a specified length.
273
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..................");
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
275
[ Dat
]
import java.io.*;
e
import java.util.Scanner;
System.out.println("SAVE..................");
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.
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.
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.
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
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.
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.
]
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.
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.
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
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
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
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.
288
]
Date
[
289
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
290
public abstract V setValue(V);
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
]
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
[ 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,
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
[ Dat
]
e
LinkedHashMap<String, Integer> map = new
Integer>(); LinkedHashMap<String,
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());
}
}
}
}
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