Core Java All
Core Java All
/*
what is java ?
pillar of oop
polymorphism
inheritence
abstraction
encapsulation
features
class
object
polymorphism
inheritence
dynamic binding
message passing
encapsulation and abstraction
1) Install JDK
Q.what is JDK ?
Q.what is compiler ?
what is JVM ?
JVM stands for java virtual machine
it is application which convert your byte code in to machine code
what is platform ?
4) compile application
q.what is compilation ?
C:\Program Files\Java\jdk1.8.0_291\bin>
iii) type command javac filename.java
javac OctNovFirst.java
as per our example before compilation we have only one file name as
OctNovFirst.java but after compilation we have two files
OctNovFirst.java created by programmer and it contain source code
OctNovFirst.class created by compiler after compilation and it contain byte code.
5) run application :
if we want to run program in java then we have statement name as
java filename
e.g java OctNovFirst
why ?
because we want to accept input of type integer but we have string for input
and string cannot store in integer directly so compiler will generate compile time
error to us .
as per our example we have statement a=x[0]; here a is type of integer
and x[0] is type of string so string cannot store directly in integer
so compiler will generate compile time error
converting one type of data in to another type for speicified line called as type casting.
/*
Scanner class
Q.what is package ?
or
import packagename.classname :
this statement can use single member from package
in application.
Example:
import java.util.*;
or
import java.util.Scanner;
}
}
/*System.out.println("Name is "+name);
System.out.println("Id is "+id);
System.out.println("Percentage is "+per);*/
System.out.println(name+"\t"+id+"\t"+per);
}
}
Example
Example
import java.util.*;
public class PatternApp
{
public static void main(String x[])
{ Scanner xyz = new Scanner(System.in);
int rows;
System.out.println("Enter number of rows\n");
rows=xyz.nextInt();
for(int i=1; i<=rows;i++)
{
for(int j=1; j<=rows;j++)
{
if(i<=j)
{ System.out.printf("*");
}
}
System.out.println();
}
}
}
Array in java
Q.what is array ?
1) declaration
2) memory allocation
1) datatype variablename[][];
2) datatype [][]variablename;
3) datatype []variablename[];
int a[][];
int [][]b;
int [] a[],b[][],c[][],d;
Example
import java.util.*;
public class MatrixApp
{
public static void main(String x[])
{
int a[][]=new int[3][3];
Scanner xyz = new Scanner(System.in);
System.out.println("enter the values in matrix\n");
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 the values of matrix\n");
for(int i=0; i<a.length; i++)
{
for(int j=0; j<a[i].length;j++)
{ System.out.printf("%d\t",a[i][j]);
}
System.out.printf("\n");
}
}
}
Jagged Array
1 2 3
4 5 6 7
8 9
e.g
int a[][]=new int[3][];
a[0] = new int[3];
a[1] = new int[4];
a[2] = new int[2];
import java.util.*;
public class MatrixApp
{
public static void main(String x[])
{ int a[][]=new int[3][];
a[0] = new int[3];
a[1] = new int[4];
a[2] = new int[2];
Scanner xyz = new Scanner(System.in);
System.out.println("enter the values in matrix\n");
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 the values of matrix\n");
for(int i=0; i<a.length; i++)
{
for(int j=0; j<a[i].length;j++)
{ System.out.printf("%d\t",a[i][j]);
}
System.out.printf("\n");
}
}
}
how to initialize two dimensional array in java
syntax:
datatype variablename[][]= new datatype[][]{
{1,2,3},
{4,5,6},
{7,8,9}
};
{ --> matrix
{1,2,3}, -->row and elements are columns
{4,5,6},
{7,8,9}
};
Example
new int[]{10,20,30,40,50}
Q.what is class ?
class A
{ int x; //instance variable
}
class variable: class variable means those variable declared
as static within class called as class variable
class A
{ int x; //instance variable
static int m; //classs variable or static variable
}
class A
{ int x; //instance variable
static int m; //classs variable or static variable
void show() //method
{
}
A() //constructor
{
}
{
instance initializer
}
static{
static initializer
}
}
class Employee
{ private int id;
private String name;
private long sal;
public void setData(String name,int id,long sal)
{ this.name=name;
this.id=id;
this.sal=sal;
}
public void show(){
System.out.println(name+"\t"+id+"\t"+sal);
}
}
2) reusibility
Q.what is object ?
1) donwload eclipse
https://www.eclipse.org/downloads/
https://www.eclipse.org/downloads/download.php?file=/oomph/epp/2022-12/R/eclipse-inst-
jre-win64.exe&mirror_id=492
2) create project in eclipse
package org.techhub;
class Square //class declaration
{ int no;
void setValue(int x) {
no=x;
}
void showSquare() {
System.out.printf("square is %d\n",no*no);
}
}
public class SquareApplication {
public static void main(String[] args) {
Square s1 =new Square(); //object created
s1.setValue(5);//method calling
s1.showSquare();
}
}
package org.techhub;
import java.util.*;
class Power {
int base, index, p = 1;
void setValue(int x, int y) {
base = x;
index = y;
}
int getPower() {
for (int i = 1; i <= index; i++) {
p = p * base;
}
return p;
}
}
package abc;
import java.util.*;
class Factorial
{ int no,f=1;
void setValue(int x) {
no=x;
}
int getFactorial() {
for(int i=1; i<=no;i++) {
f=f*i;
}
return f;
}
}
public class FactApp {
package abcd;
import java.util.*;
class Cube //step1 class declaratioon
{
int no;//instance variable
void setValue(int no) //step2 method defination
{
this.no=no;
}
int getCube() {
return no*no*no;
}
}
public class CubeApp {
public static void main(String[] args) {
Cube c = new Cube();//object creation step3
Scanner xyz = new Scanner(System.in);
int val;
System.out.println("Enter value");
val=xyz.nextInt();
c.setValue(val);
int result=c.getCube(); //method calling step4
System.out.printf("Cube is %d\n", result);
}
}
Q.why we have to use reference with object ?
3) provide encapsulation
08-02-2023
WAP to create class name as Value with two functions void setValue(int x)
int getSum(): this function can calcualte sum of
all natural numbers between 1 to 10
Example
package org.techhub;
import java.util.*;
class Value //it is class declaration
{ int no;
void setValue(int x) { //method defination or function defination
no=x;
}
int getSum() {
int sum=0;
for(int i=1; i<=no;i++) {
sum = sum+i;
}
return sum;
}
}
public class NaturalSumApp {
public static void main(String[] args) {
Value v = new Value();//v is reference
Scanner xyz = new Scanner(System.in);
int no;
System.out.println("Enter number");
no=xyz.nextInt();
v.setValue(no); //method calling
package org.techhub;
class Square{
int no;
void setValue(int x) {
no=x;
}
int getSquare() {
return no*no;
}
}
public class SquareApplication {
public static void main(String[] args) {
new Square().setValue(5);
int result = new Square().getSquare();
System.out.println("Square is "+result);
}
}
if we think about main method class we have statement
new Square().setValue(5);
here we created object in memory suppose we consider the address of
object is 10000 and using this object we call method name as
setValue(5) means 5 value stored no who is stored in 10000 address space
i.e in object after that we have one more statement
here we can say JVM create two different object of Square class
package org.techhub;
class Square{
int no;
void setValue(int x) {
no=x;
}
int getSquare() {
return no*no;
}
}
public class SquareApplication {
public static void main(String[] args) {
Square s = new Square();
s.setValue(5);
int result=s.getSquare();
System.out.println("square is "+result);
}
}
means here we can say we use same object two times first with setValue(0
and second time with getSquare() but it is possible with the help of
reference
so we can say if we want to use same object multiple then we have to use
reference with object.
09-02-2023
how to pass array as parameter to function
if we think about diagram we have class name as SumApp which contain main
method and we have Statement Sum s = new Sum() which indicate we created
object of Sum class
again we have statement name as int a[]=new int[5] means here we create
array of size five and store its base address in reference variable a
and here we consider the base of address is 100 in diagram
Note: sum time we cannot predict how much values need a function as
parameter of same type then we can use this approach.
Example:
package org.techhub;
import java.util.*;
class Sum{
int sum=0;
void setValue(int ...x) {
for(int i=0; i<x.length;i++) {
sum =sum+x[i];
}
System.out.println("Sum of all parameters "+sum);
}
}
public class SumApp {
public static void main(String[] args) {
Sum s = new Sum();
s.setValue(10,20,30,40,50);
}
}
Diagram of above code
i) ... must be left side of variable and right hand side of data type
means
ii) we cannot pass more than one variabble argument means more than
one
variable with ... (tripple dot) in single function
Example: void setValue(int ...x,String ...x) it is not valid declaration
compile generate compile time error to us
package org.techhub;
import java.util.*;
class Sum{
int sum=0;
void setValue(String name,int ...x) {
System.out.println("Name is "+name);
for(int i=0; i<x.length;i++) {
sum =sum+x[i];
}
System.out.println("Sum of all parameters "+sum);
}
}
public class SumApp {
public static void main(String[] args) {
Sum s = new Sum();
s.setValue("Ram",10,20,30,40,50);
}
}
13/02/2023
Static variable, instance variable and local variable in java
Static variable means variable declared with a static keyword and static variable
known as class level variable.
Instance variable means variable declared without static keyword called as
instance variable.
Example:
class A{
static int x; //static variable
int y ;// this is instance variable
}
If we want to work with a static and instance variable we have to
Know some important points related with static and instance variable
I) Static variable and instance variable has some default values provided by java
as per their data type
Means if user not provide value to static or instance variable and try to use it
then java provide default value to them
Default values of static and instance variable
Data Type Default value
int 0
Float 0.0
Long 0
short 0
Byte 0
boolean False
String Null
double 0.0
Example:
package org.techhub;
class Stat
{ int x;
static int y;
boolean b;
String str;
float t;
}
public class StatVarApp {
public static void main(String[] args) {
Stat s = new Stat();
System.out.println("X is "+s.x);
System.out.println("Y is "+s.y);
System.out.println("B is "+s.b);
System.out.println("Str is "+s.str);
System.out.println("T is "+s.t);
}
}
if we think about above code we get answer X is 0 because x is integer and it is
non static variable but its type is integer so integer has default value 0 and Y is
0 because y type is integer and it is static so default value of y is B is false
because b type is Boolean and Boolean data type use default value as false str is
null because str is type of String and string use default value as null and t is 0.0
because its type is float .
2) static variable can by using class name and instance variable can use by using
reference cannot use by class name but static can use by reference or object
also.
Means we can say static variable can use by object and class name
Example:
package org.techhub;
class Stat {
int x = 200;
static int a = 100;
}
public class StatVarApp {
public static void main(String[] args) {
System.out.println("X is " + Stat.x);
System.out.println("A is " + Stat.a);
}
}
In above we get compile time error because we have variable x in class stat and
it is non static variable means it is instance variable and we try to use it by using
class name but instance variable cannot use by class name so compiler will
generate compile time error to us.
So if we want to resolve above compile time error you have to create object of
Stat class and use its instance variable.
Following code resolve above compile time error
package org.techhub;
class Stat {
int x = 200;
static int a = 100;
}
public class StatVarApp {
public static void main(String[] args) {
4) Static variable can use in non static function but non static variable or
instance variable cannot use in static function
Example:
package org.techhub;
class A{
static int m=100;
void show() {
System.out.println("M is "+m);
}
}
public class StatVarApp {
public static void main(String[] args) {
new A().show();
}
}
above code generate output is M is 100
there is no compile time error because we can use static variable in non static
function but if we use non static variable in static function then there is compile
time error shown in following code
package org.techhub;
class A{
int m=100;
static void show() {
System.out.println("M is "+m);
}
}
public class StatVarApp {
public static void main(String[] args) {
new A().show();
}
}
in above code we have show() function it is a static function and we int x=100
but it is instance variable and we try to use the instance variable or non static
variable in static function so compiler will generate compile time error to us
5) Static variable share its common copy between multiple object of same class
and instance variable share its separate copy for every object.
Means if we create 2 objects of same class then we have two copies of instance
variable and But single copy of static variable in memory and we can use that
copy by two objects commonly shown in following diagram.
if we think about above diagram we have static variable x and instance variable
y so variable x allocate its memory before creating object a1 and a2 in memory
and get stored in permanent generation section of memory and the default is 0
if we think about main method we have statement A a1 = new A(); means here
we create object new A() and store its address 1000 in reference variable a1 and
this object contain one variable name as y so when we use the a1.x=100 means
we store value in variable x using a1 reference i.e 100 and we have statement
a1.y=200 so here a1 reference stored 200 in y who is stored in 1000 address
space means in first object again we have memory A a2= new A(); here we get
new object in memory and It contain variable y means as per our concept y
allocate two times in memory with every object so y has two different values in
two different object but x allocate only once in memory so x has single value
assign by a1 object as per our example which is 100
so when we print the output
With First object
x =100 Y=200
With second object
x=100 y 0
because we not initialize value second object so java provide default value 0
because its data type is integer.
6) Static variable life present when ever program running in memory but
instance variable life present when ever object running in memory.
if we think about above code we have two objects in memory i.e emp1 and
emp2 and we have static variable in memory name as compName
if we consider first statement Employee emp1 = new Employee() the meaning is
we have object in memory new Employee() whose address is 1000 which stored
in emp1 and it contain three variables i.e id,name and sal id=1 ,name=ABC and
sal=10000 and we have one more object in memory i.e Employee emp2 =new
Employee(); here second object address is 2000 which is stored in emp2 and it
contain different data i.e id=2 ,name=MNO and sal=20000
but both object having a different name,id and sal because they are instance
variable in our class but both object use common variable i.e compName
But as per our scenario ABC has less salary than MNO so ABC decide leave
company for increment and ABC resign for job from XYZ company so if we
want to implement this statement in our code we need to initialize emp1=null
shown in diagram
Here we initialize emp1=null means 1000 address not use by any one reference
when JVM found 1000 location or address not use by any reference so JVM
consider it is useless object so JVM delete object automatically from memory as
background processes called as garbage collection
Q. What is garbage collection?
Garbage collection is automatic memory management technique of JVM which
release object when it is not use by reference means jvm delete useless object
automatically.
Garbage collection is process to responsible the jvm becouse it will be relese the
useless data from the memory automatically it will be responsible by the jvm.
14/02/2023
Local variable
Local variable means a variable declared within function called as local variable
class A{
int x; //instance variable
static int y ; //class variable
void show(int t) //local variable
{ int m=0; //local variable
}
}
If we want to work with local variable we need to know the some important
points
i) Local variable cannot access outside of his block
Example:
package org.techhub;
class LVar{
void setValue(int x) {
}
int getSquare() {
return x*x;
}
}
public class LocalVarApp {
public static void main(String[] args) {
}
}
if we think about above code we get compile time error to us because we have
two in LVar class void setValue(int x) and int getSquare() so we cannot access
the x variable outside of his block i.e outside of setValue() function and we try
to access local variable x in getSquare() function so it is not possible so
compiler will generate compile time error to us.
So if we want to solve this problem we have to copy the local variable value in
instance variable or in static variable and we can use outside of function.
Example without error
package org.techhub;
class LVar{
int no;
void setValue(int x) {
no=x;
}
int getSquare() {
return no*no;
}
}
public class LocalVarApp {
public static void main(String[] args) {
}
}
}
}
Above code will generate compile time error to us because we try to declare
local variable x as static and it is not possible.
Q .Why local variable not declare as static?
There are two reasons
1) Memory allocation Technique: if we think about static variable then it will
allocate memory before creating object of class at the time of class file loading
in JVM.
If we think about local variable it will allocate memory when call the function
for function call we need to object if function is not static
2) Memory Storage area : local variable stored in stack section of memory
and static variable stored in permanent generation section of memory so these
are the two different areas of memory allocation so we cannot declare local
variable as static.
3) local variable life start when function call and end when function complete its
execution but static variable life start when JVM load class file and end when
program terminate or close its execution
4) Local variable cannot have default values: the meaning of this statement if
we declare local variable if we use it without initialization then compiler will
generate compile time error
Source Code
package org.techhub;
class LVar{
void show() {
int no;//no default values.
}
}
public class LocalVarApp {
public static void main(String[] args) {
}
}
Above code not generate any compile time error because we declare local
variable no in show () function under LVar class but we not use it so there is no
problem;
But if we use the local variable without initialization then compiler will
generate problem
Source code demonstrates above concept.
package org.techhub;
class LVar{
void show() {
int no;//no default values.
System.out.println("No is "+no);
}
}
public class LocalVarApp {
public static void main(String[] args) {
}
}
above code generate compile time error to us because we have local variable no
under show() function and we use in System.out.println(“No is “+no) but the
rule is if we want to use any local variable it must have some value and local
not have any value so we get error so if we want to resolve this error we must
have to provide some value to local variable
}
}
4) Local variable cannot declare as private, protected, and public
because private public and protected are the access specifier the major goal
these access specifier is provide security to class member and class but local
variable already secured because they cannot access outside of his block so if
we apply private public or protected with local variable it is meaningless so java
not allow to use private public and protected with local variable.
Note: if we try declare the local variable as private public and protected then
compiler will generate compile time error shown in following code.
package org.techhub;
class LVar{
static void show() {
private int no=0;//no default values.
System.out.println("No is "+no);
}
}
public class LocalVarApp {
public static void main(String[] args) {
}
}
Above code generate compile time error to us because we declare local variable
no as private.
5) If instance variable and local variable name is same then instance variable
never use in block in which local variable name is same.
package org.techhub;
class LVar{
int no;
void setValue(int no) {
no=no;
}
int getSquare() {
return no*no;
}
}
public class LocalVarApp {
public static void main(String[] args) {
LVar l = new LVar();
l.setValue(10);
int result = l.getSquare();
System.out.printf("Square is %d\n", result);
}
}
Above code generate result square is 0 because we use the instance variable
name and local variable name same but when we have instance variable name
and local variable name same then local variable never copy its value in
instance variable so avoiding these problem we have to use this with instance
variable.
package org.techhub;
class LVar{
int no;
void setValue(int no) {
this.no=no;
}
int getSquare() {
return no*no;
}
}
public class LocalVarApp {
public static void main(String[] args) {
LVar l = new LVar();
l.setValue(10);
int result = l.getSquare();
System.out.printf("Square is %d\n", result);
}
}
Above code generate output Square is 100
Q. what is this?
This is a internal reference present in every class which is used for point to
current running object in memory shown in following diagram
if we think about above code we have class name as LVar with function void
setValue(int no){ this.no=no; } if we think about main method in main method
we create object of LVar class like as LVar l = new LVar() here we have
reference variable l which contain 10000 address of object when we call the
function l.setValue(10) the meaning is 10000.setValue(10) so this 10 value pass
to local variable no in setValue(int no) function we have statement this.no=no
so here this reference points to 10000 address location which is address of
object pointed by reference l means here we can say this reference or pointer
and reference l points to same memory so 10 value stored in object after that
when we call l.getSquare() so we get result as 10*10
package org.techhub;
class LVar{
static int no;
void setValue(int x) {
this.no=x;
}
}
public class LocalVarApp {
public static void main(String[] args) {
LVar l = new LVar();
l.setValue(10);
}
}
if we think about above code we have class name as LVar with static variable
no and when create object in main method LVar l = new LVar() so here this
points to reference variable l so when we call the function setValue(int x) then
we have statement this.no=x here JVM can find reference or address who is
present in l so we can use static variable by this reference.
Note: if we define static function in class and try to use this reference in static
function so there is possibility we can call static function without object means
by class name and if we this reference in function then there is problem this
reference cannot find any address in memory because we not use object with
function calling and this work with function calling object i.e running obect so
compiler generate error.
package org.techhub;
class LVar{
int no;
static void setValue(int x) {
this.no=x;
}
}
public class LocalVarApp {
public static void main(String[] args) {
LVar.setValue(10);
}
}
above code generate compile time error to us because we this reference in static
function setValue().
15/02/2023
POJO class
POJO class is a class with a setter and getter method Setter method helps us to store data in object and
getter method help us to fetch data from object.
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){
this.name=name;
}
public String getName(){
return name;
}
public void setSal(int sal)
{ this.sal=sal;
}
public int getSal(){
return sal;
}
}
Example with memory diagram
if we think about diagram we have class name as Employee with field id and name and write a setter
and getter method for id and name after that we have statement in diagram Employee emp = new
Employee() here we have reference name is emp and new Employee() is object after that we have
statement emp.setId(1) means we call setter method and we store data in object using a setter method
means value 1 in id variable using setter method again we have statement emp.setName(“ABC”) here
we store ABC value in name variable object using a setName() method means in short we can say if
we want to store data in object using a POJO class we have setter method after that we have statement
System.out.println(emp.getId()+”\t”+emp.getName()); here we call emp.getId() means this method
return id from object and emp.getName() this method return name from object means we can say
getter method help to retrieve data from object .
POJO class work as container class using this we can store data and we can retrieve data.
Example with Source code
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;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
}
public class PojoApplication {
Screen short 1
screen shot 2
if we think above code and diagram in screen short 1 we have pojo class name as Employee with six
field or variable or data name as id,name,sal,address,email and contact and we write setter and getter
methods for every field. The major goal of this class is store data in object and pass to another class as
container because we required 6 parameter in company class as per our previous example name as
without pojo class example so passing single single parameter we created pojo class and store 6
parameter in it and pass Employee reference in Company class addNewEmployee() method mention
in screen short 2.
Company class contain two methods void addNewEmployee (Employee employee) means we pass
employee reference in addNewEmployee() method indirectly we pass six parameter in
addNewEmployee() method
If we think about main method present in class CompanyApplication in main method we created
object of Company class after that we have Statement Employee emp = new Employee() means here
we created object of Pojo class and store its reference in emp as per our diagram it is 10000 after that
we have emp.setId(1); emp.setName(“ABC”); emp.setSal(10000); emp.setEmail(“[email protected]”);
emp.setAddress(“PUNE”); emp.setContact(“12333333”); using this method we store data in
Employee class object whose address present in emp after that we have statement
c.addNewEmployee(emp) means we pass employee reference in Company class as parameter means
we pass 10000 address to addNewEmployee() function as per our example and it is hold by local
reference name as employee declared under addNewEmployee(Employee employee) method means
employee reference from addNewEmployee() method define under Company class use object created
in main function using call by reference technique after that we have statement in addNewEmployee()
method this.employee=employee means we copy the address of local variable in instance variable
declared under Company class means instance variable of Employee from Company class also points
to object created in main function means here we can say we have single object in memory and use by
three different references in program again we have c.showDetails() statement in main function means
we call showDetails() function of Company class from main method and in that method we have
statement String name =employee.getName() means 10000.getName() means in showDetail()
function we use data from object which we created in main function using getter method and display
it.
Note: means if we think about POJO class we can say setter method normally use for store data in
object and use setter method from object want to pass as parameter and using getter method we can
use object data.
16/02/2023
Example with POJO class object as parameter
package org.techhub;
public class Product {
private int id;
private String name;
private int price;
public int getPrice() {
return price;
}
public void setPrice(int price) {
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;
}
}
package org.techhub;
public class Shop {
Product prod;
public void addNewProduct(Product prod) {
this.prod=prod;
}
public void show() {
System.out.println(prod.getId()+"\t"+prod.getName()+"\t"+prod.getPrice());
}
}
package org.techhub;
class B
{ void setA(A a1) {
a1.no=200;
}
}
if we think about above diagram we have main method in TestMCQAPP class in this method we have
statement A a2 = new A(); here we create object class A and store its address in reference variable a2
in our diagram we consider 10000 address of A class object after that we have statement a2.setNo(10)
means we call setNo() method of class A and pass 10 value in it means 10 value stored in object
whose address is 10000 again we have statement new B().setA(a2) here we created anonymous object
of class B and we pass reference of class A to this method i.e we pass a2 means we pass 10000 to
setA() function this address get stored in local variable a1 and we have logic in setA( A a1){
a1.no=200; } means we replace this value on address 10000 means 200 get override on 10 stored in
object 10000 by a2 reference and return type of A setA(A a1) function is class A means we can return
reference of class A from setA() function at calling point as our example we return reference a1 from
set(A a1) function at calling point means reference A a3 = new B().setA(a2) here a3 points a1 means
a3 points 10000 means a2 and a3 points to same memory when we call
System.out.println(a3.getNo()); then this method return no value and print so no value is 200 so we
have output 200
Array of Objects
Array of objects is used for store multiple object data in single name reference
Example: Create Employee class with 5 objects store data in it and display it.
So in this scenario we have to use array of object concepts.
if we think about above code we have reference statement Employee emp[]= new Employee[5]; the
meaning of this statement is we create 5 references of Employee class for storing five object address
when think about this statement Employee emp [] = new Employee[5]; here we create five references
the values that references is by default null
when we think about for loop in above diagram for(int i=0; i<emp.length; i++) first time i=0 and i<5
i.e length of array this condition is true so your control enter in for loop and execute statement
emp[i]=new Employee() means emp[0]= new Employee() using new Employee() JVM create new
object in memory and store id and name in that object and store the address of object in emp[0] means
here we can say emp[0] is reference which points to first object ,again i++ so I increase by 1 so
second time your condition is like as i<emp.length means 1 < 5 it is true condition so your control
enter in loop then we statement emp[i]=new Employee() i.e emp[1] = new Employee() again your
JVM create new object in memory and store id and name in it and store its address in emp[1]
reference and so on .
}
public class EmployeeArrayOfObjectApp {
public static void main(String[] args) {
Employee emp []= new Employee[5];//array of references.
for(int i=0; i<emp.length;i++) {
Scanner xyz = new Scanner(System.in);
emp[i] = new Employee();//array of objects
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 employee details");
for(int i=0; i<emp.length;i++) {
System.out.println(emp[i].getId()+"\t"+emp[i].getName()+"\t"+emp[i].getSal());
}
}
20/02/2023
Constructor
Q what is constructor?
Constructor is function same name as class name without return type
Q. how to declare constructor in java?
If we want to declare constructor in java we have following syntax
Syntax: class classname{
classname (){
write here your logics
}
}
Example: class A {
A () {
System.out.println (“I am constructor”);
}
}
Q. Why use constructor?
1) To initialize object: in the case of java we cannot allocate memory for object without
constructor calling means we can initialize some values of class using constructor at the time
of object creation so we can say it is used for to initialize object.
2) To call function at time of object creation: constructor call automatically when we
create object of class means if we want to execute some logic at time of object creation.
Types of constructor
package org.techhub;
class A {
A() {
System.out.println("I am constructor");
}
}
public class ConsApplication {
public static void main(String[] args) {
A a1 = new A();
}
}
Types of constructor
1) Default constructor: if we not pass parameter to constructor called as default constructor.
class A {
A() {System.out.println("I am constructor");
}
}
}
public class ArraySumApplication {
public static void main(String[] args) {
int a[] = new int[5];
Scanner xyz = new Scanner(System.in);
System.out.println("Enter values in array\n");
for(int i=0; i<a.length;i++) {
a[i]=xyz.nextInt();
}
ArraySum aSum = new ArraySum(a);
int result=aSum.getSum();
System.out.println("Result is "+result);
}
}
if we think about above code we have class ArraySumApplication with main method and one
more class name as ArraySum with parameterize constructor we pass array of type integer as
parameter in ArraySum constructor so if we think about main method we first created array
before object because we want to pass array as parameter to constructor so when we want to
parameter to constructor we need to pass parameter to object so we need to declare
parameter before object here we have array as parameter so we before object use array
int a[] = new int[5] and we have for loop for(int i=0; i<a.length;i++) { a[i]=xyz.nextInt(); }
using this statement we store all values in array and after for loop we have statement
ArraySum aSum = new ArraySum(a) means from here we pass array as parameter to
constructor
and we have one more method name as getSum() we call it int result=aSum.getSum() so we
get sum of all array elements.
Example: we want to create program to create class POJO class name as Employee with
id,name and salary with a setter and getter method and we want to create one more class
name as Company with parameterized constructor Company(Employee employee) here we
pass Employee class reference as parameter in Company class constructor and we have one
more method name as void show() using this method we can get employee details and display
it.
If we think about this code we have class name as Company which contain parameterized
constructor of Employee type so if we think main method code we have to create object of
Employee class before Company class and we store data in it and we pass employee class
reference in Company class constructor or in company class object.
Source Code
package org.techhub;
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;
}
class Company
{ Employee employee;
Company(Employee employee){
this.employee=employee;
}
void show() {
System.out.println(employee.getId()+"\t"+employee.getName()+"\t"+employee.getSa
l());
}
}
public class CompanyClassApplication {
}
if we think about above code we create object of Employee class and we store data in
employee object by using a setter methods but if we want to initialize data in employee object
at the time of object creation then you can declare parameterized constructor in Employee
class and pass three parameter in it and pass there parameter from Employee object to
employee constructor so we not need to call externally setter methods for storing data in
object shown in following code.
Example with Source code
package org.techhub;
class Employee
{
public Employee(String name,int id,int sal) {
this.name=name;
this.id=id;
this.sal=sal;
}
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;
}
class Company
{ Employee employee;
Company(Employee employee){
this.employee=employee;
}
void show() {
System.out.println(employee.getId()+"\t"+employee.getName()+"\t"+employee.getSal());
}
}
public class CompanyClassApplication {
}
3) Overloaded constructor: Overloaded constructor means if we use the same name
constructor with different type with different parameter list with different parameter sequence
called as overloaded constructor
In the case of constructor overloading which constructor get executed is dependent on its data
type, parameter list and parameter sequence shown in following Example
Example
package org.techhub;
class Cube {
int no;
float value;
Cube(int no) {
this.no = no;
}
Cube(float value) {
this.value = value;
}
int getIntCube() {
return no * no * no;
}
float getFloatCube() {
return value * value * value;
}
}
public class CubeOverloading {
public static void main(String x[]) {
Cube c1 = new Cube(5); //call integer constructor
Cube c2 = new Cube(5.5f); //call float constructor
int intCube =c1.getIntCube();
float floatCube=c2.getFloatCube();
System.out.println("Cube of integer is "+intCube);
System.out.println("Cube of float is "+floatCube);
}
}
Function call using anonymous object with parameterized constructor using
overloading
package org.techhub;
class Cube {
int no;
float value;
Cube(int no) {
this.no = no;
}
Cube(float value) {
this.value = value;
}
int getIntCube() {
return no * no * no;
}
float getFloatCube() {
return value * value * value;
}
}
public class CubeOverloading {
public static void main(String x[]) {
int intCube =new Cube(5).getIntCube();
float floatCube=new Cube(5.5f).getFloatCube();
System.out.println("Cube of integer is "+intCube);
System.out.println("Cube of float is "+floatCube);
}
}
Function call using anonymous object with parameterized constructor using overloading in
System.out.println() methods
package org.techhub;
class Cube {
int no;
float value;
Cube(int no) {
this.no = no;
}
Cube(float value) {
this.value = value;
}
int getIntCube() {
return no * no * no;
}
float getFloatCube() {
return value * value * value;
}
}
public class CubeOverloading {
public static void main(String x[]) {
System.out.println("Cube of integer is "+new Cube(5).getIntCube());
System.out.println("Cube of float is "+new Cube(5.5f).getFloatCube());
}
}
22/02/2023
4) this () constructor
this () constructor is used for constructor chaining purpose
Q. what is constructor chaining?
Constructor chaining means if we call one constructor from another constructor called as
constructor chaining.
There are two ways to work with constructor chaining
1) Using this () constructor: we can perform constructor chaining within single class with
constructor overloading
2) Using super () constructor: using super constructor we can perform constructor chaining
by using inheritance
Note: super () constructor we will discuss in inheritance chapter.
if we think about above code we have class name as A with three constructor one is default
A(),one is A(int x) and one is A(float x) and we call integer constructor from default using
this(5) and we call float constructor from integer parameter constructor this(5.5f) so in the
case of constructor chaining calling perform by rule of stack means last call constructor
execute first and first call constructor execute last
So here we have class name as ConsChainApp with main method and in main method we
have statement A a1 = new A() here we call default constructor and from default constructor
call this(5) so this constructor execute the integer parameter constructor A(int x) and from
this constructor we call this(5.5f) means here float constructor get executed so here output is
I am float constructor 5.5, then I am integer constructor 5 and I am default constructor shown
in following code.
Note: this() constructor must be first line of code in calling constructor if we try to write it on
different line then compiler will generate compile time error to us .
Example:
class A {
A() { System.out.println("I am default constructor");
this(5);
}
A(int x) {
this(5.5f);
System.out.println ("I am integer constructor” + x);
}
A(float x) {
System.out.println ("I am float constructor” + x);
}
}
if we think about above code it will generate compile time error to us because we write
this(5) in second line of code and it is not possible we must be write this() constructor on
single line of code.
If we want to work with constructor we have know the some important points
if(count!=5) {
System.out.println("I am default constructor");
A();
}
++count;
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
if we think about above code we get compile time error because we try to perform recursion
within constructor and it is not possible.
class A {
int count=0;
A() { if(count!=5) {
System.out.println("I am default constructor");
A();
}
++count;
}
}
3) We cannot declare constructor as static
Because static member allocate memory before creating object of class but constructor must
be call when we create object of class and it is opposite behavior of each so we cannot
declare constructor as static.
package org.techhub.chaining;
class A {
int count=0;
static A() {
System.out.println("I am constructor");
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
Above code generate compile time error to us because we have constructor and we declare it
as static in code static A () and it is not allowed so compiler will generate compile time error
to us.
5) Cannot declare constructor as final (Note: we will discuss final keyword in inheritance
chapter)
class A {
int count=0;
final A() {
System.out.println("I am constructor");
}
}
class B extends A //here A is parent and B is child
{
}
Above code will generate compile time error to us because we try to declare constructor as
final.
Final is used for avoid method overriding in java but constructor cannot override so use of
final with constructor is meaningless.
6) If we have single constructor in class and if we declare constructor as private then we
cannot create its object outside of class
package org.techhub.chaining;
class A {
int count=0;
private A() {
System.out.println("I am constructor");
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
above code will generate compile time error to us because we have single constructor in class
with private access specifier and it is not possible to access private member outside of class
so compiler will generate compile time error to us
Note: when we want to create SingleTone class and Utility class in java then class
constructor must be private.
iii) Define one static method and return same class reference from it.
class ABC{
private static ABC ab;
private ABC(){
System.out.println(“I am singleton class”);
}
public static ABC getInstance(){
if(ab ==null)
{ ab = new ABC();
}
return ab;
}
}
if we think about above diagram we have class name as ABC with private constructor and in
this class we have one reference name as private static ABC ab; and we have one method
public static ABC getInstance() this method return reference of ABC class and if we think
about main method we have statement ABC a1 = ABC.getInstance() means we call method
ABC.getInstance() using classname because it is a static and in this method contain logic
if(ab == null) so initially a1 is null so this condition is true and if block get executed then
ab = new ABC() is get executed means we created object of ABC class within definition and
when we create object of ABC class then constructor of ABC get executed and we get output
I am constructor and after if block we have statement return ab means we return reference of
ab class to function calling i.e it store in a1 reference after that we have next statement in
main method ABC a2 = ABC.getInstance() means we call getInstance() method second time
but second time ab contain 1000 address not null value so we have logic in getInstance()
method if(ab == null) so this statement get false so new object not created just return ab
reference at function calling means in a2 rerence means we have single object in memory but
we have two references point to same object and so on means here we can say we created
only one object in memory with different references called as Singleton class.
Source with Example
package org.techhub;
class ABC{
private static ABC ab;
private ABC() {
System.out.println("I am constructor");
}
public static ABC getInstance() {
if(ab==null) {
ab = new ABC();
}
return ab;
}
}
public class SingleTonApplication {
public static void main(String[] args) {
ABC a1 = ABC.getInstance();
ABC a2 = ABC.getInstance();
ABC a3 = ABC.getInstance();
}
}
2) What is Utility class: A utility class means class contain private constructor and all
methods must be static called as utility class.
Example of Utility class: java.lang.Math is utility class in java.
How to create user defined Utility class in java
If we want to create utility class in java we have following steps.
class ABCD
{
private ABCD() {
}
public static void test() {
System.out.println("I am test method from utility class");
}
public static void show() {
System.out.println("I am show method from utility class");
}
}
public class UtilityClassApplication {
public static void main(String[] args) {
ABCD.test();
ABCD.show();
}
}
23/02/2023
Inheritance
Inheritance means to transfer property of one class to another class called as
inheritance.
Property sender class called as parent class and property receiver class called as
child class.
Q. Why use inheritance or what is benefit of inheritance?
There are two major benefits of inheritance.
1) Reusability: Reusability means we can use parent class content without
creating its object by single or multiple child classes
2) Extensibility: Extensibility means child class can acquire property from
parent class and can add own properties in child class
How to perform inheritance in java
If we want to perform inheritance in java we have extends keyword
Syntax:
class parentclassname
{
}
class chilclassname extends parentclassname
{
}
e.g class Value{
int a,b;
void setValue(int x,int y)
{ a=x;
b=y;
}
}
class Add extends Value{
int getAdd(){
return a+b;
}
}
class Mul extends Value{
int getMul(){
return a*b;
}
}
if we think about above code we have three classes name as Value,Add and Mul
here Value is parent class Add and Mul is child classes.
if we think here we can create object of Add and Mul class and we can reuse
setValue() function of Value class using Add and Mul class called as reusability
and in Add class we added one extra method name as getAdd() and return
addition of two values from Value class and in Mul class we added one extra
method name as getMul() and we return multiplication of two values called as
extensibility
Note: In the case of java we cannot create any program without inheritance
How it is possible?
In java every class has default parent class name as Object class and it is a
member of java.lang package and java.lang is a default package of java means
we not need to import it in program.
Example:
class A{
}
Internal meaning
class A extends java.lang.Object{
}
Q. Why Object class is parent of every class in java?
Because Object class contain some methods those required to every class in java
int hashCode()
boolean equals()
String toString()
Object clone()
Class getClass()
void finalize()
void wait()
void wait(int)
void notify()
void notifyAll()
static{
}
Note: in the case of inheritance we not need to create object of parent class we
can use parent content by using child class object shown in following code.
24/02/2023
Constructor with inheritance
When we have parent class with default constructor and child class with constructor and if we create
object of child class then by default parent constructor get executed before child constructor shown in
following example.
Source code Example
package org.techhub;
class A
{ A(){ System.out.println("I am parent constructor");
}
}
class B extends A
{ B(){ System.out.println("I am child constructor");
}
}
public class ConsWithInheritenceApp {
public static void main(String[] args) {
B b1 = new B();
}
}
if we think about above code we have two classes name as A and B so A is our parent class and B is
our child class and A class contain default constructor and we created object of class B but internally
A constructor get executed before constructor of class B shown in following output.
Output
I am parent constructor
I am child constructor
Note: when we have parameter in parent constructor and if we create object of child class then
programmer has responsibility to pass parameter to parent constructor from child class for that we
have to use super() constructor
If programmer not passes parameter to parent constructor from child class then compiler will generate
compile time error to us shown in following code.
Code with compilation error
package org.techhub;
class A
{ A(int x){ System.out.println("I am parent constructor");
}
}
class B extends A
{ B(){ System.out.println("I am child constructro");
}
}
public class ConsWithInheritenceApp {
public static void main(String[] args) {
B b1 = new B();
}
}
If we think about above code we get compile time error to us because we have A(int x) integer
parameter in parent constructor and we not provide parameter from child constructor so compiler will
generate compile time error to us
So if we want to resolve this problem we have to pass parameter from child class constructor and we
have to use super () constructor in class B constructor because our B is child class.
}
}
public class ConsWithInheritenceApp {
public static void main(String[] args) {
B b1 = new B();
}
}
Q. how many ways to perform constructor chaining in java?
There are two ways to perform constructor chaining in java
1) Using this () constructor: normally use this () constructor perform constructor chaining within
same class means in short we can say for perform constructor chaining using this () constructor we
need to use constructor overloading in same class.
2) Using super () constructor: normally super () constructor perform constructor chaining using
inheritance
Final keyword
Final is non access specifier in java which we can use with variable, with function and with class.
Final variable
final variable is used for declare constant values in java means if we declare any variable as final then
we cannot modify its value once we assign it and if we try to modify the value of final variable then
compiler will generate error to us at compile time.
Example with final
package org.techhub;
public class FinalVariableApplication {
public static void main(String[] args) {
final int a=100;
++a;
System.out.println("A is "+a);
}
}
If we think about above code we have statement final int a=100 means initialize variable at a=100 as
constant value using final keyword but we try to modify this value ++a so it is not possible so
compiler will generate compile time error to us.
Note: for setting constant value in program must be use final otherwise not.
Final method
Final method means a method cannot override in child class means final keyword is used for avoid
method overriding in java.
}
If we want to work with method overriding in java we have some important rules
1) In method overriding parent method signature and child method signature must be same
Or must be match
class A
{ void show(){
}
}
class B extends A
{
void show(){
}
}
Means in overriding method return type, function name, argument list and argument type must be
same.
}
}
Above code generate compile time error to us because we define method in as
void show() and we try to change its return type in child class but it is not allowed in
Method overriding so compiler will generate compile time error to us.
Note: if we have same method in parent class and same method in child class with different parameter
or different data type or different parameter sequence then it is consider overloading in inheritance.
package org.techhub;
class A
{ void show(int x) {
System.out.println("X is "+x);
}
}
class B extends A
{ void show() {
System.out.println("I am show in child");
}
}
public class OverridingRulesApp {
public static void main(String[] args) {
new B().show(10);
}
}
If we think about above code we have two classes name as A and B and in A class contain method
void show (int x) and in B class contain method void show() without parameter means we have same
name method with different parameter sequence or data type called as method overloading
So method overloading may be happen in inheritance using parent and child classes.
Q. how we can call parent logic in method overriding using child object?
If we want to call parent logic using child object in method overriding we have to use super reference
or keyword.
Super is reference in java which is used for call parent logic from child class when child override
method from parent.
Example
class A
{ void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ void show() {
super.show(); //call parent show method
System.out.println("I am show in child");
}
}
public class OverridingRulesApp {
public static void main(String[] args) {
new B().show();
}
}
if we think about above code we have method name void show() and we override in child class name
as B and in class we have statement super.show() means we call parent show() method from child
class using super reference so we get output I am parent show I am show in child.
Example
package org.techhub;
class A
{
final void show() {
System.out.println("I am final");
}
}
class B extends A
{
}
public class OverridingRulesApp {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}
above code generate output to us I am final in above we define final void show() in class A and we
inherit class A in class B and if we think about main method we create object of class B and call
b1.show() using class B reference so show() get call means we can say B class use show() method
from A by using inheritance even show is final so we can say we can inherit final method.
2) Loose Coupling: Loose coupling means if one class function is partially dependent on another
class object called as loose coupling and we can achieve loose coupling by using dynamic
polymorphism.
If we think about above diagram we have three classes name as A B and C Here A and B
is parent classes and C is child class so class A contain show () method and class B contain show ()
method and we inherited both classes in class C means class Contain two version of show () method
one is from class A and one is from class B so when we create object of class C and try to call method
show () then compiler will generate compile time error to us called as diamond problem and if we
want to resolve this problem java suggest use interface.
Syntax:
interface interfacename
{
}
Note: interface is internally like as abstract class so we cannot create its object and if we try to create
its object then we get compile time error.
Example:
interface ABC {
}
If we declare any method within interface it is by default abstract means we cannot write logic of
interface method in java.
Example:
interface ABC
{void show (); //public abstract void show();
}
So if we want to work with interface then we have to override interface in any another class and
Override its method and write its logic so if we want to implement interface in any another class we
have implements keyword.
Syntax:
class classname implements interfacename
{ public returntype methodname(arguments){
Write here your logics
}
}
Example of interface
package org.techhub;
interface ABC
{ void show();//public abstract void show()
}
class MNO implements ABC
{ public void show() {
System.out.println("I am interface method ");
}
}
public class InterfaceTestApplication {
public static void main(String[] args) {
MNO m = new MNO();
m.show();
}
}
If we want to work with interface we have some important points
interface ABC
{ float PI=3.14f;
void show();//public abstract void show()
}
Q. if we declare abstract method in class then we can declare it as protected and interface
method is abstract so why we cannot declare interface method as protected if it is abstract?
When we declare abstract method in class then it work with default access specifier by default and if
we declare it as protected then protected can override on default so compiler will accept protected
Example shown in following diagram
But when we declare method in interface then it will use public abstract access specifier by default
and if we declare it as protected then protected not override on public so compiler consider method
with protected public access specifier in java there is public or protected access specifier not protected
public access specifier so compiler will generate error to us at compile time shown in following
diagram.
package org.techhub;
interface ABC
{ abstract void show();
}
class MNO implements ABC
{ public void show() {
System.out.println("I am interface method ");
}
}
public class InterfaceTestApplication {
If we think about above code we have ABC is interface and MNO is implementer class of ABC
interface here we created reference of ABC and object of MNO so it is allow
Means here we create reference of interface and object of its implementer class
Abstract Interface
For declare abstract class use abstract keyword For declare interface use interface keyword
Abstract class is used for achive partial Interface can use for 100% abstraction
abstraction
Abstract class variable is not public static and Interface variable is by default public static final
final by default
Abstract may be contain constructor But interface cannot have constructor
We can declare abstract method in abstract class But we cannot declare abstract method in
protected interface as protected
Abstract class need to extends in another class But interface need to implement in another class
Abstract class cannot support for multiple Interface can support for multiple inheritance
inheritance
Abstract can define normal method in it But interface cannot define normal method in its
body but we can define static method in interface
as per jdk 1.8 as well as define default method
also as per jdk 1.8 version
Abstract method is not by default public and But interface method is by default public and
abstract abstract
Abstract class can implement interface But interface cannot inherit abstract class
Abstraction Encapsulation
Abstraction achieve by using abstract keyword Encapsulation achieve by using declaring
variable of class as private and access via public
setter and getter methods
Abstraction solve problem at design level Encapsulation solve problem at implementation
level
In abstraction just we provide prototype or Encapsulation we provide implementation of
template of method not its implementation method and hide data from end user or
unauthorized access by declaring data as private
and provide access as per logical level
The major goal of abstraction is achieve dynamic The major goal of encapsulation provide security
polymorphism to user data
Example of abstraction is Vehicle means we can Example of encapsulation suppose consider we
Vehicle contain engine () but we cannot predict are designing login application and if we create
class of verify user login then we can declare its
its design just we can provide its prototype and its username and password as private and we can
implementation is depend on type of vehicle. define one method name as verifyLogin() and we
can check internal login from database it is
example of encapsulation.
Final Abstract
Final can use with variable, function and class Abstract can use only with function and class
Final class can create its object Abstract class cannot create its object
Final class is used for achieve immutable objects Abstract class is used for achieve dynamic
polymorphism
Final class cannot inherit in any another class Abstract class must be inherit in any another class
Final method cannot override means use for Abstract method must be override
avoid method overriding
Final method can have logic Abstract method cannot have logic
Static Abstract
Static can work with variable and method as well Abstract can work with class and methods not
as only work inner class not outer class variable
If we use static keyword with method then we If we use abstract keyword with method then
can access it without using object of class need to call using abstract reference or child class
object
Static method can support to compile time Abstract method can support to dynamic
polymorphism polymorphism
Using static method we can achieve method Using abstract method we can achieve method
hiding overriding
Static method can use only static variable Abstract method can work with static as well as
abstract
Static method must have definition Abstract method not need a definition as well as
static keyword cannot work with abstract method
08-02-2023
Exception Handling
Q. What is Exception?
Exception is an event which occur at program run time and it is responsible for disturb normal flow of
application called as exception.
Q. Why use Exception Handling or what is benefit of Exception?
1) It help programmer to detect error at run time
2) Avoid code in which exception may be occur or code responsible for exception and execute
remaining application in safe zone
3) You can design custom error handling logic as per need to project.
3) finally: finally is block in java which always execute if exception generate in program or not
Syntax of finally block
try{
write here your logics in which exception may be occur
}
finally{
write here logic which want to execute always
}
or
try{
write here your logics in which exception may be occur
}
catch(exceptiontype ref)
{
}
finally{
write here logic which want to execute always
}
try{
write here your logics in which exception may be occur
}
finally{
write here logic which want to execute always
}
4) throw: throw keyword is used for handle user defined exceptions in java and we can use throw
with function
5) throws: throws is also keyword for handle checked exceptions and we can use it with function
also.
Example: Now we want to handle ArithmeticException using
import java.util.*;
public class DivNovApp
{
public static void main(String x[])
{ Scanner xyz = new Scanner(System.in);
int a,b,c;
System.out.println("Enter two values");
a=xyz.nextInt();
b=xyz.nextInt();
c=a/b;
System.out.printf("Division is %d\n",c);
System.out.println("Logic1");
System.out.println("Logic2");
}
}
Example
if we think about above code we get run time error i.e ArithmeticException because we have
statement c=a/b and we provide input as a=9 and b=0 so the statement c=a/b is like as c=9/0 and if
we divide any number by 0 it is consider as infinity and system cannot calculate infinity so JVM
generate run time exception to us
so we want to resolve this problem we need to handle exception using try and catch block
means as per this exception we need to c=a/b statement within try block and need to handle
ArithmeticException in catch block shown in following diagram and code
ArrayIndexOutOfBoundsException
This class is used for handle ArrayIndexOutOfBoundsException Normally this exception occur when
we try to store value in array more than its size then JVM generate
ArrayIndexOutOfBoundsExceptions.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
int a[] =new int[2];
a[2]=200;
System.out.println("Value is "+a[2]);
}
}
If we think about above code we created array of size 2 int a [] =new int [2]
means we have only two index in array i.e 0 & 1 but if we think about statement a[2]=200 means we
try to store value on 2nd index but which is not present in array so JVM generate run time error to us
ArrayIndexOutOfBoundsException to us.
So if we want to handle this exception at run time in code then we have to write a[2]=200 in try block
and ArrayIndexOutOfBounds in catch block shown in following code.
Source code
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try {
int a[] = new int[2];
a[2] = 200;
System.out.println("Value is " + a[2]);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Error is " + ex);
}
}
}
Example: NullPointerException
Normally NullPointerException generated by JVM when we try to use any reference without memory
allocation or without new keyword then JVM generate NullPointerException so it may array reference
or it may be object reference etc.
Example
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
static int a[];
public static void main(String[] args) {
try {
a[2] = 200;
System.out.println("Value is " + a[2]);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Error is " + ex);
}
}
}
if we think about above code it will generate NullPointerException to us because we have statement
int a[] means here we declare array variable but we not allocate its memory and we try to use without
new keyword a[2]=200 so without new we cannot use any array or object in java so JVM generate
NullPointerException to us
if we want to handle this problem we need to handle NullPointerException or use new keyword.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
static int a[];
public static void main(String[] args) {
try {
a[2] = 200;
System.out.println("Value is " + a[2]);
} catch (NullPointerException ex) {
System.out.println("Error is " + ex);
}
}
}
We have one more example of NullPointerException
package org.techhub;
import java.util.*;
class Test
{ void show()
{ System.out.println("I am show method");
}
}
public class ArrayExceptionApp {
static Test t;
public static void main(String[] args) {
t.show();
}
}
if we think about above code we have reference name as static Test t and we not initialize any object
address in it so it is by default null and we have statement t.show() so it is not possible if we want to
use any class member we must have object we cannot using reference without object so JVM generate
NullPointerException if we want to avoid this problem we have use try and catch block and handle
NullPointerException
package org.techhub;
import java.util.*;
class Test
{ void show()
{ System.out.println("I am show method");
}
}
public class ArrayExceptionApp {
static Test t;
public static void main(String[] args) {
try {
t.show();
}
catch(NullPointerException ex) {
System.out.println("Error is "+ex);
}
}
}
Example: NumberFormatException
Normally NumberFormatException occur when we try to convert string to value primitive type of
value
Some time if we try to convert string value to integer but if there is some space or if there any another
non numeric value in string then conversion is not possible so your JVM generate
NumberFormatException at run time.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
String s="12345 "; //12345 is integer but format is string because in ""
int a=Integer.parseInt(s);
System.out.println("A is "+a);
}
}
if we think about above code we have String s=”12345 “; string contain space and we have statement
int a=Integer.parseInt(s) here 12345 can convert by JVM from string to integer but space cannot
convert by JVM in to integer so we get NumberFormatException at run time so if we want to avoid
this problem we have to handle NumberFormatException shown in following code.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
String s="12345 "; //12345 is integer but format is string because in ""
try {
int a=Integer.parseInt(s);
System.out.println("A is "+a);
}
catch(NumberFormatException ex) {
System.out.println("There is conversion problem ");
}
}
}
Example: InputMismatchException
InputMismatchException occur when user except specific type of input but provide different type then
JVM generate InputMismatchException at run time.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
int a,b;
System.out.println("Enter two values");
Scanner xyz = new Scanner(System.in);
a=xyz.nextInt();
b=xyz.nextInt();
System.out.printf("A=%d\tB=%d\n",a,b);
}
}
Example:
Enter two values
10.4
Exception in thread "main" java.util.InputMismatchException
for avoid this problem we have tho handle InputMismatchException.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
int a,b;
try {
System.out.println("Enter two values");
Scanner xyz = new Scanner(System.in);
a=xyz.nextInt();
b=xyz.nextInt();
System.out.printf("A=%d\tB=%d\n",a,b);
}
catch(InputMismatchException ex)
{
System.out.println("Error is "+ex);
}
}
}
Note: if we write only Exception in catch block then JVM can handle any type of exception.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try {
//write here any logic JVM can handle any exception
int a,b,c;
Scanner xyz = new Scanner(System.in);
System.out.println("Enter two values");
a=xyz.nextInt();
b=xyz.nextInt();
c=a/b;
System.out.println("Division is "+c);
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
Note: because Exception is a parent of all exception classes in java as per the rule of loose coupling
we can say if we pass reference of parent you can pass any child reference so it is possible we can
manage more than one exception by single catch block with help of Exception class.
}
}
}
if we think about above code we get compile time error because we have two catch block with single
try block and in first catch block we use Exception class as parameter means catch(Exception ex) and
in second catch block we use catch(ArithmeticException ex) but if we use Exception then we can
handle any kind of exception like as ArithmeticException, InputMismatchException etc so we not
need to handle it separately so after catch(Exception ex) write any catch block with another exception
class is meaningless so compiler will generate compile time error to us
Note: In JDK 1.7 version of java there some enhancement in exception means java added two new
concepts in exception.
1) Catch using multiple exception class with single reference
2) Try with resource bundle
Example without Catch using multiple exception class with single reference
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try {
// write here any logic JVM can handle any exception
int a, b, c;
Scanner xyz = new Scanner(System.in);
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
} catch (ArithmeticException ex) {
System.out.println("Error is "+ex);
}
catch(InputMismatchException ex) {
System.out.println("Error is "+ex);
}
}
}
If we think about above code we handle two exceptions ArithmeticException and
InputMismatchException but for that we need to write two separate catch blocks but when we want to
10 different type of exception separately then we need to write 10 different catch block and it is not
feasible in real time so java suggest you can handle multiple exception by single catch block and for
that we have to use catch with multiple classes using single reference shown in following code
Example
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try {
// write here any logic JVM can handle any exception
int a, b, c;
Scanner xyz = new Scanner(System.in);
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
} catch (ArithmeticException | InputMismatchException |
ArrayIndexOutOfBoundsException ex) {
System.out.println("Error is "+ex);
}
}
}
2) Try with resource bundle
Try with resource bundle means we directly pass reference as parameter to try block or we direct
create object in try block means here try block work like as function parameter or function calling
point.
Syntax:
try(object)
{
}
catch(exceptiontype ref)
{
}
Source code with example
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try (Scanner xyz = new Scanner(System.in)) {
// write here any logic JVM can handle any exception
int a, b, c;
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
} catch (ArithmeticException | InputMismatchException |
ArrayIndexOutOfBoundsException ex) {
System.out.println("Error is " + ex);
}
}
}
Finally block
finally is block in java which always execute if exception generate in program or not Normally finally
block use by developer to writing code which is necessary to execute in any situation like database
connection close , file close etc
Note: finally can work with try as well as finally can work with try and catch
Example: try with finally without catch
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try (Scanner xyz = new Scanner(System.in)) {
// write here any logic JVM can handle any exception
int a, b, c;
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
}
finally {
System.out.println("I can execute always");
}
System.out.println("Logic1");
System.out.println("Logic2");
System.out.println("Logic3");
}
}
Example: try with finally with catch block
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try (Scanner xyz = new Scanner(System.in)) {
// write here any logic JVM can handle any exception
int a, b, c;
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
finally {
System.out.println("I can execute always");
}
System.out.println("Logic1");
System.out.println("Logic2");
System.out.println("Logic3");
}
}
Q. what is diff between catch and finally?
Finally Catch
Finally block not need parameter Catch block required parameter
Finally always if exception generate by try or not Catch block always execute when exception
generate in try block
Using finally we cannot handle exception in Using catch we can handle exception in program
program just execute code which essential to and execute remaining application
execute in any situation.
If we use try without catch and if exception But if we use try with catch and finally then catch
generate in program then finally get before block execute before finally block
exception
10-03-2023
throws and throw
throws is clause for exception handling which is used with a function normally throws clause refer by
programmer to handle checked exceptions.
Syntax:
return type function name (data type arguments) throws exception type
{Write here your logics
}
Note: we have two questions
1) Why use throws clause with function definition
2) Why throws handle to checked exception
Checked exception help us to generate compile time warning if there is possibility code may be
contain exception and if we use function then we can reuse code in program means if suppose we
have three developer A , B and C and if A developer design some logical code and write function for
that and write code in function if B and C developer required logic design by A then B and C
developer can call function defined by developer A but if function may be contain exception design
by developer A so the responsibility of A is generate compile time warning related with exception at
function calling point then A programmer can use throws clause with function and handle checked
exception means when A handle checked exception with throws clause with his function and if any
other developer call function defined by A then compiler will generate compile time warning for
exception so this is major reason we can use throws and checked exception with function definition.
Important points related with checked exceptions
1) Need to handle with function definition using throws clause
2) When we use the throws keyword with function definition then we not need to write try and catch
in function block.
3) When we use throws keyword with function definition then we have to write try and catch at
function calling point.
4) When we use throws keyword with function definition the exception generate in function definition
but handle at function calling point means JVM create exception object in function definition
implicitly and throw it at function calling point.
throw keyword
throw keyword is used for handle user defined exceptions in java
Q. What is user defined exceptions?
Those exceptions define by programmer itself called as user defined exceptions.
Q. Why we need to create user defined exceptions in java?
1) Suppose programmer has some error or exception in his program but java not provide inbuilt class
for handle that exception in this scenario programmer can create own exception handler class and
manage exception
2) Project requirement is to design custom exception handler in this case programmer need to own
exceptions called as user defined exceptions.
package org.techhub;
import java.util.*;
class VoterException extends ArithmeticException
{
public String getVoterError() {
return "invalid voter you are not eligible";
}
}
class ValidateVoter
{
void verifyVoter(String adhar, int birthYear) {
int age=2023-birthYear;
if(age<18) {
VoterException v = new VoterException();
throw v;
}
else {
System.out.println("Welcome");
}
}
}
public class VotingApplication {
Throws Throw
Use for handle checked exception User for handle user defined exceptions
Not need to create explicitly object of exception Need to create explicitly of object exception and
class and throw it internally JVM create object throw it manually
and throw at function calling point
Throws can work with multiple exception at time Throw cannot work with multiple exception at
time
}
}
}
above code generate compile time error to us because we use throw with non exception class. you can
only use throw with exception class or exception child class not other
}
}
}
If we think about above code there is any compile time error it will execute properly because we can
use exception class with throw class and if we use Exception in catch block then we can handle any
kind of exception.
}
}
}
this code not handle ArithmeticException at run time because we handle InputMismatchException
and throw ArithmeticException
import java.util.InputMismatchException;
}
}
}
Above code execute properly and handle exceptions
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws SQLException
{
}
}
public class TestThrow {
public static void main(String[] args) {
Test t = new Test();
t.getConn();
}
}
Above code will generate compile time error to us because we handle SQLException with getConn()
method at function definition and SQLException is checked category exception so when we use any
checked exception at with function definition then we must be handle exception at function calling
point means we must be write try and catch at function calling point so we not use try and catch at
function calling point means we not handle exception so compiler will generate compile time error to
us so if we want to remove this error write try and catch at function calling point shown in following
code.
package org.techhub;
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws SQLException
{
}
}
public class TestThrow {
public static void main(String[] args) {
try {
Test t = new Test();
t.getConn();
}catch(SQLException ex) {
}
}
}
Q.what will be output of given code?
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws Exception {
}
}
class ABC extends Test
{ void getConn() throws Throwable{
}
}
above code will generate compile time error to us because we handle Exception with getConn()
method in Test class and Test is parent of ABC class and in ABC class we again override getConn()
method and handle Throwable class so it is not possible means in the case of override if we handle
child class in parent and try to handle parent in child then it is not possible
but if we handle parent exception class in parent method and override same method in child and
handle child exception class it is possible but we need to handle parent exception where we call
function.
Shown in Following Code
package org.techhub;
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws Throwable {
}
}
class ABC extends Test
{ void getConn() throws Exception{
}
}
public class TestThrow {
public static void main(String[] args) {
try {
Test t = new Test();
t.getConn();
}
catch(Throwable ex) {
}
}
}
Q. what will be output of given code?
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn() {
}
}
class ABC extends Test
{ void getConn() throws Exception{
}
}
if we think about above code we get compile time error to us because we not handle exception in
parent class and we override same method in child class try to handle exception so it is not allowed so
compiler generate error to us if we want to remove this we need to handle exception parent method or
remove exception with child method shown in following code.
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws Exception {
}
}
class ABC extends Test
{ void getConn() throws Exception{
}
}
Constructor
Q what is constructor?
Constructor is function same name as class name without return type
Q. how to declare constructor in java?
If we want to declare constructor in java we have following syntax
Syntax: class classname{
classname (){
write here your logics
}
}
Example: class A {
A () {
System.out.println (“I am constructor”);
}
}
Q. Why use constructor?
1) To initialize object: in the case of java we cannot allocate memory for object without
constructor calling means we can initialize some values of class using constructor at the time
of object creation so we can say it is used for to initialize object.
2) To call function at time of object creation: constructor call automatically when we create
object of class means if we want to execute some logic at time of object creation.
Types of constructor
package org.techhub;
class A {
A() {
System.out.println("I am constructor");
}
}
public class ConsApplication {
public static void main(String[] args) {
A a1 = new A();
}
}
Types of constructor
1) Default constructor: if we not pass parameter to constructor called as default
constructor.
class A {
A() {System.out.println("I am constructor");
}
}
Example:
package org.techhub;
import java.util.*;
class ArraySum{
int a[];
int sum=0;
ArraySum(int a[]){
this.a=a;
}
int getSum() {
for(int i=0; i<a.length;i++) {
sum = sum+a[i];
}
return sum;
}
}
public class ArraySumApplication {
public static void main(String[] args) {
int a[] = new int[5];
Scanner xyz = new Scanner(System.in);
System.out.println("Enter values in array\n");
for(int i=0; i<a.length;i++) {
a[i]=xyz.nextInt();
}
ArraySum aSum = new ArraySum(a);
int result=aSum.getSum();
System.out.println("Result is "+result);
}
}
if we think about above code we have class ArraySumApplication with main method and
one more class name as ArraySum with parameterize constructor we pass array of type
integer as parameter in ArraySum constructor so if we think about main method we first
created array before object because we want to pass array as parameter to constructor so
when we want to parameter to constructor we need to pass parameter to object so we
need to declare parameter before object here we have array as parameter so we before
object use array
int a[] = new int[5] and we have for loop for(int i=0; i<a.length;i++) { a[i]=xyz.nextInt(); }
using this statement we store all values in array and after for loop we have statement
ArraySum aSum = new ArraySum(a) means from here we pass array as parameter to
constructor
and we have one more method name as getSum() we call it int result=aSum.getSum() so we
get sum of all array elements.
Example: we want to create program to create class POJO class name as Employee with
id,name and salary with a setter and getter method and we want to create one more class
name as Company with parameterized constructor Company(Employee employee) here we
pass Employee class reference as parameter in Company class constructor and we have one
more method name as void show() using this method we can get employee details and
display it.
If we think about this code we have class name as Company which contain parameterized
constructor of Employee type so if we think main method code we have to create object of
Employee class before Company class and we store data in it and we pass employee class
reference in Company class constructor or in company class object.
Source Code
package org.techhub;
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;
}
class Company
{ Employee employee;
Company(Employee employee){
this.employee=employee;
}
void show() {
System.out.println(employee.getId()+"\t"+employee.getName()+"\t"+employee.getS
al());
}
}
public class CompanyClassApplication {
}
if we think about above code we create object of Employee class and we store data in
employee object by using a setter methods but if we want to initialize data in employee
object at the time of object creation then you can declare parameterized constructor in
Employee class and pass three parameter in it and pass there parameter from Employee
object to employee constructor so we not need to call externally setter methods for storing
data in object shown in following code.
Example with Source code
package org.techhub;
class Employee
{
public Employee(String name,int id,int sal) {
this.name=name;
this.id=id;
this.sal=sal;
}
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;
}
class Company
{ Employee employee;
Company(Employee employee){
this.employee=employee;
}
void show() {
System.out.println(employee.getId()+"\t"+employee.getName()+"\t"+employee.getSal());
}
}
public class CompanyClassApplication {
}
3) Overloaded constructor: Overloaded constructor means if we use the same name
constructor with different type with different parameter list with different parameter
sequence called as overloaded constructor
In the case of constructor overloading which constructor get executed is dependent on its
data type, parameter list and parameter sequence shown in following Example
Example
package org.techhub;
class Cube {
int no;
float value;
Cube(int no) {
this.no = no;
}
Cube(float value) {
this.value = value;
}
int getIntCube() {
return no * no * no;
}
float getFloatCube() {
return value * value * value;
}
}
public class CubeOverloading {
public static void main(String x[]) {
Cube c1 = new Cube(5); //call integer constructor
Cube c2 = new Cube(5.5f); //call float constructor
int intCube =c1.getIntCube();
float floatCube=c2.getFloatCube();
System.out.println("Cube of integer is "+intCube);
System.out.println("Cube of float is "+floatCube);
}
}
Function call using anonymous object with parameterized constructor using overloading
package org.techhub;
class Cube {
int no;
float value;
Cube(int no) {
this.no = no;
}
Cube(float value) {
this.value = value;
}
int getIntCube() {
return no * no * no;
}
float getFloatCube() {
return value * value * value;
}
}
public class CubeOverloading {
public static void main(String x[]) {
int intCube =new Cube(5).getIntCube();
float floatCube=new Cube(5.5f).getFloatCube();
System.out.println("Cube of integer is "+intCube);
System.out.println("Cube of float is "+floatCube);
}
}
Function call using anonymous object with parameterized constructor using overloading in
System.out.println() methods
package org.techhub;
class Cube {
int no;
float value;
Cube(int no) {
this.no = no;
}
Cube(float value) {
this.value = value;
}
int getIntCube() {
return no * no * no;
}
float getFloatCube() {
return value * value * value;
}
}
public class CubeOverloading {
public static void main(String x[]) {
System.out.println ("Cube of integer is "+new Cube (5).getIntCube ());
System.out.println ("Cube of float is “+new Cube (5.5f).getFloatCube ());
}
}
4) this () constructor
this () constructor is used for constructor chaining purpose
Q. what is constructor chaining?
Constructor chaining means if we call one constructor from another constructor called as
constructor chaining.
There are two ways to work with constructor chaining
1) Using this () constructor: we can perform constructor chaining within single class with
constructor overloading
2) Using super () constructor: using super constructor we can perform constructor chaining
by using inheritance
Note: super () constructor we will discuss in inheritance chapter.
Example:
if we think about above code we have class name as A with three constructor one is default
A(),one is A(int x) and one is A(float x) and we call integer constructor from default using
this(5) and we call float constructor from integer parameter constructor this(5.5f) so in the
case of constructor chaining calling perform by rule of stack means last call constructor
execute first and first call constructor execute last
So here we have class name as ConsChainApp with main method and in main method we
have statement A a1 = new A() here we call default constructor and from default
constructor call this(5) so this constructor execute the integer parameter constructor A(int
x) and from this constructor we call this(5.5f) means here float constructor get executed so
here output is
I am float constructor 5.5, then I am integer constructor 5 and I am default constructor
shown in following code.
Note: this() constructor must be first line of code in calling constructor if we try to write it
on different line then compiler will generate compile time error to us .
Example:
class A {
A() { System.out.println("I am default constructor");
this(5);
}
A(int x) {
this(5.5f);
System.out.println ("I am integer constructor” + x);
}
A(float x) {
System.out.println ("I am float constructor” + x);
}
}
if we think about above code it will generate compile time error to us because we write
this(5) in second line of code and it is not possible we must be write this() constructor on
single line of code.
If we want to work with constructor we have know the some important points
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
if we think about above code we get compile time error because we try to perform
recursion within constructor and it is not possible.
class A {
int count=0;
A() { if(count!=5) {
System.out.println("I am default constructor");
A();
}
++count;
}
}
3) We cannot declare constructor as static
Because static member allocate memory before creating object of class but constructor
must be call when we create object of class and it is opposite behavior of each so we cannot
declare constructor as static.
package org.techhub.chaining;
class A {
int count=0;
static A() {
System.out.println("I am constructor");
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
Above code generate compile time error to us because we have constructor and we declare
it as static in code static A () and it is not allowed so compiler will generate compile time
error to us.
5) Cannot declare constructor as final (Note: we will discuss final keyword in inheritance
chapter)
class A {
int count=0;
final A() {
System.out.println("I am constructor");
}
}
class B extends A //here A is parent and B is child
{
}
Above code will generate compile time error to us because we try to declare constructor as
final.
Final is used for avoid method overriding in java but constructor cannot override so use of
final with constructor is meaningless.
6) If we have single constructor in class and if we declare constructor as private then we
cannot create its object outside of class
package org.techhub.chaining;
class A {
int count=0;
private A() {
System.out.println("I am constructor");
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
above code will generate compile time error to us because we have single constructor in
class with private access specifier and it is not possible to access private member outside of
class so compiler will generate compile time error to us
Note: when we want to create SingleTone class and Utility class in java then class
constructor must be private.
iii) Define one static method and return same class reference from it.
class ABC{
private static ABC ab;
private ABC(){
System.out.println(“I am singleton class”);
}
public static ABC getInstance(){
if(ab ==null)
{ ab = new ABC();
}
return ab;
}
}
if we think about above diagram we have class name as ABC with private constructor and in
this class we have one reference name as private static ABC ab; and we have one method
public static ABC getInstance() this method return reference of ABC class and if we think
about main method we have statement ABC a1 = ABC.getInstance() means we call method
ABC.getInstance() using classname because it is a static and in this method contain logic
if(ab == null) so initially a1 is null so this condition is true and if block get executed then
ab = new ABC() is get executed means we created object of ABC class within definition and
when we create object of ABC class then constructor of ABC get executed and we get output
I am constructor and after if block we have statement return ab means we return reference
of ab class to function calling i.e it store in a1 reference after that we have next statement in
main method ABC a2 = ABC.getInstance() means we call getInstance() method second time
but second time ab contain 1000 address not null value so we have logic in getInstance()
method if(ab == null) so this statement get false so new object not created just return ab
reference at function calling means in a2 rerence means we have single object in memory
but we have two references point to same object and so on means here we can say we
created only one object in memory with different references called as Singleton class.
Source with Example
package org.techhub;
class ABC{
private static ABC ab;
private ABC() {
System.out.println("I am constructor");
}
public static ABC getInstance() {
if(ab==null) {
ab = new ABC();
}
return ab;
}
}
public class SingleTonApplication {
public static void main(String[] args) {
ABC a1 = ABC.getInstance();
ABC a2 = ABC.getInstance();
ABC a3 = ABC.getInstance();
}
}
2) What is Utility class: A utility class means class contain private constructor and all
methods must be static called as utility class.
Example of Utility class: java.lang.Math is utility class in java.
How to create user defined Utility class in java
If we want to create utility class in java we have following steps.
i) Declare class constructor as private
ii) Define all methods of class as static
Example:
package org.techhub;
class ABCD
{
private ABCD() {
}
public static void test() {
System.out.println("I am test method from utility class");
}
public static void show() {
System.out.println("I am show method from utility class");
}
}
public class UtilityClassApplication {
public static void main(String[] args) {
ABCD.test();
ABCD.show();
}
}
Inheritance
Inheritance means to transfer property of one class to another class called as inheritance.
Property sender class called as parent class and property receiver class called as child class.
Q. Why use inheritance or what is benefit of inheritance?
There are two major benefits of inheritance.
1) Reusability: Reusability means we can use parent class content without creating its object by
single or multiple child classes
2) Extensibility: Extensibility means child class can acquire property from parent class and can add
own properties in child class
How to perform inheritance in java
If we want to perform inheritance in java we have extends keyword
Syntax:
class parentclassname
{
}
class chilclassname extends parentclassname
{
}
e.g class Value{
int a,b;
void setValue(int x,int y)
{ a=x;
b=y;
}
}
class Add extends Value{
int getAdd(){
return a+b;
}
}
class Mul extends Value{
int getMul(){
return a*b;
}
}
if we think about above code we have three classes name as Value,Add and Mul here Value is parent
class Add and Mul is child classes.
if we think here we can create object of Add and Mul class and we can reuse setValue() function of
Value class using Add and Mul class called as reusability and in Add class we added one extra method
name as getAdd() and return addition of two values from Value class and in Mul class we added one
extra method name as getMul() and we return multiplication of two values called as extensibility
Note: In the case of java we cannot create any program without inheritance
How it is possible?
In java every class has default parent class name as Object class and it is a member of java.lang
package and java.lang is a default package of java means we not need to import it in program.
Example:
class A{
}
Internal meaning
class A extends java.lang.Object{
}
Q. Why Object class is parent of every class in java?
Because Object class contain some methods those required to every class in java
int hashCode()
boolean equals()
String toString()
Object clone()
Class getClass()
void finalize()
void wait()
void wait(int)
void notify()
void notifyAll()
static{
}
Note: in the case of inheritance we not need to create object of parent class we can use parent
content by using child class object shown in following code.
}
}
class B extends A
{ B(){ System.out.println("I am child constructro");
}
}
public class ConsWithInheritenceApp {
public static void main(String[] args) {
B b1 = new B();
}
}
If we think about above code we get compile time error to us because we have A(int x) integer
parameter in parent constructor and we not provide parameter from child constructor so compiler
will generate compile time error to us
So if we want to resolve this problem we have to pass parameter from child class constructor and we
have to use super () constructor in class B constructor because our B is child class.
}
}
}
public class ConsWithInheritenceApp {
public static void main(String[] args) {
B b1 = new B();
}
}
Q. how many ways to perform constructor chaining in java?
There are two ways to perform constructor chaining in java
1) Using this () constructor: normally use this () constructor perform constructor chaining within
same class means in short we can say for perform constructor chaining using this () constructor we
need to use constructor overloading in same class.
2) Using super () constructor: normally super () constructor perform constructor chaining using
inheritance
Final keyword
Final is non access specifier in java which we can use with variable, with function and with class.
Final variable
final variable is used for declare constant values in java means if we declare any variable as final then
we cannot modify its value once we assign it and if we try to modify the value of final variable then
compiler will generate error to us at compile time.
Example with final
package org.techhub;
public class FinalVariableApplication {
public static void main(String[] args) {
final int a=100;
++a;
System.out.println("A is "+a);
}
}
If we think about above code we have statement final int a=100 means initialize variable at a=100 as
constant value using final keyword but we try to modify this value ++a so it is not possible so compiler
will generate compile time error to us.
Note: for setting constant value in program must be use final otherwise not.
Final method
Final method means a method cannot override in child class means final keyword is used for avoid
method overriding in java.
}
If we want to work with method overriding in java we have some important rules
1) In method overriding parent method signature and child method signature must be same
Or must be match
class A
{ void show(){
}
}
class B extends A
{
void show(){
}
}
Means in overriding method return type, function name, argument list and argument type must be
same.
}
}
Above code generate compile time error to us because we define method in as void
show() and we try to change its return type in child class but it is not allowed in
Method overriding so compiler will generate compile time error to us.
Note: if we have same method in parent class and same method in child class with different
parameter or different data type or different parameter sequence then it is consider overloading in
inheritance.
package org.techhub;
class A
{ void show(int x) {
System.out.println("X is "+x);
}
}
class B extends A
{ void show() {
System.out.println("I am show in child"); }
}
public class OverridingRulesApp {
public static void main(String[] args) {
new B().show(10);
}
}
If we think about above code we have two classes name as A and B and in A class contain method
void show (int x) and in B class contain method void show() without parameter means we have
same name method with different parameter sequence or data type called as method overloading
So method overloading may be happen in inheritance using parent and child classes. Q. how we can
call parent logic in method overriding using child object?
If we want to call parent logic using child object in method overriding we have to use super
reference or keyword.
Super is reference in java which is used for call parent logic from child class when child override
method from parent.
Example
class A
{ void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ void show() {
super.show(); //call parent show method
System.out.println("I am show in child");
}
}
public class OverridingRulesApp {
public static void main(String[] args) {
new B().show();
}
}
if we think about above code we have method name void show() and we override in child class name
as B and in class we have statement super.show() means we call parent show() method from child
class using super reference so we get output I am parent show I am show in child.
Example
package org.techhub;
class A
{
final void show() {
System.out.println("I am final");
}
}
class B extends A
{
}
public class OverridingRulesApp {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}
above code generate output to us I am final in above we define final void show() in class A and we
inherit class A in class B and if we think about main method we create object of class B and call
b1.show() using class B reference so show() get call means we can say B class use show() method
from A by using inheritance even show is final so we can say we can inherit final method.
}
@Override
void s3() {
// TODO Auto-generated method stub
}
}
class MNO extends ADP {
void s1() {
System.out.println("I Required s1");
}
}
class PQR extends ADP {
void s2() {
System.out.println("I Required s2");
}
}
public class AdapterApplication {
public static void main(String[] args) {
MNO m = new MNO();
m.s1();
PQR p = new PQR();
p.s2();
}
}
if we think about above code we have two child classes name as MNO and PQR and we one class
name as ADP which contain all blank definition of ABC class so we can say it is adapter class and
MNO and PQR classes accept the methods from ADP class
How to achieve dynamic polymorphism by using abstract class and abstract method
2) Loose Coupling: Loose coupling means if one class function is partially dependent on another class
object called as loose coupling and we can achieve loose coupling by using dynamic polymorphism.
Syntax:
interface interfacename
{
}
Note: interface is internally like as abstract class so we cannot create its object and if we try to
create its object then we get compile time error.
Example:
interface ABC {
}
If we declare any method within interface it is by default abstract means we cannot write logic of
interface method in java.
Example:
interface ABC
{void show (); //public abstract void show();
}
So if we want to work with interface then we have to override interface in any another class and
Override its method and write its logic so if we want to implement interface in any another class we
have implements keyword.
Syntax:
class classname implements interfacename
{ public returntype methodname(arguments){
}
Write here your logics
}
}
Example of interface
package org.techhub;
interface ABC
{ void show();//public abstract void show()
}
class MNO implements ABC
{ public void show() {
System.out.println("I am interface method ");
}
}
public class InterfaceTestApplication {
public static void main(String[] args) {
MNO m = new MNO();
m.show();
}
}
If we want to work with interface we have some important points
interface ABC
{ float PI=3.14f;
void show();//public abstract void show() }
Note: if we think about JDK 1.8 version of java then we can define static method in interface.
Q. if we declare abstract method in class then we can declare it as protected and interface method is
abstract so why we cannot declare interface method as protected if it is abstract?
When we declare abstract method in class then it work with default access specifier by default and if
we declare it as protected then protected can override on default so compiler will accept protected
Example shown in following diagram
But when we declare method in interface then it will use public abstract access specifier by default and
if we declare it as protected then protected not override on public so compiler consider method with
protected public access specifier in java there is public or protected access specifier not protected
public access specifier so compiler will generate error to us at compile time shown in following
diagram.
package org.techhub;
interface ABC
{ abstract void show();
}
class MNO implements ABC
{ public void show() {
System.out.println("I am interface method "); }
}
public class InterfaceTestApplication {
If we think about above code we have ABC is interface and MNO is implementer class of ABC
interface here we created reference of ABC and object of MNO so it is allow
Means here we create reference of interface and object of its implementer class
Abstract Interface
For declare abstract class use abstract keyword For declare interface use interface keyword
Abstract class is used for achive partial Interface can use for 100% abstraction
abstraction
Abstract class variable is not public static and Interface variable is by default public static final
final by default
Abstract may be contain constructor But interface cannot have constructor
We can declare abstract method in abstract class But we cannot declare abstract method in
protected interface as protected
Abstract class need to extends in another class But interface need to implement in another class
Abstract class cannot support for multiple Interface can support for multiple inheritance
inheritance
Abstract can define normal method in it But interface cannot define normal method in its
body but we can define static method in interface
as per jdk 1.8 as well as define default method
also as per jdk 1.8 version
Abstract method is not by default public and But interface method is by default public and
abstract abstract
Abstract class can implement interface But interface cannot inherit abstract class
Q. what are similarities between abstract classes and interface?
1) Both are used for achieve abstraction
2) Both cannot create object
3) Abstract class and interface both used for achieve dynamic polymorphism
4) Abstract class and interface contain abstract methods
5) Abstract method in abstract class and interface cannot declare as final
6) If abstract class contain multiple abstract method then all method must be override
where abstract class get inherited and if interface contain more than one abstract method then all
method must be override
Abstraction Encapsulation
Abstraction achieve by using abstract keyword Encapsulation achieve by using declaring variable
of class as private and access via public setter and
getter methods
Abstraction solve problem at design level Encapsulation solve problem at implementation
level
In abstraction just we provide prototype or Encapsulation we provide implementation of
template of method not its implementation method and hide data from end user or
unauthorized access by declaring data as private
and provide access as per logical level
The major goal of abstraction is achieve dynamic The major goal of encapsulation provide security
polymorphism to user data
Example of abstraction is Vehicle means we can Example of encapsulation suppose consider we
Vehicle contain engine () but we cannot predict are designing login application and if we create
its design just we can provide its prototype and class of verify user login then we can declare its
its implementation is depend on type of vehicle. username and password as private and we can
define one method name as verifyLogin() and we
can check internal login from database it is
example of encapsulation.
Q. what is diff between final and abstract
Final Abstract
Final can use with variable, function and class Abstract can use only with function and class
Final class can create its object Abstract class cannot create its object
Final class is used for achieve immutable objects Abstract class is used for achieve dynamic
polymorphism
Final class cannot inherit in any another class Abstract class must be inherit in any another
class
Final method cannot override means use for Abstract method must be override
avoid method overriding
Final method can have logic Abstract method cannot have logic
Static Abstract
Static can work with variable and method as well Abstract can work with class and methods not
as only work inner class not outer class variable
If we use static keyword with method then we If we use abstract keyword with method then
can access it without using object of class need to call using abstract reference or child
class object
Static method can support to compile time Abstract method can support to dynamic
polymorphism polymorphism
Using static method we can achieve method Using abstract method we can achieve method
hiding overriding
Static method can use only static variable Abstract method can work with static as well as
abstract
Static method must have definition Abstract method not need a definition as well as
static keyword cannot work with abstract method
Wrapper classes : Wrapper classes is used for conversion purpose means it is used for convert primitive
type value to reference type value and reference type value to primitive type value.
There are two types of conversion in java
1) Primitive type conversion: primitive conversion means those conversions perform between simple
data type called as primitive conversion.
There are two types of conversion in java
i) Implicit conversion: implicit conversion means if we compiler is able to perform conversion
automatically called as implicit conversion means when we put larger type value at left hand side and
smaller type value at right hand side then compiler is able to perform conversion automatically called as
implicit conversion.
if we think about above code we have two variables int a=100; and long b; here we have again one
statement b=a; here we store 4byte memory space in 8 byte means here we have smaller type value at
right hand side and larger type value at left hand so here compiler is able to perform conversion
automatically called as implicit conversion.
ii) Explicit conversion: explicit conversion means those conversions perform manually by programmer
called as explicit conversion when we have larger type value at right hand side and smaller type value at
left hand side then compiler is unable to perform automatically in this case programmer need to
perform conversion manually called as explicit conversion
int a;
long b=10;
a=b;
if we think about above code we get compiler time error because we have larger type value b and
smaller type a and we try to store larger type value in smaller type so compiler is unable to perform
conversion because we cannot store larger value in smaller type so in this case programmer need to
perform conversion manually called as explicit conversion shown in following code.
int a;
long b=10;
a=(int)b; //here we convert manually long type to int type.
Following code demonstrate implicit and explicit conversion.
package org.techhub;
public class ConversionApplication {
public static void main(String[] args) {
int a=100;
long b=a; //implicit conversion
System.out.printf("A=%d\tB=%d\n", a,b);
int c;
long d=200;
c=(int)d;//explit conversion
System.out.printf("C=%d\tD=%d\n",c,d);
}
}
implicit and explicit conversion get failed if we try to convert primitive type value to
Reference type and reference type value to primitive type.
Example:
package org.techhub;
public class ConversionApplication {
public static void main(String[] args) {
String s="12345";
int b=(int)s;
System.out.printf("B is %d\n", b);
}
}
If we think about above code we get compile time error because we have String s=”12345”;
Here s is reference of String class and int b is primitive type data and we have statement
int b=(int)s; here we cannot convert reference type value to primitive type directly so compiler generate
compile time error to us
So for resolve this problem java provides some inbuilt classes to us called as Wrapper classes.
So if we want to work with wrapper classes we have following diagram.
Some time auto boxing and auto un boxing get failed as well as auto unboxing if we have
Different type of primitive and different type of reference then auto boxing and auto unboxing
get failed.
package org.techhub;
public class TestWrapperApp {
public static void main(String[] args) {
Float a=5.4f;
int b=a;
}
}
if we think about above code we get compile time error because we have Float a=5.4f and we have
statement int b=a;// here we store reference float in primitive type of integer so it not converted
automaticlally
so if we want to solve this problem Number class provide some inbuilt method to us called as
xxxValue()
Note: Number is abstract class in java and it inherit in all numeric classes mention in above diagram
int intValue(): this is used for convert any reference value in to primitive type of integer
package org.techhub;
public class TestWrapperApp {
public static void main(String[] args) {
Float a=5.4f;
int b=a.intValue();
System.out.println("B is "+b);
}
}
float floatValue() : this method is used for convert any reference value to primitive type of float
package org.techhub;
public class TestWrapperApp {
public static void main(String[] args) {
Double d=5.4;
float b=d.floatValue();
System.out.println("B is "+b);
}
}
package org.techhub;
public class TestWrapperApp {
public static void main(String[] args) {
Float f=5.3f;
long d=f.longValue();
System.out.println("D is "+d);
}
}
package org.techhub;
public class TestWrapperApp {
public static void main(String[] args) {
String str="1234";
int b=Integer.parseInt(str);
System.out.println("B is "+b);
}
}
String toString(): this method is used for convert any object to the string.
package org.techhub;
public class TestWrapperApp {
public static void main(String[] args) {
Integer a=1000;
String s=a.toString();
System.out.println(s);
}
}
String, StringBuffer and StringBuilder
String: String is immutable class of java immutable means once we initialize value never change
Later called as immutable
Q. what is diff between String creation using initialization technique and using a new keyword?
If we create string using initialization technique then JVM create string object in string pool
Constant means if we have two strings with same value then JVM create only one object in memory
And use same object address in multiple references
If we create string using a new keyword if your string values same then JVM create new object every
time.
Shown in following diagram.
if we think about above code we have two object String s=”abc”; and String s1=”abc”;if we create
objects of string by using a initialization technique then JVM create single object in string pool constant
and store its reference in two different variables and when we create object by using a new keyword
then JVM create new object every time if your value is same.
String s="abc";
String s1="abc";
System.out.println("Address of First object is "+System.identityHashCode(s));
System.out.println("Address of Second object is "+System.identityHashCode(s1));
Output:
Address of First object is 123961122
Address of Second object is 123961122
if we think about above code we have two reference s and s1 and we print hashcode of both objects
and we found same hashcode of both objects so we can say s and s1 use same memory space.
Output:
Address of First object is 123961122
Address of Second object is 942731712
If we think about above code we found different hash code of s and s1 but we have same values of s and
s1 so we can say internally in memory we two different objects.
What is heap?
The heap memory is a run time data area from which the memory for all java class instance and arrays
are allocated. Heap is created when JVM startup and we can increase size of heap as well as decrease
size of heap which application is running.
If we want to work with a String we have some inbuilt constructor provided by string to us.
String (): this constructor is used for create new string with null value.
Example:
String (String): here user can create string with some default value provided by user at the time object
creation
public class StringHandlngApplication {
static String s=new String("Good");
public static void main(String[] args) {
System.out.println(s);
}
}
String(char[]): this constructor is used for convert primitive type of character array in to string.
package org.techhub;
public class StringHandlngApplication {
public static void main(String[] args) {
char ch[]= {'a','b','c','d','e'};
String s = new String(ch); //here we accept character array as parameter and convert in string object.
System.out.println(s);
}
}
if we want to work with string we have some inbuilt methods provided by String class to us
package org.techhub;
public class StringHandlngApplication {
public static void main(String[] args) {
String s="good";
int len=s.length();
System.out.println("Length of string is "+len);
}
}
char charAt(int index): this method accept integer value as parameter and return character means this
method can accept index of character and return its value.
Show in following diagram.
package org.techhub;
public class StringHandlngApplication {
public static void main(String[] args) {
String s="good";
int len=s.length();
for(int i=0; i<len;i++) {
char ch=s.charAt(i);
System.out.println("ch["+i+"]"+" --------- >"+ch);
}
}
}
String toUpperCase(): this method is used for convert lower case string to upper case.
package org.techhub;
public class StringHandlngApplication {
public static void main(String[] args) {
String s="good";
System.out.println("Before convert "+s);
s.toUpperCase();
System.out.println("After convert "+s);
}
}
Output:
Before convert good
After convert good
if we think about above code we use toUpperCase() method but string not converted in upper case
because we use statement s.toUpperCase() here string s is cannot modify its value and toUpperCase()
return new string value at its left hand side as new object we so need to catch in external string variable
means if we perform any operation string we need to store in new variable at left hand side as resultant
output.
int indexOf(String): this method is used for search specified text or string or some portion of string if
data found return its index and if data not found return -1
Example: suppose consider we have String=”good morning india” and we want to find morning from a
string then we can use indexOf() method.
package org.techhub;
public class ConcatApplication {
public static void main(String[] args) {
String str="good morning india";
int index=str.indexOf("morning");
if(index!=-1) {
System.out.println("String found");
}
else { System.out.println("String not found");
}
}
}
String substring(int startIndex,int endIndex): this method is used for extract some specified portion of
string.
Example: suppose consider we have string str=”good morning india”;
and we want to extract morning text from string.
package org.techhub;
public class ConcatApplication {
public static void main(String[] args) {
String str="good morning india";
String s1=str.substring(5, 12);
//here 5 is starting index and 12 is ending index.
System.out.println(s1);
}
}
String [] split (String text): this method is used for split string using a some specified character and return
data string array.
Example: suppose consider we have string str=”good morning india good afternoon india and good
evening india”;
so we want to separate every word from a string as well as we want to calculate the total number of
word in string so if we want to achieve this task we need to separate words using space because if we
found space then we consider end of words shown in following diagram and code.
boolean endsWith(String): this method is used for check particular string ends with specified character
or not if ends with specified character return true otherwise return false.
Example: suppose we have string good morning india good afternoon india good evening india
count the number of words ends with ing and remove ind from that words and print final string after
removing ing
Input : String s=”good morning good afternoon india good evening india”;
Oupput: String s=”good morn good afternoon india good even india”;
package org.techhub;
import java.util.*;
public class ConcatApplication {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
String str="good morning india good afternoon india good evening india";
String words[]=str.split(" ");
String newWord="";
for(String s:words) {
boolean b=s.endsWith("ing");
if(b) {
s=s.substring(0,(s.length()-3));
}
al.add(s);
}
str="";
for(String s:al) {
str=str+s+" ";
}
System.out.println(str);
}
}
String trim(): this method is used for remove white spaces at beginning of string and at ending of string.
package org.techhub;
}
}
How to remove middle space?
package org.techhub;
public class ConcatApplication {
public static void main(String[] args) {
String s="good morning india";
s="";
for(String s1:s.split(" "))
s=s+s1;
System.out.println(s);
}
}
Assignments:
a) WAP to input string from keyboard and find duplicated words in string
String s=”abc mno pqr abc”;
Output : abc --- 2
Note: use LinkedHashMap here and mark word as key and count as value and extract key and value
from LinkedHashMap and compare value with 1 means if value is greater than 1 so print its key so we
can found duplicated words.
b) WAP to input string and remove stop words and display string after removing stop words and show
the count how many stopwords remove from a string .
Example of stop words is , are, my , but ,could , can etc search list on google
3) WAP to input string from keyboard and find its permutation using recursion
abc = 1 x 2 x 3 = 6
Output:
abc
bca
cba
bac
acb
cab
3) finally: finally is block in java which always execute if exception generate in program or not
Syntax of finally block
try{
write here your logics in which exception may be occur
}
finally{
write here logic which want to execute always
}
or
try{
write here your logics in which exception may be occur
}
catch(exceptiontype ref)
{
}
finally{
write here logic which want to execute always
}
try{
write here your logics in which exception may be occur
}
finally{
write here logic which want to execute always
}
4) throw: throw keyword is used for handle user defined exceptions in java and we can use throw
with function
5) throws: throws is also keyword for handle checked exceptions and we can use it with function
also.
Example: Now we want to handle ArithmeticException using
import java.util.*;
public class DivNovApp
{
public static void main(String x[])
{ Scanner xyz = new Scanner(System.in);
int a,b,c;
System.out.println("Enter two values");
a=xyz.nextInt();
b=xyz.nextInt();
c=a/b;
System.out.printf("Division is %d\n",c);
System.out.println("Logic1");
System.out.println("Logic2");
}
}
Example
if we think about above code we get run time error i.e ArithmeticException because we have
statement c=a/b and we provide input as a=9 and b=0 so the statement c=a/b is like as c=9/0 and if
we divide any number by 0 it is consider as infinity and system cannot calculate infinity so JVM
generate run time exception to us
So we want to resolve this problem we need to handle exception using try and catch block
Means as per this exception we need to c=a/b statement within try block and need to handle
ArithmeticException in catch block shown in following diagram and code
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
int a[] =new int[2];
a[2]=200;
System.out.println("Value is "+a[2]);
}
}
If we think about above code we created array of size 2 int a [] =new int [2]
means we have only two index in array i.e 0 & 1 but if we think about statement a[2]=200 means
we try to store value on 2nd index but which is not present in array so JVM generate run time error to
us ArrayIndexOutOfBoundsException to us.
So if we want to handle this exception at run time in code then we have to write a[2]=200 in try
block and ArrayIndexOutOfBounds in catch block shown in following code.
Source code
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try {
int a[] = new int[2];
a[2] = 200;
System.out.println("Value is " + a[2]);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Error is " + ex);
}
}
}
Example: NullPointerException
Normally NullPointerException generated by JVM when we try to use any reference without
memory allocation or without new keyword then JVM generate NullPointerException so it may array
reference or it may be object reference etc.
Example
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
static int a[];
public static void main(String[] args) {
try {
a[2] = 200;
System.out.println("Value is " + a[2]);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Error is " + ex);
}
}
}
if we think about above code it will generate NullPointerException to us because we have statement
int a[] means here we declare array variable but we not allocate its memory and we try to use
without new keyword a[2]=200 so without new we cannot use any array or object in java so JVM
generate NullPointerException to us
if we want to handle this problem we need to handle NullPointerException or use new keyword.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
static int a[];
public static void main(String[] args) {
try {
a[2] = 200;
System.out.println("Value is " + a[2]);
} catch (NullPointerException ex) {
System.out.println("Error is " + ex);
}
}
}
We have one more example of NullPointerException
package org.techhub;
import java.util.*;
class Test
{ void show()
{ System.out.println("I am show method");
}
}
public class ArrayExceptionApp {
static Test t;
public static void main(String[] args) {
t.show();
}
}
if we think about above code we have reference name as static Test t and we not initialize any object
address in it so it is by default null and we have statement t.show() so it is not possible if we want to
use any class member we must have object we cannot using reference without object so JVM
generate NullPointerException if we want to avoid this problem we have use try and catch block and
handle NullPointerException
package org.techhub;
import java.util.*;
class Test
{ void show()
{ System.out.println("I am show method");
}
}
public class ArrayExceptionApp {
static Test t;
public static void main(String[] args) {
try {
t.show();
}
catch(NullPointerException ex) {
System.out.println("Error is "+ex);
}
}
}
Example: NumberFormatException
Normally NumberFormatException occur when we try to convert string to value primitive type of
value
Some time if we try to convert string value to integer but if there is some space or if there any
another non numeric value in string then conversion is not possible so your JVM generate
NumberFormatException at run time.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
String s="12345 "; //12345 is integer but format is string because in ""
int a=Integer.parseInt(s);
System.out.println("A is "+a);
}
}
if we think about above code we have String s=”12345 “; string contain space and we have
statement int a=Integer.parseInt(s) here 12345 can convert by JVM from string to integer but space
cannot convert by JVM in to integer so we get NumberFormatException at run time so if we want to
avoid this problem we have to handle NumberFormatException shown in following code.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
String s="12345 "; //12345 is integer but format is string because in ""
try {
int a=Integer.parseInt(s);
System.out.println("A is "+a);
}
catch(NumberFormatException ex) {
System.out.println("There is conversion problem ");
}
}
}
Example: InputMismatchException
InputMismatchException occur when user except specific type of input but provide different type
then JVM generate InputMismatchException at run time.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
int a,b;
System.out.println("Enter two values");
Scanner xyz = new Scanner(System.in);
a=xyz.nextInt();
b=xyz.nextInt();
System.out.printf("A=%d\tB=%d\n",a,b);
}
}
Example:
Enter two values
10.4
Exception in thread "main" java.util.InputMismatchException
for avoid this problem we have tho handle InputMismatchException.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
int a,b;
try {
System.out.println("Enter two values");
Scanner xyz = new Scanner(System.in);
a=xyz.nextInt();
b=xyz.nextInt();
System.out.printf("A=%d\tB=%d\n",a,b);
}
catch(InputMismatchException ex)
{
System.out.println("Error is "+ex);
}
}
}
Note: if we write only Exception in catch block then JVM can handle any type of exception.
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try {
//write here any logic JVM can handle any exception
int a,b,c;
Scanner xyz = new Scanner(System.in);
System.out.println("Enter two values");
a=xyz.nextInt();
b=xyz.nextInt();
c=a/b;
System.out.println("Division is "+c);
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
Note: because Exception is a parent of all exception classes in java as per the rule of loose coupling
we can say if we pass reference of parent you can pass any child reference so it is possible we can
manage more than one exception by single catch block with help of Exception class.
}
}
}
if we think about above code we get compile time error because we have two catch block with single
try block and in first catch block we use Exception class as parameter means catch(Exception ex) and
in second catch block we use catch(ArithmeticException ex) but if we use Exception then we can
handle any kind of exception like as ArithmeticException, InputMismatchException etc so we not
need to handle it separately so after catch(Exception ex) write any catch block with another
exception class is meaningless so compiler will generate compile time error to us
Note: In JDK 1.7 version of java there some enhancement in exception means java added two new
concepts in exception.
Example without Catch using multiple exception class with single reference
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try {
// write here any logic JVM can handle any exception
int a, b, c;
Scanner xyz = new Scanner(System.in);
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
} catch (ArithmeticException ex) {
System.out.println("Error is "+ex);
}
catch(InputMismatchException ex) {
System.out.println("Error is "+ex);
}
}
}
If we think about above code we handle two exceptions ArithmeticException and
InputMismatchException but for that we need to write two separate catch blocks but when we want
to 10 different type of exception separately then we need to write 10 different catch block and it is
not feasible in real time so java suggest you can handle multiple exception by single catch block and
for that we have to use catch with multiple classes using single reference shown in following code
Example
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try {
// write here any logic JVM can handle any exception
int a, b, c;
Scanner xyz = new Scanner(System.in);
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
} catch (ArithmeticException | InputMismatchException |
ArrayIndexOutOfBoundsException ex) {
System.out.println("Error is "+ex);
}
}
}
2) Try with resource bundle
Try with resource bundle means we directly pass reference as parameter to try block or we direct
create object in try block means here try block work like as function parameter or function calling
point.
Syntax:
try(object)
{
}
catch(exceptiontype ref)
{
}
Source code with example
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try (Scanner xyz = new Scanner(System.in)) {
// write here any logic JVM can handle any exception
int a, b, c;
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
} catch (ArithmeticException | InputMismatchException |
ArrayIndexOutOfBoundsException ex) {
System.out.println("Error is " + ex);
}
}
}
Finally block
finally is block in java which always execute if exception generate in program or not Normally finally
block use by developer to writing code which is necessary to execute in any situation like database
connection close , file close etc
Note: finally can work with try as well as finally can work with try and catch
Example: try with finally without catch
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try (Scanner xyz = new Scanner(System.in)) {
// write here any logic JVM can handle any exception
int a, b, c;
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
}
finally {
System.out.println("I can execute always");
}
System.out.println("Logic1");
System.out.println("Logic2");
System.out.println("Logic3");
}
}
Example: try with finally with catch block
package org.techhub;
import java.util.*;
public class ArrayExceptionApp {
public static void main(String[] args) {
try (Scanner xyz = new Scanner(System.in)) {
// write here any logic JVM can handle any exception
int a, b, c;
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
finally {
System.out.println("I can execute always");
}
System.out.println("Logic1");
System.out.println("Logic2");
System.out.println("Logic3");
}
}
Q. what is diff between catch and finally?
Finally Catch
Finally block not need parameter Catch block required parameter
Finally always if exception generate by try or not Catch block always execute when exception
generate in try block
Using finally we cannot handle exception in Using catch we can handle exception in program
program just execute code which essential to and execute remaining application
execute in any situation.
If we use try without catch and if exception But if we use try with catch and finally then catch
generate in program then finally get before block execute before finally block
exception
package org.techhub;
import java.util.*;
class VoterException extends ArithmeticException
{
public String getVoterError() {
return "invalid voter you are not eligible";
}
}
class ValidateVoter
{
void verifyVoter(String adhar, int birthYear) {
int age=2023-birthYear;
if(age<18) {
VoterException v = new VoterException();
throw v;
}
else {
System.out.println("Welcome");
}
}
}
public class VotingApplication {
Throws Throw
Use for handle checked exception User for handle user defined exceptions
Not need to create explicitly object of exception Need to create explicitly of object exception and
class and throw it internally JVM create object throw it manually
and throw at function calling point
Throws can work with multiple exception at time Throw cannot work with multiple exception at
time
}
}
}
above code generate compile time error to us because we use throw with non exception class. you
can only use throw with exception class or exception child class not other
}
}
}
If we think about above code there is any compile time error it will execute properly because we can
use exception class with throw class and if we use Exception in catch block then we can handle any
kind of exception.
Q. what will be output of given code?
package org.techhub;
public class TestThrow {
public static void main(String[] args) {
try
{
throw new ArithmeticException();
}
catch(InputMismatchException e) {
}
}
}
this code not handle ArithmeticException at run time because we handle InputMismatchException
and throw ArithmeticException
import java.util.InputMismatchException;
}
}
}
Above code execute properly and handle exceptions
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws SQLException
{
}
}
public class TestThrow {
public static void main(String[] args) {
Test t = new Test();
t.getConn();
}
}
Above code will generate compile time error to us because we handle SQLException with getConn()
method at function definition and SQLException is checked category exception so when we use any
checked exception at with function definition then we must be handle exception at function calling
point means we must be write try and catch at function calling point so we not use try and catch at
function calling point means we not handle exception so compiler will generate compile time error
to us so if we want to remove this error write try and catch at function calling point shown in
following code.
package org.techhub;
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws SQLException
{
}
}
public class TestThrow {
public static void main(String[] args) {
try {
Test t = new Test();
t.getConn();
}catch(SQLException ex) {
}
}
}
Q.what will be output of given code?
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws Exception {
}
}
class ABC extends Test
{ void getConn() throws Throwable{
}
}
above code will generate compile time error to us because we handle Exception with getConn()
method in Test class and Test is parent of ABC class and in ABC class we again override getConn()
method and handle Throwable class so it is not possible means in the case of override if we handle
child class in parent and try to handle parent in child then it is not possible
but if we handle parent exception class in parent method and override same method in child and
handle child exception class it is possible but we need to handle parent exception where we call
function.
Shown in Following Code
package org.techhub;
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws Throwable {
}
}
class ABC extends Test
{ void getConn() throws Exception{
}
}
public class TestThrow {
public static void main(String[] args) {
try {
Test t = new Test();
t.getConn();
}
catch(Throwable ex) {
}
}
}
Q. what will be output of given code?
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn() {
}
}
class ABC extends Test
{ void getConn() throws Exception{
}
}
if we think about above code we get compile time error to us because we not handle exception in
parent class and we override same method in child class try to handle exception so it is not allowed
so compiler generate error to us if we want to remove this we need to handle exception parent
method or remove exception with child method shown in following code.
import java.util.InputMismatchException;
import java.sql.*;
class Test
{ void getConn()throws Exception {
}
}
class ABC extends Test
{ void getConn() throws Exception{
}
}
Collection is ready made implementation of data structure provided by java to us the major goal
of collections
1) Provide ready implementation of data structure
2) Ability to store any type of data
3) Ability to store unlimited data
4) Ability to store manages size at run time means can grow size at run time as well as can shrink size
at run time.
if we think about java we can create array with a different type of value because in java we have
Object class and if we create array of Object class then we can store different type of data in it.
Example
package org.techhub;
import java.util.*;
public class ArrayWithDifferentTypeApp {
public static void main(String[] args) {
Object obj[] = new Object[5];
obj[0]=100;
obj[1]=false;
obj[2]=new java.util.Date();
obj[3]=5.4f;
obj[4]="good";
for(int i=0; i<obj.length;i++){
System.out.println(obj[i]);
}
}
}
If we think about above code we have Object class array and we store different type of data in it
It is benefit of Object class array
but the major limitation is if we want to perform any data structure operation like as sorting ,
searching ,deletion of element ,insertion of element etc then we need to write manual logic to
developer so java provide suggest use collection to writing manual logic of data structure and for
that purpose java provide some inbuilt interfaces and classes to us called as Collection API or
collection Framework.
If we want to work with collection we have following diagram
If we think about above diagram we have top most interface name as java.lang.Iterable.
boolean hasNext(): this method is used for check element present in collection or not if present
return true otherwise return false.
Object next(): this method is used for fetch data from collection and move cursor on next element.
void remove(): this method can remove element from collection at the time of data fetching.
if we think about above code we created object of ArrayList class and we store three values in it
using add() method like as 10 20 30 after that we have statement Iterator i =al.iterator() so this
method create reference of Iterator interface and points to ArrayList collection and after that we
have statement while(i.hasNext()) this method check element present in collection or not means as
per our example first we found 10 value in collection so i.hasNext() method return true value and
control move in loop and after that i.next() method fetch data from collection i.e 10 and move
cursor on next element as per our example i.e on 20 again while loop get executed and check
i.hasNext() again we found 20 so condition is true and so on i.hasNext() method return false when
element not found in collection so we can say Iterable interface provide iterator() method for fetch
data from collection.
After Iterable interface we have one more interface java.util.Collection and it is child of
java.lang.Iterable.
java.util.Collection interface contain some inbuilt methods which is used for perform common data
structure operation like as add data in collection , remove data from collection , search data in
collection , check collection is empty or not ,return size of collection etc
if we think about above code we have ArrayList and we store 4 values in it 10 20 30 40 and we
have statement int s = al.size(); this return count of number of element present in collection i.e 4
public abstract boolean isEmpty(): this method check collection is empty or not if empty return
true otherwise return false.
if we think about above code we have ArrayList with three values 100 200 300 and we have
statement boolean b = al.isEmpty() this method check element present in collection or not so as
per example ArrayList is not empty so this method return false value in variable b and again we have
statement if(b) so this statement get false so we get answer ArrayList is not empty.
public abstract boolean contains(java.lang.Object): this method is used for search element from
collection means using this method we can check element present in collection or not if present
return true otherwise return false.
above generate output value present in collection in above code we have ArrayList with value 100
200 300 and we have statement boolean b= al.contains(200) so in our ArrayList 200 present so this
method return true value in variable b and we pass if(b) we have if(true) so we get value present in
collection.
public abstract java.util.Iterator<E> iterator(): this is used for fetch data from collection
public abstract java.lang.Object[] toArray() : this method can convert collection in to Object class
array
public abstract boolean remove(java.lang.Object): this method can remove data from collection
and if data remove successfully return true otherwise return false.
public abstract boolean containsAll(java.util.Collection<?>): this method search multiple values
present in collection or not if present return true otherwise return false
if we think about above code we have containsAll() method and we pass reference variable s in
containsAll() method means in s variable contain values 20 and 30 and when we pass variable s in
ArrayList means we want to search 20 or 30 ArrayList if we found any value return true otherwise
return false.
public abstract boolean addAll(java.util.Collection<? extends E>): this method is used for add
more than one values at time in collection.
public abstract void clear (): this method help us to remove all elements from collection
1) List: List Collection is used for store any type of data in collection but allows duplicated data and
manages your data by using index.
2) Set: Set collection is used for store only unique data in collection means not allow duplicated data
and manage data by using hashing technique as well as it help us to generate random data also.
3) Queue: Queue collection is used for store duplicated and manage using index as well as manage
using first in first out format.
public abstract E get(int): this method can return data from collection using its index and if index
not found return ArrayIndexOutOfBoundsException at run time.
Example:
public abstract E set(int, E): this method is used for replace on specified index in List Collection
if we think about above code we have statement al.set(2,300) means we want to replace value on
2nd index of ArrayList i.e we want to replace 300 on 2nd index of ArrayList means it is override on
previous value
public abstract void add(int, E): this method is used for insert value on specified index in ArrayList
and shift index by 1 like as array insertion program.
Example:
public abstract E remove(int): this method help us remove element from collection using particular
index and shift remaining index at left side of Collection and remove last unwanted block and return
removed value at left hand side for user confirmation
public abstract int indexOf(java.lang.Object): this method return index of particular element from
list collection and if element not present in list collection it will return -1
Normally this method refer for two purposes
1) Using this method you can search element from collection :
Now we want to see example search element from collection
when indexOf() method return -1 value to us then we can consider element not present in list
collection
Here above code generate output data not found because we have ArrayList with four elements 10
20 30 40 and we have statement al.indexOf (200) so in our ArrayList there is no 200 value present so
this method return -1 in index and we have statement if(index!=-1) means if(-1!=-1) so it is false
condition so else get executed and print output data not found.
public abstract java.util.ListIterator<E> listIterator(int): this method is used for fetch data in
forward direction as well as in backward direction.
public abstract java.util.List<E> subList(int, int): this method help us to extract some specified
portion of List collection Some time we need to create separate list from large list or fetch some sub
section of list collection then we can use subList()
subList() method required two index means it require starting index and ending index means
between
These two indexes we can fetch data from collection.
if we think about above collection we create small list between index 2 to 6 and store its address in
reference of l
Now we want to discuss about implementer classes of List Collection
1) Vector: Vector is legacy collection in java as well as thread safe collection means all methods of
vector are synchronized.
Q. what is legacy collection?
Legacy collection means those collection classes present in java but later version of java they are
added as part of collection
Example: if we think about vector so Vector is known as dynamic array before jdk 1.2 version of java
but from JDK 1.2 version of it is added as part of Collection so we can say it is legacy collection.
Vector (): this constructor is used for create vector with default capacity provided by java to us.
The default capacity of Vector is 10 means when we create object of Vector using this constructor
then internally java create array of Object class of size 10
If we see the capacity of Vector we have int capacity () method of Vector
Vector(int initialCapacity): this constructor help us to create vector with initial capacity as per user
choice.
package org.techhub;
import java.util.*;
public class VectorTestApplication {
public static void main(String[] args) {
Vector v = new Vector(5);
int capacity = v.capacity();
System.out.println("Initial capacity is "+capacity);
}
}
Vector (int initialCapacity, int incrementalCapacity): if we think about constructor we have two
parameters
int initialCapacity: this parameter is used for set initial capacity of Vector
int incrementalCapacity: this parameter decides the incremental capacity of vector.
Note: if we think about vector then vector allocate double memory than its current capacity but if
user want to set incremental capacity of vector as per his choice then user can use this constructor
and pass second parameter as incremental capacity of Vector.
package org.techhub;
import java.util.*;
public class VectorTestApplication {
public static void main(String[] args) {
Vector v = new Vector(5,2); //5 ,7 ,9,11,1
int capacity = v.capacity();
System.out.println("Initial capacity is "+capacity);
v.add(10);
v.add(20);
v.add(10);
v.add(20);
v.add(10);
v.add(20);
v.add(10);
v.add(20);
v.add(10);
v.add(20);
v.add(10);
v.add(20);
System.out.println("Now current capacity is "+v.capacity());
}
}
If we think about above code we use vector constructor Vector v = new Vector (5,2) here we have
initial capacity is 5 and incremental capacity is 2 means when user cross current capacity then every
time it will increase by 2 block.
Vector(Collection): this constructor is used for copy content from another collection in Vector
collection.
import java.util.*;
public class VectorTestApplication {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);
al.add(20);
al.add(30);
Vector v = new Vector(al);//Collection
System.out.println(v);
}
}
If we think about above code we copy content from ArrayList collection in to Vector
Example: we want to create program using Vector we want to store 5 values in Vector and display it.
package org.techhub;
import java.util.*;
public class VectorTestApplication {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
v.add(40);
Iterator i = v.iterator();
while(i.hasNext()) {
Object obj = i.next();
System.out.println(obj);
}
}
}
Example: WAP to store 5 values in Vector and calculate sum of all elements.
package org.techhub;
import java.util.*;
public class VectorTestApplication {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
v.add(40);
int len = v.size();
int sum=0;
for(int i=0; i<len; i++) {
Object obj = v.get(i);
sum = sum + obj;
}
System.out.println("Sum of all element is "+sum);
}
}
if we think about above code we get compile time error with statement sum = sum+ obj;
here obj is variable of Object class
Note: if we think about Object class it can store any type of data in it but we cannot perform any
operation on Object class like as addition, subtraction, comparison etc so if we want to perform any
operation on Object class we must be in its original type
when we think about collection then collection store every data in the form of Object class and
retrieve every data in the form of Object class so when we want to perform any operation with
Collection element then we need to convert it in original format.
Example we have code in above program
Vector v = new Vector();
v.add(10); here 10 work as Object so get() method return it as object but its original type is integer
so when we want to peform addition of all elements in Vector as per our example then we need to
convert obj variable in to integer type shown in following code
sum = sum +(int)obj;
shown in following code and diagram
Example without error
package org.techhub;
import java.util.*;
public class VectorTestApplication {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add(30);
v.add(40);
int len = v.size();
int sum=0;
for(int i=0; i<len; i++) {
Object obj = v.get(i);
sum = sum + (int)obj;
}
System.out.println("Sum of all element is "+sum);
}
}
Diagram of above code.
if we think about above diagram we have Vector but it is internally manage by using index and index
start from 0 so if we think statement int len =v.size() so this method return 4 value and if we think
about for loop for(int i=0; i<len; i++) { Object obj=v.get(i); sum=sum+(int)obj; } here initially i=0 i<4
this condition is true so we have statement v.get(i) means v.get(0) so this method return data from
0th index i.e 10 and then we statement sum = sum+(int)obj means sum=sum+10 and so on.
Example: WAP to store five values in Vector and find maximum value.
package org.techhub;
import java.util.*;
public class VectorTestApplication {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(2);
v.add(300);
v.add(40);
int len = v.size();
int max=(int)v.get(0);
for(int i=0; i<len; i++) {
Object obj = v.get(i);
if((int)obj>max) {
max=(int)obj;
}
}
System.out.println("Maximum value is "+max);
}
}
Example: WAP to store 5 values in Vector and arrange in ascending order.
Example
package org.techhub;
import java.util.*;
public class VectorApp {
public static void main(String[] args) {
Vector v = new Vector();
v.add(5);
v.add(3);
v.add(4);
v.add(1);
v.add(2);
System.out.println("Before Sorting");
System.out.println(v);//before sorting
for(int i=0; i<v.size();i++) {
for(int j=(i+1); j<v.size();j++) {
Object prev=v.get(i);
Object next=v.get(j);
if((int)prev>(int)next) {
v.set(i, next);
v.set(j, prev);
}
}
}
System.out.println("After Sorting");
System.out.println(v);
}
}
if we think about above code we have Vector with three values i.e 10 20 30 and we have one
statement name as Enumeration enm = v.elements() when we call this method then we get
reference of Enumeration and this reference points Vector in our example and after that we have
statement if(enm.hasMoreElements()) this method check element present in collection or not if
present return true so first it will check 10 value we found so this method return true so control
enter in loop and fetch 10 from collection and move cursor on next element i.e on 20 so loop will
execute when ever your data present in collection when your data not present in collection then it
will return false
2) Fetch Data using Iterator: Iterator can work with legacy as well as non legacy collection and this
method cursor can fetch data from collection as well as can remove data from collection at the time
of data fetching.
if we want to get reference of Iterator interface we have method iterator() and it is member of
java.lang.Iterable interface and return reference of Iterable interface
Enumeration Iterator
Work with legacy collection only Work with legacy as well as non legacy collection
Use for only fetch data from collection Can fetch and remove data form collection at
time to fetching
Methods of Enumeration boolean Methods of Iterator boolean hasNext() , next()
hasMoreElements() ,nextElement()
3) Fetch data using ListIterator: ListIterator is used for fetch data from collection in forward
direction as well as in backward direction.
If we want to create reference of ListIterator we have listIterator() method of List Collection
Syntax: ListIterator listIterator (int index): this method can fetch data from forward or backward
using some specified index.
if we think about diagram we have Vector with five values 5 3 4 1 2 and we have statement
ListIterator li=v.listIterator(v.size()); here li points to lastindex+1 after that we have statement
while(li.hasPrevious()) this method decrease pointer on previous element and check element
present on index or not if present return true and fetch data from collection and move index in
backward direction and so on.
Source code with example
package org.techhub;
import java.util.*;
public class VectorApp {
public static void main(String[] args) {
Vector v = new Vector();
v.add(5);
v.add(3);
v.add(4);
v.add(1);
v.add(2);
ListIterator li = v.listIterator(v.size());
while(li.hasPrevious()) {
Object obj = li.previous();
System.out.println(obj);
}
}
Output:
2
1
4
3
5
Q. what is diff between ListIterator and Iterator?
Iterator ListIterator
Iterator can fetch data only in forward direction ListIterator can fetch data in forward direction
as well as in backward direction
Iterator can only remove data from Collection ListIterator can add , remove , replace data in
collection at the time to traversing
Iterator can fetch data from any collection like as ListIterator can only work with List Collection
List,Set,Map etc
Iterator cannot return index of element ListIterator can return index of element with the
help of int previousIndex() and int nextIndex()
Iterator cannot add or modify collection if we try ListIterator can easily modify or add element
to modify it then it will generate using corresponding methods
ConcurrentModificationException at run time
Method of Iterator boolean hasNext(),Object Methods of ListIterator boolean
next() and void remove() hasPrevious(),Object previous(),boolean
hasNext(),Object next(),void add(E),void
set(E),void remove()
Note:ListIterator is internally child of Iterator interface means ListIterator get three methods from
Iterator i.e hasNext(),next() and remove();
4) Fetch data using for loop: using for loop we can fetch data from collection but using for loop we
can easily fetch data of list collection only.
package org.techhub;
import java.util.*;
public class VectorApp {
public static void main(String[] args) {
Vector v = new Vector();
v.add(5);
v.add(3);
v.add(4);
v.add(1);
v.add(2);
int len = v.size();
for(int i=0; i<len; i++) {
Object obj = v.get(i);
System.out.println(obj);
}
}
}
Note: normally try to avoid use for loop for fetch data from collection because it will take more time
of data fetching because internally every time two conditions get execute i.e condition and
increment and it will take more time comparision in CPU so avoid use for loop
5) Fetch data using for each
Syntax: for(data type value: array or collection)
{
}
For each specially design for fetch data from collection or array
import java.util.*;
public class VectorApp {
public static void main(String[] args) {
Vector v = new Vector();
v.add(5);
v.add(3);
v.add(4);
v.add(1);
v.add(2);
for(Object obj:v) {
System.out.println(obj);
}
}
}
Example: WAP to store 5 value in Vector and input value from keyboard and search value in Vector if
value found return true otherwise return false.
package org.techhub;
import java.util.*;
public class SearchValueApp {
public static void main(String[] args) {
Vector v = new Vector();
System.out.println("Enter value in collection");
Scanner xyz = new Scanner(System.in);
do {
int value=xyz.nextInt();
v.add(value);
xyz.nextLine();
System.out.println("Do you want to stop");
String msg=xyz.nextLine();
if(msg.equals("yes"))
{ break;
}
}while(true);
System.out.println("Enter data for search");
int data =xyz.nextInt();
boolean b = v.contains(data);
if(b)//if(true)
{ System.out.println("Data found");
}
else { System.out.println("data not found");
}
}
}
if we think about above code we created Vector object Vector v = new Vector()
and we have do loop where we condition while(true) this condition indicate we want to execute
loop infinite time and in loop we input data from keyboard and store in vector using add() method
and again we check condition do you want to stop means if user want to stop inserting value in
collection then he can type yes as input otherwise no and store unlimited data in collection and if
user type or provide input as yes then loop will break and after loop we ask user to enter data for
search and user can input any value from keyboard and we pass that value as parameter to
contains() method if value found in collection then this method return true if not found in collection
the contains() method return false in variable b and we pass that variable in if() condition as if(b)
means when we found value in then b pass true in if() block and system display output value found if
not found value then b pass if() false in collection and system generate value not found in collection.
Example: Create vector and store values in it and search value in Vector using indexOf() method?
Note : Note you can search data from Vector using indexOf() method means when we pass any value
in indexOf() then this method return its index if value present in collection and if value not present in
collection return -1 means we can predict or we can consider data present in collection or not
return value by indexOf() means when we get -1 we consider not present otherwise present.
Example: WAP to create Vector and store values in it and input value from keyboard and delete or
remove value from keyboard.
package org.techhub;
import java.util.*;
public class SearchValueApp {
public static void main(String[] args) {
Vector v = new Vector();
Scanner xyz = new Scanner(System.in);
System.out.println("Enter value count which want to store in colelction");
int count=xyz.nextInt();
for(int i=1; i<=count;i++) {
int value=xyz.nextInt();
v.add(value);
}
System.out.println("Before remove "+v);
System.out.println("Enter value for delete");
int value=xyz.nextInt();
int index=v.indexOf(value);
if(index!=-1) {
v.remove (index);
System.out.println ("Element removed success ............. ");
}
else {
System.out.println ("Data not found");
}
System.out.println ("After Remove “+v);
}
}
How to store user defined objects in Collection
if we want to store user defined objects in collection then we have create POJO class and store data
in POJO class object and store POJO class object in collection means we can store data in POJO class
by using setter method and we retrieve data from collection then we get POJO objects and after that
we can retrieve data from collection.
Following Example demonstrate storing employee objet collection and retrieving employee object
from collection.
Above diagram show the process storing user defined object in Collection
if we think about above diagram first we created object of Vector name as Vector v = new Vector()
after that we created three object of Employee name as emp1,emp2 and emp3 and we store data in
employee object respectively id , name and salary and after we store employee objects in Vector
collection using v.add(emp1); v.add(emp2); v.add(emp3) if we think about above diagram structure
first we have Vector object in memory and then we have Employee object in memory and in
Employee we have id,name and salary
so if we want to fetch or display data from collection in above scenario first we need to fetch data
from Vector or any collection then we get data of Employee object or user defined object and from
user defined object we need to fetch data from employee object i.e. id,name and salary shown in
following Example
How to fetch data from Collection when it contain user defined object?
Steps
1) Fetch data from collection or iterate collection
Iterator i = v.iterator();
while(i.hasNext(){
}
here we consider v is reference of Collection mention in above diagram which contain 3
employee object.
2) We get data in the form of Object class
Iterator i = v.iterator();
while(i.hasNext()
{ Object obj = i.next();
}
3) We need to TypeCast Object class to User defined class Object
Iterator i = v.iterator();
while(i.hasNext()
{ Object obj = i.next();
Employee e =(Employee)obj;
}
here we convert Object class reference object in to Employee class e because we have Vector
collection and which contain user defined object of Employee class means we need to convert
Object class reference to Employee reference.
}
public class SearchValueApp {
public static void main(String[] args) {
Vector v = new Vector();
Employee emp1 = new Employee();
emp1.setId(1);
emp1.setName("ABC");
emp1.setSal(10000);
v.add(emp1);
v.add(emp2);
v.add(emp3);
Iterator i = v.iterator();
while(i.hasNext()) {
Object obj =i.next();
Employee e =(Employee)obj;
System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getSal());
}
}
}
Example: We want to create program to create class name as Player with field id, name and run as
well as age and we want to remove player from team whose age is greater than 35.
}
}
5) Retrieve data from collection
package org.techhub;
import java.util.*;
public class PlayerDriverApplication {
public static void main(String[] args) {
Vector v = new Vector();
int size;
Scanner xyz = new Scanner(System.in);
System.out.println("Enter player count");
size = xyz.nextInt();
Player p[] = new Player[size]; // array of reference
for (int i = 0; i < p.length; i++) {
xyz.nextLine();
p[i] = new Player();
System.out.println("Enter name id run and age of player");
String name = xyz.nextLine();
int id = xyz.nextInt();
int run = xyz.nextInt();
int age = xyz.nextInt();
p[i].setName(name);
p[i].setId(id);
p[i].setRun(run);
p[i].setAge(age);
v.add(p[i]);
}
for (Object obj : v) {
Player plr = (Player) obj;
System.out.println(plr.getId() + "\t" + plr.getName() + "\t" + plr.getRun() + "\t" +
plr.getAge());
}
}
}
package org.techhub;
import java.util.*;
public class PlayerDriverApplication {
public static void main(String[] args) {
Vector v = new Vector();
int size;
Scanner xyz = new Scanner(System.in);
System.out.println("Enter player count");
size = xyz.nextInt();
Player p[] = new Player[size]; // array of reference
for (int i = 0; i < p.length; i++) {
xyz.nextLine();
p[i] = new Player();
System.out.println("Enter name id run and age of player");
String name = xyz.nextLine();
int id = xyz.nextInt();
int run = xyz.nextInt();
int age = xyz.nextInt();
p[i].setName(name);
p[i].setId(id);
p[i].setRun(run);
p[i].setAge(age);
v. add(p[i]);
}
System.out.println("Player list before deletion ");
for (Object obj : v) {
Player plr = (Player) obj;
System.out.println(plr.getId() + "\t" + plr.getName() + "\t" + plr.getRun() + "\t" +
plr.getAge());
}
//deletion logics
Iterator i=v.iterator();
while(i.hasNext())
{
Object obj=i.next(); //step1 fetch single single object
Player plr=(Player)obj;//convert object class in to player class
if(plr.getAge()>35) //step3 fetch age from Player object
{
i. remove(); //remove player from Vector
}
}
System.out.println("Player list after deletion ");
for (Object obj : v) {
Player plr = (Player) obj;
System.out.println(plr.getId() + "\t" + plr.getName() + "\t" + plr.getRun() + "\t" +
plr.getAge());
}
}
}
Example: WAP to create Collection of students means here we need to create POJO class of student
class with field id,name,per and perform following operation on it
case 1: add new student in Vector
case 2: show all students from Vector
case 3: delete student using its id
case 4: Search student using its id or name
case 5: Arrange all students record in descending order
case 6: find second and third topper
case 7: find student who having minimum marks
case 8 : find student whose marks between 50 to 70 percentage
case 9: find student whose name is same
case 10: find student who having same marks and same name
2) ArrayList(int initialCapacity): using this constructor we can set initial capacity of ArrayList
package org.techhub;
import java.util.*;
public class ArrayListApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList al = new ArrayList(5);
al.add(10);
al.add(20);
al.add(30);
for(Object obj:al) {
System.out.println(obj);
}
}
}
3) ArrayList (Collection): Using this constructor we can copy data from another collection in to
ArrayList Collection.
package org.techhub;
import java.util.*;
public class ArrayListApp {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(100);
v.add(110);
ArrayList al = new ArrayList(v);
for(Object obj:al) {
System.out.println(obj);
}
}
}
If we think about above code we have Vector constructor and in Vector constructor we store 3
values i.e 10,100 and 110 and we have one ArrayList and we pass Vector object or reference in
ArrayList constructor so we copy all data of Vector in ArrayList Collection.
1) Create POJO class for store voter information Here we want to create two POJO classes
a) Voter information and b) Address information and we want to use voter id in address
class for identify voter address.
package org.techhub.clientapp;
import java.util.*;
import org.techhub.model.Address;
import org.techhub.model.Voter;
import org.techhub.repository.VoterRepository;
public class ClientApplication {
public static void main(String[] args) {
VoterRepository voterRepo = new VoterRepository();
do {
Scanner xyz = new Scanner(System.in);
System.out.println("1:Add New Voter");
System.out.println("2:View All Voter");
System.out.println("Enter your choice");
int choice = xyz.nextInt();
switch (choice) {
case 1:
System.out.println("Enter voter Id");
int vid = xyz.nextInt();
xyz.nextLine();
System.out.println("Enter voter name");
String name = xyz.nextLine();
System.out.println("Enter voter email");
String email = xyz.nextLine();
System.out.println("Enter voter contact");
String contact = xyz.nextLine();
System.out.println("Enter voter gender");
String gender = xyz.nextLine();
System.out.println("Enter voter age");
int age = xyz.nextInt();
Voter v = new Voter();
v.setVoterId(vid);
v.setName(name);
v.setEmail(email);
v.setContact(contact);
v.setAge(age);
v.setGender(gender);
// address details of voter
System.out.println("Enter plotno");
int plotNo = xyz.nextInt();
System.out.println("Enter wardno");
int wardNo = xyz.nextInt();
System.out.println("Enter villater");
xyz.nextLine();
String village = xyz.nextLine();
System.out.println("Enter taluka");
String taluka=xyz.nextLine();
System.out.println("Enter district");
String distrcit=xyz.nextLine();
System.out.println("Enter state of voter");
String state=xyz.nextLine();
Address ad = new Address();
ad.setVoterid(vid);
ad.setWardNo(wardNo);
ad.setPlotNo(plotNo);
ad.setVillage(village);
ad.setTaluka(taluka);
ad.setDistrict(distrcit);
ad.setState(state);
v.setAddress(ad);
boolean b = voterRepo.addNewVoter(v);
if(b) {
System.out.println("Record Added Success................");
}
else {
System.out.println("Some problem is
there........................");
}
break;
case 2:
voterRepo.voterDetails();
break;
default:
System.out.println("Wrong choice");
}
} while (true);// infinite array
}
}
System.out.println("============================================");
for(Object obj1:al)
{
Voter v=(Voter)obj1;
Address a=v.getAddress();
if(a.getWardNo()==wardNo) {
System.out.println(v.getName()+"\t"+v.getAge()+"\t"+v.getEmail()+"\t"+v.getContact());
}
}
System.out.println("================================================");
}
}
}
LinkedList
LinkedList is implementer class of List Collection and it is by default doubly linked list means every
node has two pointers one is next, one is previous and one is data.
prev data next
LinkedList ArrayList
LinkedList is by default double linked list ArrayList is by default dynamic array
LinkedList use O(1) time complexity for deletion ArrayList use O (n) time complexity for deletion
and updation of element means LinkedList is and updation element means ArrayList is slower
faster than ArrayList for deletion of element and than linked list for deletion and updation of
for updation of element means in the case of element. In terms deletion and updation of
deletion element from LinkedList and updation element it required iterations so it will take more
of element from LinkedList no required iteration time for data deletion and shifting element so it
statement so it is faster is slower than linked list for deletion and
updation of
LikedList is slower than ArrayList for element ArrayList is faster than LinkedList for search and
searching purpose if we think about LinkedList it retrieve elements. if we think about ArrayList it is
is connected via nodes means previous node stored as dynamic array means all elements of
contain address of next and next node contain array stored sequentially so it is very easy to find
address of previous node so memory address index and address of data so ArrayList is faster
stored randomly in memory so if we want to than LinkedList
select data from linked first we need to find its
address and index so it will more time for
address searching and data searching
Constructor of LinkedList
LinkedList (): this constructor is used for create empty linked list.
LinkedList (Collection): this constructor is used for copy data from another collection in LinkedList
Example:
package org.techhub;
import java.util.*;
public class LinkedListApp {
public static void main(String[] args) {
LinkedList lst = new LinkedList();
lst.add(10);
lst.add(20);
lst.add(30);
lst.add(40);
for(Object obj:lst) {
System.out.println(obj);
}
}
}
Example: WAP to create LinkedList and store product information in it and display its data.
package org.techhub;
Stack
Stack is a child class of Vector and Vector is implementer class of List means we can say Stack is
indirect child of List Collection
Stack Collection can maintain data in last in first out format.
Source code
package org.techhub;
import java.util.*;
Collections is a utility class of java which is used for apply some data structure operation on
collection framework like as sorting, find max element, reverse element etc
Q. What is utility class?
Utility class means a class with private constructor and which contain only static methods called as
utility class In short we can say we cannot create object of Utility class in Java.
Example: Math is utility class of java, Collections is also utility class etc.
}
}
Example: WAP to store 5 values in ArrayList Collection and Arrange in ascending order?
package org.techhub;
import java.util.*;
public class ArrayListApp {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(5);
al.add(2);
al.add(9);
al.add(12);
al.add(7);
System.out.println("Before Sorting");
for(Object obj:al) {
System.out.println(obj);
}
Collections.sort(al);
System.out.println("\nAfter Sorting");
for(Object obj:al) {
System.out.println(obj);
}
}
}
@Override
public int compareTo(Object o) {
Employee emp = (Employee) o;
if (this.getId() > emp.getId()) {
return 1;
} else if (this.getId() < emp.getId()) {
return -1;
} else {
return 0;
}
}
}
Example: Create POJO class name as Player with three field id,name and run and we want to apply
sorting on player by run means arrange player record in ascending order by run.
package org.techhub;
import java.util.*;
Comparator interface is used for perform sorting with POJO object by using multiple attribute means
suppose consider if we think about above example we have Player POJO class and we apply sorting
on it by run but if we want to apply sorting of player by run, by id or by age etc then it is not possible
to perform sorting using Comparable interface so we have one more approach name as Comparator
interface.
Steps to work Comparator interface in Java
package org.techhub;
import java.util.*;
class Player {
private int id;
private String name;
import java.util.Comparator;
public class SortPlayerById implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Player p1 = (Player) o1;
Player p2 = (Player) o2;
if (p1.getId() > p2.getId()) {
return 1;
} else if (p1.getId() < p2.getId()) {
return -1;
} else {
return 0;
}
}
}
Logic with sort by run
package org.techhub;
import java.util.Comparator;
public class SortPlayerByRun implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Player p1=(Player)o1;
Player p2=(Player)o2;
if(p1.getRun()>p2.getRun()) {
return 1;
}
else if(p1.getRun()<p2.getRun()) {
return -1;
}
else {
return 0;
}
}
}
Note: when we use Comparator for sorting purpose then you to use Collections.sort() like as
mention in next step.
Now we want to implement program case 1: sort by id, case 2: sort by run
package org.techhub;
import java.util.*;
class Player {
private int id;
private String name;
package org.techhub;
import java.util.Comparator;
@Override
public int compare(Object o1, Object o2) {
Player p1 = (Player) o1;
Player p2 = (Player) o2;
if (p1.getId() > p2.getId()) {
return 1;
} else if (p1.getId() < p2.getId()) {
return -1;
} else {
return 0;
}
}
}
package org.techhub;
import java.util.Comparator;
public class SortPlayerByRun implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Player p1=(Player)o1;
Player p2=(Player)o2;
if(p1.getRun()>p2.getRun()) {
return 1;
}
else if(p1.getRun()<p2.getRun()) {
return -1;
}
else {
return 0;
}
}
}
case 1:
SortPlayerById sid=new SortPlayerById();
Collections.sort(al,sid);
System.out.println("Display player record after sorting");
for (Object obj : al) {
Player p = (Player) obj;
System.out.println(p.getId() + "\t" + p.getName() + "\t" +
p.getRun());
}
break;
case 2:
SortPlayerByRun srun=new SortPlayerByRun();
Collections.sort(al,srun);
System.out.println("Display player record after sorting");
for (Object obj : al) {
Player p = (Player) obj;
System.out.println(p.getId() + "\t" + p.getName() + "\t" +
p.getRun());
}
break;
default:
System.out.println("Wrong choice");
}
}
}
Q. what is difference between Comparator and Comparable?
Comparator Comparable
Use For perform sorting with multiple attribute Use for perform sorting with single attribute
Member of java.util package Member of java.lang package
Contain int compare(Object o1,Object o2) Contain int compareTo(Object)
Use Collections.sort(List,Comparator) version Use Collections.sort(List) version
Set Collection
Set Collection is used for store unique data not allow duplicated data and set collection use hashing
technique or hash code for verify data is duplicated or not if we found same hash code of previous
element in set then set not allow element for store means we can set collection not use indexing
technique for storing elements.
If we want to work with a Set Collection we have following classes and interfaces
Following diagram demonstrate Set Collection hierarchy
HashSet: HashSet collection is used for store unique values and generates element sequence
randomly or generates random data.
Constructor of HashSet
HashSet (): This constructor creates HashSet collection with default or initial capacity 16 and load
factor 0.75 and create internally object HashMap
Means we can say when we create this constructor then we get HashSet with default capacity 16
and when we cross this capacity then it will increase its size with 75% corresponding with initial
capacity
Means if initial capacity is 16 and when user try to 17th element in it then new capacity of HashSet is
28
HashSet(Collection): this constructor is used for copy the data from another collection in Set
collection and this constructor create HashSet with 0.75% load factor and initial capacity is 16 if
element in collection less than 16 if element in collection greater than 16 then it will increase
capacity with 0.75% as per corresponding capacity.
package org.techhub;
import java.util.*;
public class HashSetCollectionApp {
public static void main(String[] args) {
Note: by default HashSet Collection use 16 as initial capacity and 0.75% as load factor but if user
want to set initial capacity as per his choice as well as set load factor as per his choice then HashSet
Collection
provide following constructor to us.
HashSet (int initialCapacity, float loadFactor):
int initialCapacity: this parameter indicate set initial capacity as per user choice
float loadFactor: this parameter indicate set load factor as per user choice.
package org.techhub;
import java.util.*;
public class HashSetCollectionApp {
public static void main(String[] args) {
HashSet hs = new HashSet(10,0.5f);
hs.add(10);
hs.add(20);
System.out.println(hs);
}
}
Example: we want to create HashSet Collection which contain 5 values and display it.
package org.techhub;
import java.util.*;
public class HashSetCollectionApp {
public static void main(String[] args) {
HashSet hs = new HashSet(10,0.5f);
hs.add(10);
hs.add(20);
hs.add(30);
hs.add(40);
hs.add(45);
hs.add(23);
hs.add(67);
hs.add(98);
hs.add(423);
hs.add(90);
hs.add(10);
hs.add(20);
Iterator i = hs.iterator();
while(i.hasNext()) {
Object obj = i.next();
System.out.println(obj);
}
}
}
LinkedHashSet : LinkedHashSet can also store unique values but generate value sequence as per
user sequence and LinkedHashSet is child of HashSet
Constructor of LinkedHashSet
LinkedHashSet(): this constructor create object of LinkedHashSet with initial capacity 16 and load
factor 0.75 and pass these parameter to its parent means to HashSet using super() constructor.
LinkedHashSet(int initialCapacity): this constructor can create LinkedHashSet object with initial
capacity as per user choice and default load factor is 0.75%
LinkedHashSet(int initialCapacity,float loadFactor): create LinkedHashSet object with initial capacity
as per user choice and load factor as per user choice.
LinkedHashSet(Collection): this constructor is used for copy data from another collection in
LinkedHashSet
Example: we want to create Program to store 5 values in LinkedHashSet and display it.
package org.techhub;
import java.util.*;
public class HashSetCollectionApp {
public static void main(String[] args) {
LinkedHashSet hs = new LinkedHashSet();
hs.add(10);
hs.add(20);
hs.add(30);
hs.add(40);
hs.add(45);
for(Object obj:hs) {
System.out.println(obj);
}
}
}
TreeSet Collection : TreeSet collection allow unique data but arrange all data in ascending order and
TreeSet collection internally work with TreeMap
Constructor of TreeSet
TreeSet(): this constructor is used for create object with default initial capacity and load factor
means initial capacity is 16 and load factor is 1.
TreeSet(Comparator): this constructor normally use when user want to sort user defined object by
using TreeSet Collection.
Example
package org.techhub;
import java.util.Comparator;
public class SortPlayerById implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Player p1 = (Player) o1;
Player p2 = (Player) o2;
if (p1.getId() > p2.getId()) {
return 1;
} else if (p1.getId() < p2.getId()) {
return -1;
} else {
return 0;
}
}
}
package org.techhub;
import java.util.*;
public class HashSetCollectionApp {
public static void main(String[] args) {
SortPlayerById si = new SortPlayerById();
TreeSet hs = new TreeSet(si);
hs.add(new Player("ABC", 1, 5000));
hs.add(new Player("MNO", 3, 2000));
hs.add(new Player("PQR", 2, 4000));
hs.add(new Player("STV", 4, 6000));
for(Object obj:hs) {
Player p=(Player)obj;
System.out.println(p.getId()+"\t"+p.getName()+"\t"+p.getRun());
}
}
}
Note: if we think about TreeSet then we arrange all data in ascending order but if we want to
arrange TreeSet Collection in Descending order then we have descendingSet() method of TreeSet
Collection and this method return reference of NavigableSet interface.
NavigableSet interface is used for travel the collection in descending order.
Syntax: NavigableSet ref =treesetref.descendingSet();
package org.techhub;
import java.util.*;
public class DescendingSetApplications {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet treeSet = new TreeSet();
treeSet.add(4);
treeSet.add(40);
treeSet.add(3);
treeSet.add(23);
treeSet.add(22);
treeSet.add(56);
treeSet.add(32);
NavigableSet nav=treeSet.descendingSet();
for(Object obj:nav) {
System.out.println(obj);
}
}
}
Object class and its method
Example:
package org.techhub;
class Test
{ int no;
Test(int x){
no=x;
}
}
public class ObjectclassTestApp {
public static void main(String[] args) {
Test t1 = new Test(100);
Test t2 = new Test(100);
if(t1 == t2) {
System.out.println("Objects are equal");
}
else {
System.out.println("Objects are not equal");
}
}
}
if we think about above code have two object i.e t1 and t2 and t1 object contain 100 value and t2
object contain 100 after that we have t1==t2 but this program generate output Objects are not
equal.
Q. if I have two objects with same value then why they are not equal ?
In the case of Java Object comparison perform on basis of its hashcode not perform on basis of its
value.
Q. what is hashcode?
hashcode is integer number generated by JVM for object and JVM generate unique hashcode for
every object even values of object are same means in short we can say hash code is same like as
memory address
Q. can we see the hashcode of object?
Yes we can see the hash code of object and if we want to see hashcode of object we have method
name as System.identityHashCode() and this method return hashcode of object generated by JVM
for object.
if we think about above code we have two objects i.e. t1 and t2 and t1 contain hash code
1227229653 and t2 contain 971848845 means we have two object with same values but with
different hash code
and again we have statement if(t1 ==t2) so if we think about this statement the meaning is
if(1227229653==971848845) it is false so else block get executed and we get output objects are not
equal.
boolean equals(Object): this method accept object as parameter and compare parameter object
with working object if both objects are equal return true otherwise return false.
int hashCode(): this method must be override by developer and if two objects are same then
generate same hashcode and if objects are not same then generate different hashcode.
package org.techhub;
class Test extends java.lang.Object {
int no;
Test(int x) {
no = x;
}
public boolean equals(Object obj) {
Test tt = (Test) obj;
if (this.no == tt.no) {
return true;
} else {
return false;
}
}
public int hashCode() {
return no*100;
}
}
}
}
Q. why we need to generate two objects hash codes same if objects are equal?
Scenario: Some time if we store user defined objects in Set Collection then there is possibility Set
collection can store duplicated data because Set collection cross verify hash code of object when we
add element in Set Collection and by default every object has unique hash code generated by JVM so
when we add user defined object in Set Collection then Set collection first compare hash code of
new object with object those already present in Set collection if new object hash code match with
previous objects in Set collection then Set consider it is duplicated data otherwise Set allow data but
if we think about user defined object then JVM generate different hash code to every object even
data of two objects are same so there is possibility set can store duplicated data when we add user
defined objects in set it shown in following code.
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) {
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;
}
Object cloning concept
Object cloning means if create duplicated copy of object called as object clone
if we think about above diagram we have Statement Square s1 = new Square() here we create object
new Square() and we store its address 10000 in s1 reference when we have statement
s1.setValue(10) means we store 10 value in object whose address is 10000 after that we have
statement Square s2=s1;
means assign value of s1 reference in s2 reference again we have statement s2.setValue(5) means
here 10000.setValue(5) means 5 get override on no whose address is 100000 so no=5 on address
10000 so when call s1.showSquare() we found 5 not 10 mans we can say s2 reference override
object whose set by s1 reference means object previous content get lost so if we want to solve this
problem we have object clone concept.
package org.techhub;
class Square implements Cloneable
{ int no;
void setValue(int x) {
no=x;
}
void showSquare() {
System.out.printf("Square is %d\n", no*no);
}
Square getSquare()throws CloneNotSupportedException{
//Object obj=this.clone();
//Square s=(Square)obj;
//return s;
return (Square)this.clone();
}
}
Q. What is diff between object creation using cloning and using new keyword?
When we create object using new keyword then constructor gets executed but when we create
object using clone then constructor not executed.
String toString(): this method is used for convert user defined objects in to string means when use
user defined objects and try to print it or use it at any where then we cannot see its data and if we
see the user defined object as well as use user defined objects as string then we need to convert
object in to string format and for that we have toString() method of Object class.
Example
package org.techhub;
import java.util.*;
class Player
{
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 getRun() {
return run;
}
public void setRun(int run) {
this.run = run;
}
private int run;
public String toString() {
return "["+name+","+id+","+run+"]";
}
}
public class PlayerApplication {
public static void main(String[] args) {
Player p = new Player();
p.setId(1);
p.setName("ABC");
p.setRun(10000);
System.out.println(p);//p.toString()
}
}
Example: WAP to Create ArrayList Collection and store 5 players objects in it and display its data.
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) {
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;
public String toString() {
return "["+name+","+id+","+run+"]";
}
}
public class PlayerApplication {
public static void main(String[] args) {
}
}
Static block
static block is a member of java.lang.Object class
important points of static block
1) static block execute very first in program before main method also.
}
}
If we think about above code we have static block and main method and when we run program then
static block get executed before main method.
2) static block execute only once in program at first when we create object class
But instance block can execute every time when we create object of class but instance block execute
before constructor.
Generics
Generics is a concept launch by JDK 1.5 version of java which is used for avoid ClassCastException at
run time If we think about collection then we can store any type of data in Collection but there is
problem when we retrieve data from collection then we get data in the form of Object class but if
we think about Object class then it can store any type of data but we need to convert this data in its
associated format then there is possibility to generate ClassCastException at run time.
Example
package org.techhub.gen;
import java.util.*;
public class GenericApplication {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);
al.add(20);
al.add("ABC");
al.add(5.4f);
al.add(false);
al.add(50);
int sum=0;
for(Object obj:al) {
sum=sum+(int)obj;
}
System.out.println("Sum of all element is "+sum);
}
}
if we think about above code we have ArrayList with values 10 ,20 ABC , 5.4 ,false and 50 so here
when we fetch data from collection then we get data in the form of Object class and when we fetch
data in the form of Object class and we convert data in integer so first two values i.e 10 20 get
convert properly but when we fetch ABC value and we try to convert it in integer so it is not possible
because ABC is string and we try to convert in integer so it is not possible so JVM generate
ClassCastException at run time so if we want to avoid this problem we have two ways.
1) Use instanceof operator: instanceof operator is used for check object belongs in which class
called as instance of operator.
Example
package org.techhub.gen;
import java.util.*;
public class GenericApplication {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);
al.add(20);
al.add("ABC");
al.add(5.4f);
al.add(false);
al.add(50);
int sum=0;
for(Object obj:al) {
if(obj instanceof Integer) {
sum=sum+(int)obj;
}
} System.out.println("Sum of all element is "+sum);
}
}
If we think about above code first we check obj instanceof integer means here we check retrieve
value from collection is type of integer or not if it is type of integer then we can convert it otherwise
not.
But instanceof is not feasible solution so we have one more option name as generics
2) Use Generics: generics in java is denoted by < > and when we use generics with collection then
we can store specific type of data in collection whose type we mention with collection means
generic help us to apply restriction on collection to work with specified type
Example:
ArrayList<Integer> al = new ArrayList<Integer>() : if we think this statement here we use <Integer>
with al object of ArrayList means if we call any method of Collection using al then it can accept only
integer value or retrieve only integer value and if we try to store other value than integer then
compiler will generate compile time error to us shown in following code.
Example
package org.techhub.gen;
import java.util.*;
public class GenericApplication {
public static void main(String[] args) {
ArrayList <Integer>al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add("ABC");
al.add(5.4f);
al.add(false);
al.add(50);
int sum=0;
for(Object obj:al) {
if(obj instanceof Integer) {
sum=sum+(int)obj;
}
}
System.out.println("Sum of all element is "+sum);
}
}
if we think about above code we get compile time error to us because we try to store value ABC,5.4
and false in al object but we use <Integer> with al object means al only works with integer and we
try to use other than integer data with al so compiler will generate error so if we want to avoid this
problem we can remove 5.4,ABC and false from ArrayList Collection.
package org.techhub.gen;
import java.util.*;
public class GenericApplication {
public static void main(String[] args) {
ArrayList <Integer>al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(50);
int sum=0;
for(Integer obj:al) {
sum=sum+obj;
}
System.out.println("Sum of all element is "+sum);
}
}
Example:
package org.techhub.gen;
import java.util.*;
public class GenericApplication {
public static void main(String[] args) {
ArrayList <Integer>al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(50);
int sum=0;
for(Integer obj:al) {
sum =sum+obj;
}
System.out.println("Sum of all element is "+sum);
}
}
if we think about this code here we found we lost main use collection to store different type of data
because above ArrayList object only with integer type of data so it work like as normal array so we
loose feature of collection is different type of data.
1) Class with Generics: if we use class with generic notations then we can create user defined class
as generic class.
Syntax: class classname<E>{
}
Example
package org.techhub.gen;
class ABC<E> //ABC work as generic class
{ void show(E e) {
System.out.println("E is "+e);
}
}
public class UserGenericClassApplication {
public static void main(String[] args) {
ABC <Integer>a1 = new ABC<Integer>();
a1.show(10);
a1.show(20);
a1.show(30);
a1.show(49);
}
}
Interface with generics: Interface with generics is facility where we can change the method
parameter type in its every implementer class as per the requirement of child.
syntax: interface interfacename<E>
{ returntype methodname(E e)
}
Example: we want to create interface name as Area with method name as void setRadius(E e) and
we have two implementer classes name as Circle and Cirm and we want to pass radius as integer in
Circle class and radius as float in Cirm class then we can use generics for change the parameter type
of method as per the requirement of child class.
package org.techhub.gen;
interface Area<E> {
void setRadius(E e);
}
class Circle implements Area<Integer> {
@Override
public void setRadius(Integer e) {
System.out.println("Integer radius " + e);
}
}
class Cirm implements Area<Float> {
@Override
public void setRadius(Float e) {
System.out.println("Float Radius " + e);
}
}
public class InterfaceWithGenApplication {
public static void main(String[] args) {
Circle c = new Circle();
c.setRadius(5);
Cirm cm = new Cirm();
cm.setRadius(5.4f);
}
}
Wildcard generics: if we think about wild card generics it is denoted by?
So normally wild card generics refer in program when we want to work with multiple types of data
at run time then we can use wild card generics
There are two types of wild card generics
1) Unbounded generics: unbounded generics refer with parameter in method when we not sure
about parameter type then we can use unbounded generics
Example:
package org.techhub.gen;
import java.util.*;
class Test
{ void show(List<?> list) {
for(Object obj:list) {
System.out.println(obj);
}
}
}
public class UnBoundedApplication {
public static void main(String[] args) {
//List<Integer> list=Arrays.asList(10,20,30,40,50);
List<String> list=Arrays.asList("good","bad");
Test t = new Test();
t.show(list);
}
}
if we think about above code we have function name as show(List<?>) this function indicate we can
accept any type of parameter or any type generic list as parameter in show
2) Bounded generics:
There are two types of bounded generics
1) Upper bounded : in upper bounded generics we have to use extends keyword means if
use extends keyword in upper bounded means we can pass any paent class reference in as
parameter in generics
Syntax: ? extends parametername
}
public class LowerBoundedGenerics {
public static void main(String[] args) {
ArrayList<? super Value> al = new ArrayList();
Mul m = new Mul();
m.setValue(10, 20);
al.add(m);
Add ad = new Add();
ad.setValue(5, 4);
al.add(ad);
}
}
If we think about above ArrayList object al so this al object only accept parameter those are child
class of Value means we can store Mul and Add class object in ArrayList.
Map interface:
Map interface is used for store data in the form of key and value pair Here key cannot be duplicate
and value may be duplicated using key we can store data in map , retrieve data from map, update
data in map or remove data from map as well as search data from map
In short we can say Map is combination of set and list collection set work as key and list work as
value.
Following diagram shows how map store data
Map for student record
Rollno (key) Name(Value)
1 Abc
2 Mno
3 Pqr
4 Abc
5 Mno
If we want to work with Map interface we have following implementer classes provided by Java to us
If we think about above diagram we have Map is interface and Map interface provide some inbuilt
method to us which is used for perform operation on Map collection
Methods of Map interface
public abstract V put(K,V): this method is used for store data in the form of key and value pair here
K represent key of any type and V represent a value of any type but we can specify key and value of
particular type using generics.
public V get(K): this method can retrieve data from map using its key if key not found return null so
normally we refer this method in three cases
1) Fetch Data from Map: using this method can retrieve data from map.
2) Search Data from map: when we found null result from map means we can consider data not
present if we not found null result from map then we can consider data present in map collection.
public abstract V remove(K): this method is used for remove data from map using its key if key not
found then return null.
boolean containsKey (K): this method check key present in map or not if present return true
otherwise return false.
boolean containsValue (V): this method check value present in map or not if present return true
otherwise return false.
Set keySet(): this method return all keys from map collection normally we refer this method when
we want to fetch all data from collection.
Collection values(): this method is used for return all values from collection.
Map.Entry entrySet(): this method return data in the form of Map.Entry and Entry is interface which
return key and value for that we have two methods
Object getKey (): return key from map
Object getValue (): return value from map.
HashMap: HashMap can store data in the form of key and value pair but generate key sequence
randomly.
Constructor of HashMap
1) HashMap(): this constructor is used for create HashMap object with default initial capacity as well
as with default load factor and the initial capacity of HashMap is 16 and default load factor of
hashmap is 0.75
2) HashMap(int initialCapacity): this method is used for create HashMap with initial capacity set by
developer and this constructor use default load factor value.
3)HashMap(int initialCapacity,float loadFactor): this constructor is used for create object with
initial capacity as per user choice and load factor value as per user choice.
4) HashMap(Map<K,V>): this constructor is used for copy the another map data in HashMap.
Example: we want to create program to store student id and student name in HashMap and display
its data.
package org.techhub;
import java.util.*;
public class HashMapApplication {
}
}
LinkedHashMap: LinkedHashMap is used for store data in the form of key and value pair but arrange
key sequence as per user sequence.
Constructor of LinkedHashMap
1) LinkedHashMap(): this constructor is used for create LinkedHashMap object with default initial
capacity as well as with default load factor and the initial capacity of LinkedHashMap is 16 and
default load factor of hashmap is 0.75
2) LinkedHashMap(int initialCapacity): this method is used for create LinkedHashMap with initial
capacity set by developer and this constructor use default load factor value.
3)LinkedHashMap(int initialCapacity,float loadFactor): this constructor is used for create object
with initial capacity as per user choice and load factor value as per user choice.
4)LinkedHashMap(Map<K,V>): this constructor is used for copy the another map data in
LinkedHashMap.
}
}
TreeMap: TreeMap can store data in the form of key and value pair but arrange key sequence in
ascending order.
TreeMap(): sort by default keys using primitive data type.
TreeMap(Comparator): accept Comparator as parameter means we can sort keys when we have
user defined objects as key
TreeMap(Map): It is used for copy the data from another Map in TreeMap.
package org.techhub;
import java.util.*;
public class HashMapApplication {
public static void main(String[] args) {
TreeMap <Integer,String> map = new TreeMap<Integer,String>();
map.put(4, "ABC");
map.put(5, "MNO");
map.put(2, "PQR");
map.put(23, "ABC");
map.put(56, "STV");
map.put(76, "XYZ");
map.put(234, "STV");
map.put(897, "ABCD");
map.put(6789, "POQSS");
map.put(54, "SSSS");
map.put(4, "YYYYY");
map.put(67, "YYTTT");
map.put(56, "OOOOOOO");
map.put(44, "PPPPPPPPPPP");
Set<Map.Entry<Integer, String>> data=map.entrySet();
for(Map.Entry<Integer, String> v:data) {
System.out.println(v.getKey()+" --------- >"+v.getValue());
}
}
}
Example: WAP to input 10 values in array and find occurrence of every element of array.
package org.techhub;
import java.util.*;
public class HashMapApplication {
public static void main(String[] args) {
int a[]=new int[] {10,20,30,10,20,30,10,20,30,40};
LinkedHashMap <Integer,Integer> map = new LinkedHashMap<Integer,Integer>();
for(int val:a) {
Integer key = map.get(val);
if(key!=null) {
++key;
map.put(val,key);
}
else {
key=0;
map.put(val, ++key);
}
}
Set<Map.Entry<Integer, Integer>> data=map.entrySet();
for(Map.Entry<Integer,Integer> d:data) {
System.out.println(d.getKey()+" --------------- "+d.getValue());
}
}
}
Map With collection
Some time when we want to give more than one values to single key then we can use map with
collection property.
Example: Example we want to create application where we want to design Tournament application
where we want to maintain team name and all player list of team.
if we think about above diagram we have LinkedHashMap<String,ArrayList> here we specify we can
maintain key as string and value as ArrayList
Means we can store multiple value with single key
if we think above code
LinkedHashMap<String,ArrayList> map = new LinkedHashMap<String,ArrayList>();
here we created linked hash map with key string and value with ArrayList
again we have statement ArrayList<String> india = new ArrayList<String>(); here we created one
collection name as india means we store multiple values in this collection means we have statement
india.add(“Rohit”); india.add(“Virat kohali”); india.add(“Hardik pandya”) means store three values in
single object i.e india and again same we have one more object of ArrayList <String> aus = new
ArrayList<String>() and we three player name in aus collection and we have statement
map.put(“india”,india) means here we have single key name as india and we have three different
values india object means we use collection with map when we want to store multiple values to
single key.
How to retrieve data from when we want to retrieve collection from map
When we retrieve data from map when we have value as collection then we get collection object as
value means as per our example we get ArrayList as value so we need to apply Iterater on ArrayList
for fetch data from collection.
System.out.println("========================"+teamName+"======================
==");
ArrayList<String>playerList=d.getValue();
for(String pName:playerList)
{
System.out.println(pName);
}
}
}
}
public void start(): this method is used for start thread means when we call this method then run() method internally
get executed.
means we not need to call run() method manually by thread child class object and if we call run() method manually
then it is not work as thread it work as normal method.
public static void sleep(int milliseconds): this method help us to hold thread execution for a specified time period
and it is static method of Thread class but when we call this method we must be handle InterruptedException at
compile time means InterruptedException is checked type of exception so when we use sleep() method then we
must be use try and catch or throws block otherwise compiler will generate compile time error to us.
public void join(): this method is used for hold another thread execution whenever running thread is not complete its
execution and if we want to use this method we need to handle InterruptedException at compile time
public boolean isAlive(): this method check thread is running or not if thread is running return true otherwise return
false means we can say this method help us check status of thread in memory
public void stop(): this method is used for terminate execution of thread at run time.
Example: Now we want to create Thread name as MyThread and we want to write simple for loop in it and execute
for loop five times and maintain delay in every iteration of 10 seconds using sleep() method shown in following code
and diagram.
if we think about above we created object MyThread class which work as thread in program and we have statement
m.start() when we call start() method then internally run90 method get executed and in run() method we write logic
for(int i=1; i<=5; i++) System.out.printf(“ I = %d\n”,i) and Thread.sleep(1000) here on every iteration of i process
waiting for 10 seconds if we execute another thread in waiting of every iteration of MyThread class then we can say it
is multi threading.
if we think about above memory diagram we consider ThreadApp is our java program so it is process and in this
program we create two object MyThread m = new MyThread() so it is my one thread and we have one more object
name as MyThread1 m1 = new MyThread1(); here we create second thread both thread present under ThreadingApp
process so when we call m.start() then internally run() method get executed in of first thread so in this thread we
have loop which execute five times and every iteration has 10 seconds waiting period so when first iteration get
executed of first thread then process find 10 seconds waiting period in first thread so process create object of second
thread and execute second thread 10 times in waiting for first thread because in second thread we have waiting
period is 1 seconds so means processor execute first and second thread simultaneously called as context switching.
Example: in above example we have two thread first thread execute five times and second thread execute 50 times
so we want to terminate execution of first thread after 3rd iteration in this case we can use stop() method shown in
following code.
package org.techhub;
import java.lang.*;//step1
class MyThread extends Thread // step2
{
public void run() // step3
{
try {
for (int i = 1; i <= 5; i++) {
System.out.printf("First Thread = %d\n", i);
if(i==3) {
stop();
}
Thread.sleep(10000);
}
} catch (InterruptedException ex) {
System.out.println("Error is " + ex);
}
}
}
class MyThread1 extends Thread
{
public void run() // step3
{ try {
for (int i = 1; i <= 50; i++) {
System.out.printf("Second Thread = %d\n", i);
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("Error is " + ex);
}
}
}
public class ThreadingApp {
public static void main(String[] args) {
MyThread m = new MyThread();// step4
m.start(); // step5
MyThread1 m1 = new MyThread1();
m1.start();
}
}
if we think about above code we have two threads MyThread and MyThread1 and both are executed by processor
waiting of each other but we want to complete execution first thread even first thread has waiting once first thread
get completed we want to start() second in this case we can use join() method.
package org.techhub;
import java.lang.*;//step1
class MyThread extends Thread // step2
{
public void run() // step3
{
try {
for (int i = 1; i <= 5; i++) {
System.out.printf("First Thread = %d\t%b\n", i,isAlive());
if(i==3) {
stop();
}
Thread.sleep(10000);
}
} catch (InterruptedException ex) {
System.out.println("Error is " + ex);
}
}
}
class MyThread1 extends Thread
{
public void run() // step3
{
try {
for (int i = 1; i <= 50; i++) {
System.out.printf("Second Thread = %d\n", i);
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("Error is " + ex);
}
}
}
public class ThreadingApp {
public static void main(String[] args) throws InterruptedException{
MyThread m = new MyThread();// step4
m.start(); // step5
m.join();
System.out.println("Now status of first thread is "+m.isAlive());
MyThread1 m1 = new MyThread1();
m1.start();
}
}
Q. what is resource?
_________________________________________________________________________
Here resource indicate object
if we think about above code we have three classes one is Table class which work as resource and we have two more
classes one is Two and one is Three and we pass Table object in class Two using setTable() method and we pass Table
object in class Three using setTable() method and if we think about main method we create object of Table t = new
Table() and in diagram we consider reference of Table object is 10000 and which stored in reference variable t and
again we have statement Two tw = new Two() means we create object of thread two and we call method
tw.setTable(t) means Thread two use object of Table class and when we call tw.start() then internally JVM call run()
method of thread two and in two thread we have statement table.showTable(2) means we call showTable() method
by passing parameter value 2 then for loop get execute for(i=1; i<=5; i++) so here we have statement
System.out.printf(“%d X %d = %d\n”,i,x,i*x) here 1 x 2 = 2 get executed again we have statement
Thread.sleep(1000) means processor create object of Three th = new Three() in waiting of thread two and again we
statement th.setTable(t) means thread three use object of Table class and again we call method th.start() means
internally JVM call run() method of thread three and from run() we have table.showTable(3) again we call
showTable() from thread three and we have statement for(i=1;i<=10;i++) System.out.printf(“%d X %d = %d\n”,i,x,i*x)
here 1 x 3 =3 get executed again in waiting of thread three processor call thread two and in waiting of thread two
processor call thread table means here Table object use by simultaneously thread two and thread three so here we
can say it is example of asynchronization.
so if we want to perform synchronization means if Thread two use Table object whenever Thread two not complete
its execution JVM should not start thread three so java provide synchronized keyword to us for achieve
synchronization and we can use synchronized keyword with method and with block shown in following example.
Example of synchronization
package org.techhub;
class Table
{ synchronized 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);
}
}
}
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 t = new Table();
Two tw = new Two();
tw.setTable(t);
tw.start();
Three th = new Three();
th.setTable(t);
th.start();
}
}
Q. what is diff between join() and synchronized
join() Synchronized
join() is method of thread class synchronized is keyword and which known as non
access specifier
Join() method can work with thread object Synchronized keyword can work with method or
block as resource
If we have multiple thread e.g But if we use synchronized keyword with resource
first,second,third,fourth and if we use join() then all threads use resource one by one
method with first thread then remaining three sequentially
threads hold its execution when ever running
thread is not completed after remaining all threads
executed simultaneously so we need to use join
with every thread
2) unconditional wait: unconditional wait means if thread not re-execute if self again we need to send request to
thread for re-execution purpose called as unconditional wait.
syntax: void wait();
in the case of unconditional wait we need to send request to thread for re-execution purpose and for that we
have two methods
void notify(): this method call waited thread one by one sequentially in the form of queue but call only one thread a
time.
void notifyAll(): notifyAll() call all waited thread at same time in the form of last in first out format.
import java.util.Scanner;
class Table
{ synchronized void showTable(int x) {
try {
for(int i=1; i<=10;i++) {
System.out.printf("%d X %d = %d\n", i,x,i*x);
if(i==5) {
wait();
}
Thread.sleep(1000);
}
}
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 t = new Table();
Two tw = new Two();
tw.setTable(t);
tw.start();
Three th = new Three();
th.setTable(t);
th.start();
do {
Scanner xyz = new Scanner(System.in);
String msg=xyz.nextLine();
if(msg.equals("restart"))
{
t.recall();
}
}while(true);//infinte loop
}
}
Q. what is diff between wait and sleep?
Wait Sleep
Wait() is a method of Object class Sleep() is static method of Thread class
Wait() can work with conditional as well as Sleep() only works with conditional wait
unconditional wait
Wait() is a overloaded method of Object class one Sleep() is not overloaded method method
is wait() and one is wait(int milliseconds)
Wait() method only works in synchronized block Sleep() can work in synchronized as well as
asynchronized block
Thread Priority: Thread priority decide which thread execution priority or starting priority means when we have
multiple threads and when we want to start then we can decide starting or thread execution priority as per our
choice for that purpose we have facility called as thread priority
if we want to apply priority on thread we have void setPriority(int priority) method of Thread class.
Syntax:
void setPriority(int priority): this method accept integer as parameter as thread priority
means Thread class provide some fix constant values to for thread priority
0 ,5 and 10 - 0 stands for min priority , 5 stands for norm priority and 10 stands for max priority
means thread contain three static and final variable of type integer which work as thread priority constant
class Thread
{
public static final int MAX_PRIORITY=10;
public static final int MIN_PRIORITY=0;
public static final int NORM_PRIORITY=5;
}
Note: these are the fix priority values provided by java to us but user can provide thread
priority value between 0 to 10 as per his choice in setPriority() method.
Example
package org.techhub;
import java.awt.datatransfer.SystemFlavorMap;
class A extends Thread
{ public void run() {
try {
for(int i=1;i<=5;i++) {
System.out.printf("First =%d\n", i);
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.printf("Second =%d\n", i);
Thread.sleep(1000);
}
}catch(Exception ex) {
System.out.println("error is "+ex);
}
}
}
public class ThreadPriorityApplication {
public static void main(String[] args) {
B b1 = new B();
A a1= new A();
a1.setPriority(Thread.MIN_PRIORITY);
b1.setPriority(Thread.MAX_PRIORITY);
a1.start();
b1.start();
}
}
Note: Every program has a default thread called as main thread and it is started by JVM at the time of program run
means when we execute java filename then JVM start new thread automatically internally called as main method and
assign default priority to main thread i.e normal priority shown in following code.
package org.techhub;
//java ThreadPriorityApplication - JVM - thread
public class ThreadPriorityApplication {
public static void main(String[] args) {
Thread t = Thread.currentThread();
String name=t.getName(); //return current thread name
System.out.println(name);
int priorityValue=t.getPriority();
System.out.println("Current priority of thread "+ priorityValue);
}
}
abstract class A{
}
class B extends A implements Runnable
{
}
Note: Runnable is marker interface in java
Marker interfaces means those interfaces has special run time environment provided by JVM called as marker
interface
File class: File class help us to access path of particular driver , create new folder , create new file ,
delete folder ,delete file, access all drive names from hard disk ,access drive list of system , see the total
space of driver , see the free space of drive etc
How to get DriverList from computer and its total size and free size
static File [] listRoots(): this method help us to fetch all drive list from computer.
long getTotalSpace(): this method help us to get total space of drive in bits
long getFreeSpace(): this method help us to get free space of drive in bits.
Source code
package
org.techhub; import
java.io.*;
public class FileHandlingApplication {
public static void main(String[] args)
{ File f[]=File.listRoots();
for(int i=0; i<f.length;i++) {
long
totalSpace=f[i].getTotalSpace(); long
freeSpace=f[i].getFreeSpace();
System.out.println(f[i]+"\t"+(totalSpace/1073741824)+" GB \t "+(freeSpace/1073741824)+" GB ");
}
}
}
Source code
Example package
org.techhub; import
java.io.*;
public class FileHandlingApplication {
public static void main(String[] args) {
/*File f = new
File("D:\\OCT2022\\JAVA\\resume"); boolean b1 =
f.exists();
if (f.exists()) {
System.out.println("folder already exist");
} else {
boolean b = f.mkdir();
if (b) {
System.out.println("Folder created ");
} else
{ System.out.println("Some problem is there.
}
}*/ ...............................................................................")
System.out.println(new
File("D:\\OCT2022\\JAVA\\resume12344445").exists()?"folder already exist":new
File("D:\\OCT2022\\JAVA\\resume12344445").mkdir() ? "Folder created ":"Some problem is there.
................................. ");
}
}
boolean isFile(): this method help check return path is file or not if path is file return true otherwise
return false.
boolean isDirectory(): this method help us to check path is folder or not if path is folder return
true otherwise return false.
package org.techhub;
import java.io.*;
public class FileHandlingApplication {
public static void main(String[] args) {
/*File f = new
File("D:\\OCT2022\\JAVA\\resume"); boolean
b=f.isDirectory();
if(b) {
System.out.println("path is folder");
}
else
{ System.out.println("path is not folder");
}*/
System.out.println(new File("D:\\OCT2022\\JAVA\\resume").isDirectory()?"path is folder":"path is
not folder");
}
}
boolean createNewFile(): this method help us create new file using File class and if file created
return true otherwise return false.
package org.techhub;
import java.io.*;
public class FileHandlingApplication {
public static void main(String[] args)throws IOException {
/*File f = new File("D:\\OCT2022\\JAVA\\resume\\test.doc");
boolean b =f.createNewFile();
if(b) {
System.out.println("File Created");
}
else
{ System.out.println("Some problem ............ ");
}*/
System.out.println((new
File("D:\\OCT2022\\JAVA\\resume\\test.doc").createNewFile())?"File Created":"Some
problem .................................... ");
}
}
1) Write or read data using text format:if we want to work notepad file, word file etc then we can use
format
2) Write or read data using a byte format: if we want to work with image, audio, video etc we can
use byte format.
if we want to work with text format we have two types of classes provided by java to us
1) Write class
2) Reader
Writer: Writer classes help us to write data in file using a text format.
Reader: Reader classes help us to read data from file using text format.
Writer is abstract class from java.io package which is parent of all write classes in java and which
contain some abstract method those help us to write data in file.
Following diagram demonstrate use of Writer class hierarchy
if we think about above diagram we have top most class name as Writer class and it is abstract class
which contain some abstract method those help us to write data in file using a some abstract method.
void write(String data,int index,int length): this method is used for write specified length of data in
file. String : this parameter is used for hold String means in this parameter contain complete character
arraydata.
int offset: this parameter is used for use index from data want to write
int length: indicate decide how much data we want to write in file.
void close(): this method help us to close the file.
Write Mode: write mode means if file is not exist then create new file and if file is exist then override
previous data of file and add new data at the end of file.
Append Mode: append mode means if file not exist then create new file and file is exist then
save previous content of file and add new content at the end of file.
Write Mode: write mode means if file is not exist then create new file and if file is exist then override
previous data of file and add new data at the end of file.
Append Mode: append mode means if file not exist then create new file and file is exist then
save previous content of file and add new content at the end of file.
Example: we want to write program to create file using a FileWriter class and store data in
Note: BufferedWriter contain newLine() method which is used for write data in file on new line.
Constructor of BufferedWriter class
BufferedWriter(Writer): BufferedWriter class accept as parameter to Writer class means we can
accept any child of Writer class in BufferedWriter constructor.
Methods of BufferedWriter class : BufferedWriter class can user all methods of Writer as well it
contain newLine() method which help us to add data on new line in file.
Example: we want to create file name as second.txt using BufferedWriter class and store data in file
on new line.
package org.techhub;
import java.io.*;
import java.util.*;
public class SaveDataUsingFileWriterApp {
public static void main(String[] args) throws IOException
{ Scanner xyz = new Scanner(System.in);
System.out.println("Enter data in file");
String data =
xyz.nextLine(); FileWriter
fw = new
FileWriter("D:\\OCT2022\\JAVA\\resume\\second.txt",true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.newLine();
bw.close();
fw.close();
System.out.println("Record Save Success. ................ ");
}
}
Reader class
int read(): this method is used for read single single character data from file and return -1 when file
has no data or file is end.
int read(char[]): this method can read complete character array data from file and return its length and
when file end or when file has no data return -1
int read(char[],int offset,int length): this method help us to read specified length of data from file
FileReader class
Constructor of FileReader class
FileReader(String path): this constructor can accept file path using a string format.
FileReader(File path): this constructor can accept file path using a file class reference
package org.techhub;
import java.io.*;
public class ReadFileApp {
public static void main(String[] args) throws IOException,InterruptedException{
FileReader fr = new FileReader("D:\\OCT2022\\JAVA\\resume\\second.txt");
int data;
while((data=fr.read())!=-1) {
char ch=(char)data;
System.out.print(ch);
Thread.sleep(100);
}
}
}
BufferedReader class: BufferedReader class is used for read data line by line from file
BufferedReader class provide readLine() method to us for read single single line data from file.
String readLine(): this method can read single single line data from file and if file is end return null value.
Stream classes help us to work with byte format data means if we want to work with image audio,video
etc we can use stream classes.
Basically there are two types of streams
1) OutputStream : OutputStream help us to write data in file using byte format
2) InputStream: InputStream help us read data from file using a byte format.
Now we want to discuss about OutputStream class
if we think about above diagram we have OutputStream class which is parent of all stream classes and it
is abstract class and it contain some abstract method those help us to write data in file using byte format.
FileOutputStream(String path): this constructor accept file path using a string format.
FileOutputStream(File path): this constructor can accept file path using a file class reference
FileOutputStream(String path,boolean mode): this constructor can accept file path using a string
format and set mode on file if we pass true then file can use append mode and if we pass false then file
can use write mode.
FileOutputStream(File path,boolean mode): this constructor can accept file path using file format
and set mode on file if we pass true then file can use append mode otherwise use write mode.
Example: we want to create program create file and store text data in it.
package org.techhub;
import java.io.*;
import
java.util.*;
public class StreamApplication {
public static void main(String[] args) throws IOException
,FileNotFoundException{ FileOutputStream fout = new
FileOutputStream("D:\\OCT2022\\JAVA\\resume\\s.txt");
Scanner xyz = new
Scanner(System.in);
System.out.println("Enter data in file");
String data=xyz.nextLine();
byte b[]=data.getBytes();
fout.write(b);
fout.close(); System.out.println("Success.
.............................................................. ")
;
}
}
InputStream class
if we think about above diagram we have InputStream and it is parent of all stream reading classes in
java and it is abstract class and it contain some abstract method those help us to read data from file
using byte format.
int read(): this method can read single single byte data from file
int read(byte[]): this method can read complete byte array data from file and return its length
int read(byte [],int offset,int length): this method can read specified length of data from file.
FileInputStream class
Constructor of FileInputStream class
FileInputStream(String path): this constructor can accept file path using a string format.
FileInputStream(File path): this constructor can accept file path using file class reference.
Example of FileInputStream
class package org.techhub;
import java.io.*;
import java.util.*;
public class StreamApplication {
public static void main(String[] args) throws IOException
,FileNotFoundException{ File f = new
File("D:\\OCT2022\\JAVA\\resume\\s.txt");
FileInputStream finf = new FileInputStream(f);
int data;
while((data=finf.read())!=-1) {
System.out.print((char)data);
}
}
}
Example
package org.techhub;
import java.io.*;
import java.util.*;
public class StreamApplication {
public static void main(String[] args) throws IOException ,FileNotFoundException{
FileInputStream finf = new FileInputStream("D:\\OCT2022\\JAVA\\banner.jpg");
FileOutputStream fout = new FileOutputStream("D:\\OCT2022\\CPP\\banner.jpg");
int data;
while((data=finf.read())!=-1)
{ fout.write(data);
}
fout.close();
finf.close();
System.out.println("Success.
............................................................... ")
;
}
}
Serialization and Deserialization
Serialization is process where we store object data in file and Deserialization is process where we read
object data from file
If we perform Serialization in Java then JVM encrypt object content and store in file
The major goal of serialization data security means when send your object data in network from one
machine to another machine or in file then JVM encrypt object content and store in file or send network
so if we want to perform Serialization in Java We have some following steps.
Syntax: void writeObject(Object): this method is used for write object data in file and store encrypted
format in file.
Example of
serializationpackage
org.techhub; import
java.io.*;
class Employee implements Serializable
{ private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name)
{ this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
}
public class SerializationApplication {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
FileOutputStream fout = new FileOutputStream("D:\\OCT2022\\JAVA\\emp.txt");
ObjectOutputStream oout = new ObjectOutputStream(fout);
Employee emp = new
Employee(); emp.setId(1);
emp.setName("ABC");
emp.setSal(10000);
oout.writeObject(emp);
oout.close();
System.out.println("Success");
}
}
Note: Serializable is marker interface in java.
5) close the file.
Deserialization: Deserialization is process where we read object data from file means serilizable
object only read by JVM using deserialization process.