0% found this document useful (0 votes)
17 views

Core Java All

The document provides an overview of Java programming, covering its object-oriented nature, key concepts such as classes and objects, and the process of creating, compiling, and running Java applications. It explains the Java Development Kit (JDK), the Java Virtual Machine (JVM), and how to handle user input using command line arguments and the Scanner class. Additionally, it discusses arrays, including one-dimensional, two-dimensional, and jagged arrays, along with examples of their usage.

Uploaded by

48Vedant Kadole
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Core Java All

The document provides an overview of Java programming, covering its object-oriented nature, key concepts such as classes and objects, and the process of creating, compiling, and running Java applications. It explains the Java Development Kit (JDK), the Java Virtual Machine (JVM), and how to handle user input using command line arguments and the Scanner class. Additionally, it discusses arrays, including one-dimensional, two-dimensional, and jagged arrays, along with examples of their usage.

Uploaded by

48Vedant Kadole
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 323

02-02-2023

/*
what is java ?

Java is object oriented language.

Q.what is object oriented ?

Object oriented is a concept of programming.


based on four pillars and seven features

pillar of oop

polymorphism
inheritence
abstraction
encapsulation

features

class
object
polymorphism
inheritence
dynamic binding
message passing
encapsulation and abstraction

how to create program in java

if we want to create program in java we have some


important steps.

1) Install JDK

Q.what is JDK ?

JDK stands for java development kit


JDK : jdk is group of applications or softwares which contain
some supporting softwares those help us to create and execute
java application
it contain compiler,JVM etc

Q.what is compiler ?

compiler is software or application which is used for convert


source code to byte code in java.

Q.what is byte code ?

byte code is machine understandable code or it is format


which easily convert in machine code with help of JVM

what is JVM ?
JVM stands for java virtual machine
it is application which convert your byte code in to machine code

Q.why java develope byte code ?

byte code is platform independent code

what is platform ?

platform indicate operating system.


platform indendent means we can execute byte code on any operating system
so java is platform independent language.

2) create sample application

we cannot create any program of java without class


means we must be write minimum single class in java.

syntax: access specifier class classname


{
public static void main(String x[])
{ write here logics
}
}

e.g public class First


{
public static void main(String x[])
{
System.out.println("good morning");
}
}
public class First :

here public is access specifier

what is access specifier

access specifier are some keywords which can apply restrictions


on class and class member

there are four types of access specifier in java


public,private,protected,deault

class : class is keyword for class declaration


First is classname and user can give any name to his class

public static void main(String x[]) : it is main function of java


same like as main function in c or cpp

String x[] : it is command line argument


command line is parameter present in main function of string array type
called as command line argument
System.out.println("good morning"): it is output statement of java same like as
printf() in c language.

meaning : System is class out is static reference of PrintStream class


System and PrintStream maintain HAS-A relationship between
them println() is overloaded method for display output on output screen.

if we want to code of java then you can use following editors


i)notepad,notepad++,wordpad,eclipse,spring tool suite etc

once we create program in java then we need to save it.


3) save application :
if we want to save program in java then save in bin folder
where jdk install and give classname and filename same
with .java extension.

once we create your program then you can compile it.

4) compile application
q.what is compilation ?

compilation is process where we convert source code to byte code in java

how to compile program in java

if we want to compile program in java then we have some important steps.


i) open command prompt
start menu --> open command prompt
ii) go where java file save

C:\Users\Admin>cd C:\Program Files\Java\jdk1.8.0_291\bin

C:\Program Files\Java\jdk1.8.0_291\bin>
iii) type command javac filename.java
javac OctNovFirst.java

when we compile java program successfully then internally java compiler


create new file automatically with extension of .class and in this file
contain your byte code.

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.

after compile program successfully we need to run program

5) run application :
if we want to run program in java then we have statement name as
java filename
e.g java OctNovFirst

WAP to calculate addition of two values


public class AddApp
{
public static void main(String x[])
{
int a=100,b=200,c;
c=a+b;
System.out.printf("Addition is %d\n",c);
}
}
if we think about above code we calculate addition of fix two numbers
but we want to accept input from keyboard and after that calculate addition

How to accept input from keyboard in java

if we want to accept input from keyboard we have two ways

i) using command line argument


ii) using Scanner class.

Command line argument

Q.what is command line argument ?

command line argument is infinite string array present in main function


as argument
means using command line argument we can accept infinite parameter input
first first input of command line is at position of zero index because it
is array.

public class AddApp


{
public static void main(String x[])
{
int a,b,c;
a=x[0]; //first input
b=x[1]; //second input
c=a+b;
System.out.printf("Addition is %d\n",c);
}
}
if we think about above code we have two errors
incompitable types.

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

how to solve this type of error in java


if we want to solve this type of error in java we have to use type casting

what is type casting

converting one type of data in to another type for speicified line called as type casting.

so as per our example we have to coonvert string to integer

how to convert String value to integer value

if we want to convert string value to integer value we have following statement

syntax: int variable =Integer.parseInt(String value);


as above statement indicate we have Integer class and its one static method name as
parseInt() which is used for convert string value to integer value.

float variable =Float.parseFloat(String)

for string to double


-
double variable=Double.parseDouble(String);
etc

public class AddApp


{
public static void main(String x[])
{
int a,b,c;
a=Integer.parseInt(x[0]); //first input
b=Integer.parseInt(x[1]); //second input
c=a+b;
System.out.printf("Addition is %d\n",c);
}
}

/*
Scanner class

Scanner class is used for accept


input from keyboard on new line.

steps to work with Scanner class

1) add java.util package in application

Q.what is package ?

package is a collection of classes


and interfaces in java.
it is like as header file in c language.

if we want to add package in program


we have import keyword.
syntax:
import packagename.* :
this statement indicate we can use all
member from package in application.

or
import packagename.classname :
this statement can use single member from package
in application.

Example:
import java.util.*;
or
import java.util.Scanner;

2) create object of Scanner class

Scanner ref =new Scanner(System.in);

e.g Scanner xyz = new Scanner(System.in);

3) use its method to work with Scanner

Scanner provide some inbuilt method to us


for accept input from keyboard

int nextInt(): this method help us to accept input of type


integer using Scanner

float nextFloat(): this method help us to accept input of


type float using Scanner

double nextDouble(): this method help us to accept


input of type double

long nextLong(): this method help us to accept input of


type long

short nextShort(): this method help us to accept


input of type short .

String nextLine(): this method help us to accept input of


type string

byte nextByte(): this method help us to accept input of type


byte etc

WAP to input two values from keyboard and


calculate its addition using Scanner class

import java.util.*; //step1


public class AdditionApp
{
public static void main(String x[])
{
Scanner xyz = new Scanner(System.in);//step2
int a,b,c;
System.out.println("Enter two values\n");
a=xyz.nextInt(); //step3
b=xyz.nextInt();
c=a+b;
System.out.printf("Addition is %d\n",c);

}
}

WAP to input two values consider first as base


and second as index and calculate its power.
import java.util.*; //step1
public class PowerApplication
{
public static void main(String x[])
{
Scanner xyz = new Scanner(System.in); //step2
int base,index,p=1;
System.out.println("Enter base and index");
base=xyz.nextInt(); //step3
index=xyz.nextInt();
for(int i=1; i<=index; i++)
{ p = p *base;
}
System.out.printf("Power is %d\n",p);
}
}
WAP to input name,id,per of student and display it
using Scanner class.
import java.util.*; //step1
public class StudentApp
{
public static void main(String x[])
{
Scanner xyz = new Scanner(System.in); //step2
String name;
int id;
float per;
System.out.println("Enter name of student");
name=xyz.nextLine();
id=xyz.nextInt();
per=xyz.nextFloat();
/*System.out.printf("Name is %s\n",name);
System.out.printf("Id is %d\n",id);
System.out.printf("Percentage is %f\n",per);*/

/*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

import java.util.*; //step1


public class AreaApp
{
public static void main(String x[])
{
Scanner xyz = new Scanner(System.in); //step2
float radius,area,PI=3.14f;
System.out.println("Enter radius of circle");
radius=xyz.nextFloat();
area=radius*radius*PI;
System.out.printf("Area of circle is %f\n",area);
}
}

WAP to input number and print fibonacii series


number of times as per number.
import java.util.*; //step1
public class Fibo
{
public static void main(String x[])
{
Scanner xyz = new Scanner(System.in); //step2
int limit,f1=0,f2=1,fib;
System.out.printf("Enter limit\n");
limit=xyz.nextInt();
System.out.printf("%d\n%d\n",f1,f2);
for(int i=1; i<=limit; i++)
{ fib=f1+f2;
f1=f2;
f2=fib;
System.out.printf("%d\n",fib);
}
}
}

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 ?

array is a collection of similar data type.

how to use array in java

if we want to use array in java we have two steps

1) declaration

syntax: datatype variablename[];

e.g int a[];//declaration

declaration always null because in java


array variable is not normal variable it
is reference or pointer.

2) memory allocation

memory allocation means we create memory block


for array by using a new keyword.
means in short we can say javva array is run time
array we can allocate its memory at run time
by using a new kewyord

syntax: variablename= new datatype[size];

import java.util.*; //step1


public class ArrayTestApp
{
public static void main(String x[])
{ Scanner xyz = new Scanner(System.in);//step2
int a[]=new int[5];
System.out.println("Enter five values in array\n");
for(int i=0; i<a.length; i++)
{
a[i]=xyz.nextInt();
}
System.out.println("display array values\n");
for(int i=0; i<a.length; i++)
{ System.out.printf("%d\n",a[i]);
}
} }
00-0-2023
/*
Two dimensional array in java

Two dimensional array is used for create matrix

how many ways to declare two dimensional array in java

if we want to declare the two dimensional array in java


we have following ways

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

Jagged Array is facility in java where we can create


different column list for every row.

1 2 3
4 5 6 7
8 9

Syntax of jagged array

datatype variablenamep[][]=new datatype[rowsize][];


variablename[rowindex]=new datatype[colsize];

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

initialization means we fix the value in array.

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

public class MatInitializationApp


{
public static void main(String x[])
{ int a[][] = new int[][]{
{1,2,3},
{4,5,6},
{7,8,9}
};
System.out.println("Display matrix");
for(int i=0; i<a.length; i++)
{
for(int j=0; j<a[i].length;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.printf("\n");
}
}
}
Example

public class MatInitializationApp


{ public static void main(String x[])
{ int a[][] = new int[][]{
{1,2,3},
{4,5,6},
{7,8,9}
};
int b[]=a[1];
for(int i=0; i<b.length; i++)
{ b[i]=b[i]+10;
}
System.out.println("Display matrix");
for(int i=0; i<a.length; i++)
{ for(int j=0; j<a[i].length;j++)
{ System.out.print(a[i][j]+"\t");
}
System.out.printf("\n");
}
}
}
Output:
1 2 3
14 15 16
7 8 9

what is anonymous array in java

anonymous array means array without reference called anonymous array.


int a[]=new int[]{10,20,30,40,50};
if we think about this code we have array with reference
i.e a

but we use the array

new int[]{10,20,30,40,50}

above code indicate anonymous array in java


because we not use reference with array in above code.

anonymous normally refer by programmer when they want to pass array


as parameter in function not use more than one time at funciton
calling point.

public class AnonymousArrayApp


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

show(new int[]{10,20,30,40,50});//calling point


}
public static void show(int m[])
{
for(int i=0; i<m.length; i++)
{ System.out.println(m[i]);
}
}
}
07-02-2023
/*
classes and object using java

Q.what is class ?

class is a combination of state and behaviour


or
class is a combination instance variable,
class variable,method,constructur,instance
intializer,static initalizer,and nested classes

instance variable: instance variable means


those variable declared as non static within
class called as instance variable.

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
}

method means function define within class called as method.

class A
{ int x; //instance variable
static int m; //classs variable or static variable
void show() //method
{
}
A() //constructor
{
}

{
instance initializer
}

static{
static initializer
}
}

Q.why use class or what is benefit of class

the major benefit of class is


1) ability to store different type of data
class is user defined data type means we can
store different type of data in class.

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

we can declare class only once and we can reuse it


more than one time for that you have to create its object.

Q.what is object ?

object is a block of memory where class data store


or object is instance of class which can hold all
class variables.

how to create object in java

classname ref=new classname();

e.g Employee e =new Employee();

here e is reference of Employee class and new Employee()


is real object.

once we create object of the class then we can reuse


it more than one time if we want to reuse any class
we have some important steps.
i) declare class
ii) define methods within class
iii) create object of class
iv) call its method using object.methodname()
now we want to use eclipse IDE for java development
purpose

steps to work with eclipse

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

if we want to create project in eclipse we have


following steps.

file --> new --> project --> java project -->


click on next button --> give project name
and click on finish

once we create project you get project at left


side of eclipse i.e project explorer
in project explorer we have
src folder we have to write all java classes
in that folder
so you have to create own package in src folder
if we want to create package in src folder you have
to right click on src --> select new option --->
select package option --> give package name
and click on next and finish.

after creating pakage you have to create class under


package
if we want to create under package we have
steps

right click on package -->new --> class -->


click on next --> give classname -->
click on finish button .

Q.what is diff between reference and object ?

reference is a variable which hold address of object


and object is block of memory where class data store.

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();

}
}

if we think about above code we have class name as


Square with two methods
i.e void setValue(int x) and void showSquare()

Square s1 =new Square(): here we have Square s1 is reference


of Square class and new Square() is actual object

s1.setValue(5); here we call method setValue(5) and pass


5 value as parameter to method
s1.showSquare(): this method can calculate square of number and
display it.

WAP to create class name as Power with with two function


void setValue(int base,int index)
int getPower()

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;
}
}

public class PowerApplication {

public static void main(String x[]) {


Power p = new Power();
Scanner xyz = new Scanner(System.in);
int base,index;
System.out.println("Enter base and index");
base=xyz.nextInt();
index=xyz.nextInt();
p.setValue(base, index);
int result = p.getPower();
System.out.println("Power is "+result);
}
}

WAP to create class name as Factorial with two fucntions


void setValue(int x): this function accept number as parameter
int getFactorial(): this function can
calculate factorial of number and return it at function calling
pointer
also we have one class name as FactorialApplication
with main method

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 {

public static void main(String[] args) {


Scanner xyz = new Scanner(System.in);
Factorial f =new Factorial();
int no;
System.out.println("Enter number");
no =xyz.nextInt();
f.setValue(no);
int result =f.getFactorial();
System.out.println("Factorial is "+result);

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 ?

Q.what happen if we not 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

int result = v.getSum();


System.out.println("sum is "+result);
}
}

what is diff between reference and object


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

why we need to use reference ?

if we want to use same object multiple time then we have to


use reference of object
as well as if we want to share object content in some another
class using a function then we need reference of the object.

what happen if we not use reference with object

if we not use reference with object then JVM


create new object every time.
and without reference object called as anonymous object
anonymous object can use only once in application
not more than one
JVM delete the anonymous object automatically when its line code
execution finish.

following code shows the implemention above statements

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

int result = new Square().getSquare()


if we think about statement we create new object in memory i.e second object
and we consider address of this object is 11000 using this object
we call function int getSquare() and in getSquare() function we have
logic return no*no but if we think internally as per memory allocation
here we use no from second object i.e 11000 but we stored 5 value no whose
object address is 10000 so getSquare() return result using no from 11000
address space i.e from second object and we not store value in second object
no variable and no variable type is integer so in java if we have any
instance variable of type integer its default value is 0
so getSquare() return no*no i.e 0*0 at function calling pointer
in function calling point we have int result=new Square().getSquare();
so result contain 0 value so we have output is 0

here we can say JVM create two different object of Square class

note: if we want to correct answer from above code i.e square of 5


is 25 so we have to use first object with two different
function i.e with setValue() and getSquare()
so it is possible by using reference with object

shown in following code

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);
}
}

if we think about above diagram we have statement


Square s = new Square() here we have reference variable name as
s and new Square() is a real object and in diagram we consider
new Square() has 10000 address location and we store this address
in reference variable s .
after that we have statement s.setValue(5) the meaning we call
setValue() function by address 10000 (note: if we use address of object
in direct we can use object content or variables) and we pass 5 as parameter
to local variable x in setValue(int x) and we initialize variable x
value in no variable which instance variable in our class
means we can say 5 value stored in 10000 address space which we have object
created in memory
again we have statement int result=s.getSquare() if we think we not use
new keyword with getSquare() like as previous example we use
s.getSquare() means we provide instruction to JVM we want to use previous
object whose address stored in reference variable s means we not interested
to create new object so when we call method
s.geSquare() then we have logic
int getSquare(){
return no*no;
} so this function use no variable from address space 10000 and we initialize
value 5 in no on 10000 address so this function return 5*5 result
so we get 25 as return value in resutl variable at function calling point

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.

Can we apply more than one reference on single object

yes we can apply more than one reference on single object


but there is possibility if we change object content using anyone
reference then object previous content may be lost
shown in following code and diagram
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);
Square s1=s;
s1.setValue(10);
int result=s.getSquare();
System.out.println("square is "+result);
}
}
above code generate result Square is 100 shown in following diagram
if we think about diagram we have statement
Square s = new Square() means here we have object in memory
new Square() whose address is 10000 considered in above diagram
and we store this address in reference variable s
again we have statement
s.setValue(5) means we store 5 value on 10000 address location
again we have statement Square s1=s; means we assign address of
reference variable s to reference variable s1 here we not use
new keyword so JVM not create new object in memory
we just initialize refernece of s to s1 means s1 also points to
object whose address is 10000 means we can s and s1 use the same address
means use same object
we have again one more statement name as s1.setValue(10) means we
pass 10 value to no who is stored in 10000 address location
means s1 override the 10 value in no variable on 5
as per rule of variiable no use the last existing value
again we have statement
int result =s.getSquare() means we call getSquare() method usinig address
10000 using reference varibale s so we get result is 10*10
so it is 100
means we can if we apply multiple referenece on single object
and if we try to change content of object using any one reference then
all references of that object get affected because object state or variables
or content get changed
and if we want to solve this problem in java we have object cloning concept
note: we will discuss this concept in Object class lecture
after inheritence chapter.

09-02-2023
how to pass array as parameter to function

if we want to pass array as parameter to the function we have to pass base


address of array to the function

Example: we want to create class name as ArraySum with two functions


void setValue (int a[]) : this function can accept array as parameter
int getSum () : this function can calculate sum of all elements from array and
return its sum at function calling point.

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

again we have statement for(int i=0; i<a.length;i++){ a[i]=xyz.nextInt(); }


means we store 5 values in array
after we have statemen s.setValue(a) means we call setValue() function of
Sum class and pass base address of array which we created
from main function to reference variable x mention in setValue() function
through the reference variable a from main function
means here we can say reference variable x and refernece variable a points
to same array which we created in main function
so we can say setValue(a) function work with call by referencence concept.
again we have statement in setvalue()function
void setvalue(int x[]){
a=x;
}
here a is instance variable in Sum class but it is reference of int a[] array
type so we again initialize base address of array in reference of a using
reference variable x means here again instance reference variable points to
same array which we created in main function
means here we can say we have three different references to single array
again we have statement in main method
int result = s.getSum() this function calculate the sum of all elements of
array which we created in main and calculate its sum and store in sum variable
and return from function defination to function calling in result variable
and display its result.

What will be output of given code


package org.techhub;
import java.util.*;
class Sum{
int a[],sum=0;
void setValue(int x[]) {
a=x;
}
void test() {
a[1]=500;
}
}
public class SumApp {
public static void main(String[] args) {
Sum s = new Sum();
int a[]=new int[] {10,20,30,40,50};
s.setValue(a);
s.test();
System.out.println("Display array");
for(int i=0; i<a.length;i++)
{ System.out.println(a[i]);
}
}
}
diagram for above code with memory

if we think about above diagram we have int a[]=new int[]{10,20,30,40,50}


here we created array at run time and we initialize fix values in it.
again we have Sum s = new Sum() means we create object of Sum class
and we have statement s.setvalue(a); means we pass bas address of array
using reference variable to function setValue(int x[]) and
we have logic in void setvalue(int x[]){ a=x } means using this
local variable we initialize reference of array which we created in main
function to instance varible a which we have declared in Sum class.
again we have void test() and in void test() function we have logic
void test(){
a[1]=500;
} means reference variable a of Sum class points to base address 1000
when we call statement a[1] means base address+index*size so as per our
exmaple it is 1000+1*4 = 1004 means a[1] points to base 1004
so we stored value 500 on 1004 address location but previously
20 value present on this address so we override 500 on 20
this process happen when we call s.test() function in main function
after calling s.test() we have for loop and we print all values of
array in main function so we get output
10
500
30
40
50
So we perform change in test() function but we get reflection in main
function because we use call by reference technique in java when we
pass array as parmaeter to any function then it work with call by
Reference concept.

Method with variable argument concept in java


Method with variable argument is facility in java where we can
pass infinite parameter to function it is denoted by ... in function.
Syntax: return type functionname (datatype ...variable name)
{ //write here your logics
}
... indicate we can pass infinite parameter to function.
e.g class Sum
{ void calSum(int ...x)
{
}
}
if we think about function void calSum(int ...x) meaning we can
pass infinite values of type integer to function

Note: sum time we cannot predict how much values need a function as
parameter of same type then we can use this approach.

Example : shown in following diagram.


Example shown in following diagram.

if we want this type of implemention in code using a some


specified function then we cannot decide the parameter list
so we can use method with variable argument
e.g suppose if we define function void calSum(int x,int y )
means we can pass only two parameters to this function
but as per our diagram it is not feasible solution
so as per our diagram we manage code like as
void calSum(int ...x)
this function indicate we can pass infinite parameter to
calSum() of type integer
note: ... (tripper dot) is internally dynamic array created by
JVM at run time shown in following code and diagram

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

if we think about above code we have function


void setValue(int ...x)
{
}
when we call this function from main function
s.setValue(10,20,30,40,50); here we pass these values as individual
parameter but internally JVM collect all parameters and convert it
in integer array in setvalue(int ...x) function as per our example
shown in above diagram.
if we work with method with variable arguments we have some important
rules
provided by java to us .

i) ... must be left side of variable and right hand side of data type
means

void setValue(int x...) : this is invalid declaration of


variable argument and compiler may be generate compile time error to us
so you must be write like as void setValue(int ...x)

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

iii) if we have some simple values in function or some simple argument


in function and variable argument in function then variable argument
must be last parameter in function.

void calSum(String name,int ...x)


{
}
here we not use ... with name variable so we can say it is normal
parameter and we use ... with x so we can say it is variable argument
and we mention variable argument as last parameter so it will not generate
compile time error to us it is allowed means when we call this type of function
then initialize we can giveparameter to normal variable and rest all parameters
should be pass tovariable argument means as per our exmaple if we call
calSum() we pass first parameter as string and remaining all infinite parameter
to intege r s.calSum("Ram",10,20,30,40,50);
shown in following code.

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) {

Stat s = new Stat();


System.out.println("X is " + s.x);
System.out.println("A is " + Stat.a);
System.out.println("A is "+s.a);
}
}
Above code generate output x is 200 A is 100 and A is 100 in above we use
static variable by class name also and by reference name also or by object also.

3) Static variable allocate its memory before creating object of class in


permanent generation section of memory or after JDK 1.8 in Meta Section of
Memory and instance variable allocate its memory after creating object of class
in heap section

Q. What is permanent generation section of Memory (permgen)


Permanent generation section is part of JVM memory which is specially design
for hold the static variable, string pool constant, class meta data etc. So static
variable allocate memory before creating object of class so we can use it
without object and can use class name.
but instance variable allocate its memory after object so we cannot use instance
variable without object.

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 want to calculate the life of instance variable we have to calculate life of


object so we should have to know
Q. whenever object present in memory?
when object not use any reference then JVM delete object memory
automatically means object present in memory when object use by some
reference and instance variable stored in object means when JVM delete
memory of object then JVM indirectly delete instance variable but static
variable not present in memory so they cannot delete when object is deleted by
JVM so we can say static variable can present in memory when ever
programming running and another reason static variable life is through the
program because static variable use by multiple object so when JVM delete
some object but static must be present for remaining objects
Above concepts explain conceptually in given diagram

Scenario for instance variable and static variable


Suppose consider we have class name as Employee with four field id,name,sal
and compName
so here we want to design compName as static variable and id,name,sal as
instance variable because suppose if we consider we have three employee so
every employee has different name, different id and different salary but if three
employee work in same company so they use common name of company so if
we think one employee is equal with one object then we need to create different
copy of name, id and salary with every object so we need to declare these three
variable as instance variable but compName should be common in all employee
means company name should be common in all objects so we have to declare it
as static
Now we want to write code for it.

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) {
}
}

2) Cannot declare local variable as static


Note: if we declare local variable as static then compiler will generate compile
time error to us.
Example:
package org.techhub;
class LVar{
int no;
void setValue(static 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

Following code resolve compile time error of local variable


package org.techhub;
class LVar{
void show() {
int no=0;//no default values.
System.out.println("No is "+no);
}
}
public class LocalVarApp {
public static void main(String[] args) {

}
}
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

Q. can we use this with a static variable?


Yes we can use this reference with a static variable because static variable can
call by class name as well as object also so we can use this reference with a
static variable.
package org.techhub;
class LVar{
static 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);
}
}
Q. can we use this reference within a static function?
No we cannot use this reference with a static function
Q. if we use this with static variable then why not use with static function?
Suppose consider if we declare static variable and if we not create object of
class then we can use it by class name but if not create object then there is no
reference means there no this reference also.
Means this reference active only with current object but if not create object then
this not created internally.
Example:
package org.techhub;
class LVar{
static int no=100;
}
public class LocalVarApp {
public static void main(String[] args) {
System.out.println(LVar.no);
}
}
if we think about above code we have class name as LVar with static variable
no and we use here no in main using class name i.e LVar.no so JVM not found
any object so there is no this reference also.
we have one more scenario if we create object of class and use static variable
but when we create object of class then JVM also find reference means this can
find reference of current object so there not problem.

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 {

public static void main(String[] args) {


Scanner xyz = new Scanner(System.in);
System.out.println("Enter name id and salary of employee");
String name=xyz.nextLine();
int id=xyz.nextInt();
int sal=xyz.nextInt();
Employee emp = new Employee();
emp.setId(id);
emp.setName(name);
emp.setSal(sal);
System.out.println (emp.getId ()+"\t"+emp.getName()+"\t"+emp.getSal());
}
}
It work like as Container means if we want to pass bulk data of different type to the function then
passing single single parameter is not good approach so better way we can store all parameter in
single object and pass object as parameter
So standard is object must be work with setter and getter method called as pojo

Now we want to create program without pojo class


Now we want to class name as Company with two methods void addNewEmployee() and
showEmployee()
Methods description given below
void addNewEmployee(String name,int id,int sal,String address,String email,String contact): this
method can accept employee details
void showDetails(): this method can display employee details.
Now we want to write code for above scenario
package org.techhub;
class Company
{ private String name;
private String email;
private String contact;
private String address;
private int id;
private int sal;
void addNewEmployee(String name,int id,int sal,String address,String email,String contact)
{
this.name=name;
this.email=email;
this.contact=contact;
this.sal=sal;
this.address=address;
this.id=id;
}
void showDetails() {
System.out.println(name+"\t"+email+"\t"+contact+"\t"+sal+"\t"+address+"\t"+id);
}
}
public class CompanyApplication {

public static void main(String[] args) {


Company c = new Company();
c.addNewEmployee("ABC",1, 10000,"PUNE", "[email protected]", "12234555555");
c.showDetails();
}
}
If we think about above code we have class name as Company and two functions first
addNewEmployee () with six parameter and showDetails () which display details of employee.
The major limitation of this code is if we think about addNewEmployee() it contain six parameter so
when we want to call this function we should to remember the six parameter data type as well as its
sequence at function calling point
Example : as per our example we created object Company in main method and we call
addNewEmployee() by company object like as
c.addNewEmployee(“ABC”,1,10000,”[email protected]”,”PUNE”,”12234555555”); here we
have to know first parameter is string,second is integer,third is integer,fourth string,fifth is string and
sixth string so it is very complicated or tedious task in real life if your function contain 50 parameters
so it is not possible to remember details of every parameter as well as its sequence so better way we
can store all parameter in single object and pass object as parameter to function so we not need to
remember type and sequence of every parameter in this case pojo class comes in picture.

Example with pojo class for resolve above problem


package org.techhub;
class Employee{
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private String contact;
private String address;
private int id;
private int sal;
}
class Company
{ Employee employee;
void addNewEmployee(Employee employee) {
this.employee=employee;
}
void showDetails() {
String name=employee.getName();
String email=employee.getEmail();
String contact=employee.getContact();
int id=employee.getId();
String address=employee.getAddress();
int sal=employee.getSal();
System.out.println(name+"\t"+email+"\t"+contact+"\t"+id+"\t"+address+"\t"+sal);
}
}
public class CompanyApplication {

public static void main(String[] args) {


Company c = new Company();
Employee emp = new Employee();
emp.setId(1);
emp.setName("ABC");
emp.setSal(10000);
emp.setAddress("PUNE");
emp.setEmail("[email protected]");
emp.setContact("12333333");
c.addNewEmployee(emp);
c.showDetails();
}

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;

public class BillingApplication {

public static void main(String x[]) {


Shop s =new Shop();
Product p = new Product();
p.setId(1);
p.setName("ABC");
p.setPrice(50);
s.addNewProduct(p);
s.show();
}
}
Example of player information using POJO class
package org.techhub.team;
public 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;


}
package org.techhub.team;
public class Team {
Player player;
public void addNewPlayer(Player player) {
this.player = player;
}
void showPlayerDetails() {
System.out.println(player.getName() + "\t" + player.getId() + "\t" + player.getRun());
}
}
package org.techhub.team;
public class TeamApplication {
public static void main(String[] args) {
Team t = new Team();
Player p =new Player();
p.setId(1);
p.setName("ABC");
p.setRun(10000);
t.addNewPlayer(p);
t.showPlayerDetails();
}
}

Q.what will be output of given code?


class A
{ int no;
void setNo(int no) {
this.no=no;
}
int getNo() {
return no;
}
}

class B
{ void setA(A a1) {
a1.no=200;
}
}

public class TestMCQAPP {


public static void main(String[] args) {
A a2 = new A();
a2.setNo(10);
new B().setA(a2);
System.out.println(a2.getNo());
}
}
Above code explain in following diagram

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.

How to create array of objects in java


If we want to create array of objects in java we have to first create array of references and after we can
create array of objet.
Syntax:
classname ref[] = new classname[size];// this is array of reference.
for(int i=0; i<ref.length; i++)
{ ref[i] = new classname(); //array of objects.
}

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 .

Example of Array of objects


package org.techhub.mcq;
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 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.

Following Examples show how constructor call

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 ConsApplication {


public static void main(String[] args) {
A a1 = new A();
}
}
Note: if user not declare constructor in class then compiler add new constructor
automatically in class called as implicit constructor.

2) Parameterized constructor: if we pass parameter to constructor called as parameterized


constructor when we pass parameter to constructor then we have to pass parameter where we
create object of class.

Source code with Example


package org.techhub;
import java.util.*;
class Square
{ int no;
Square(int no){
this.no=no;
}
int getSquare() {
return no*no;
}
}
public class SquareApplication {
public static void main(String[] args) {
Scanner xyz = new Scanner(System.in);
System.out.println("Enter number");
int no=xyz.nextInt();
Square s1 = new Square(no);
int result = s1.getSquare();
System.out.println("Square is "+result);
}
}
Example : Now we want to create program create class name as ArraySum with
parameterized constructor and pass array as parameter to constructor and define one method
in class name as int getSum() this function can calculate sum of all elements of array and
return its sum at function calling point.
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.getSa
l());
}
}
public class CompanyClassApplication {

public static void main(String[] args) {


Employee emp = new Employee();
emp.setId(1);
emp.setName("ABC");
emp.setSal(1000);
Company c = new Company(emp);
c.show();
}

}
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 {

public static void main(String[] args) {


Employee emp = new Employee("ABC",1,1000);
Company c = new Company(emp);
c.show();
}
}
if we think about main method we create Employee emp = new Employee(“ABC”,1,1000);
means here we create object of Employee class and store its reference in emp and after that
we pass emp reference in Company class constructor as parameter but if we want to optimize
code you can create direct anonymous object in Company class class constructor as
parameter so we not need to Employee emp = new Employee() before company constructor
calling
means you can manage code Company c = new Company(new Employee(“ABC”,1,1000));
so this statement is equal Employee emp = new Employee(“ABC”,1,1000); Company c=new
Company(emp); shown in following code.
Source code with example
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 {
public static void main(String[] args) {
Company c = new Company(new Employee("ABC",1,1000));
c.show();
}
}
if we think about above code we create object of Company c = new Company(new
Employee("ABC",1,1000)) and we store reference of Company object in reference variable c
and after that we call c.show() method. Instead of this approach here we want to call only
one method of Company class here i.e show() so when we want to call only one method using
any object then we not need to use reference you can use short using anonymous object
shown in following 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.getSa
l());
}
}
public class CompanyClassApplication {
public static void main(String[] args) {
new Company(new Employee("ABC",1,1000)).show();
}

}
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.

Now we want to perform constructor chaining using this () constructor


When we use this constructor then execution of constructor maintain in the form of stack.
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.

Example with source code


package org.techhub.chaining;
class A {
A() {
this(5);
System.out.println("I am default constructor");//3
}
A(int x) {
this(5.5f);
System.out.println("I am integer constructor " + x);//2
}
A(float x) {
System.out.println("I am float constructor " + x);//1
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
Output
I am float constructor 5.5
I am integer constructor 5
I am default constructor

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

1) Constructor cannot have return type


If you try to give return type to constructor then constructor consider as method means in
short we can say in java method name and constructor name may be same.
Example
package org.techhub.chaining;
class A {
void A() {
System.out.println("I am default constructor");
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
a1.A();
}
}
If we think about above code we have void A () statement in A class here we define function
with return type void means here we can say it is a function not constructor so we need to call
it using object name.
2) Constructor cannot support to recursion
because constructor call when we create object of class but recursion say we need to perform
calling within same definition means for recursion we required stack calling but for
constructor we required object for calling so this major reason constructor not support to
recursion.
Following code shown meaning of above concept
package org.techhub.chaining;
class A {
int count=0;
A() {

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.

4) We cannot override constructor


Means we cannot redefine parent class constructor again in child class and it we try to
perform overriding with constructor then it will generate compile time error to us
package org.techhub.chaining;
class A {
int count=0;
A() {
System.out.println("I am constructor");
}
}
class B extends A //here A is parent and B is child
{ A(){
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
if we think about above code we have two classes one is A as parent and B as child and we
have default constructor in class A and we try to override it in class B so it is not possible so
this is main reason compiler will generate compile time error to us
Q. Why constructors not override?
When we override a constructor then it will match its name child class and parent constructor
and child class name cannot match with each other 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.

1) What is Singleton Class?


Singleton class means class cannot create its more than one object in single application called
as Singleton class
Basically Singleton is a design pattern

Q. what is design pattern?


Design pattern are the some industry standard which is used for cover limitation of OOP.

Basically there are three types of design pattern in core java


i) Creational design pattern
ii) Structural design pattern
iii) Behavioral design pattern

How to Create Singleton class in java


If we want to create singleton class in java we have some following steps.
I) Declare class with private constructor
class ABC{
private ABC(){
System.out.println(“I am singleton class”);
}
}
ii) Declare on private static reference of same class in it.
class ABC{
private static ABC ab;
private ABC(){
System.out.println(“I am singleton class”);
}
}

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();
}
}

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.

Source code Example


package org.techhub;
class Value
{ int a,b;
void setValue(int x,int y) {
this.a=x;
this.b=y;
}
}
class Add extends Value
{
int getAdd() {
return a+b;
}
}
class Mul extends Value
{
int getMul() {
return a*b;
}
}
public class InheritenceApplication {
public static void main(String[] args) {
// TODO Auto-generated method stub
Add ad = new Add();
ad.setValue(10,20);
Mul m = new Mul();
m.setValue(5, 3);
System.out.println("Addition is "+ad.getAdd());
System.out.println("Multiplication is "+m.getMul());
}
}

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.

Output of above code


package org.techhub;
class A
{ A(int x){
System.out.println("I am parent constructor "+x);
}
}
class B extends A
{ B(){
super(100);
System.out.println("I am child constructor");
}
}
public class ConsWithInheritenceApp {
public static void main(String[] args) {
B b1 = new B();
}
}
Note: super () constructor must be first line of code in child class constructor if we not use super() in
first line of child class constructor then we get compile time error shown in following code.
package org.techhub;
class A
{ A(int x){
System.out.println("I am parent constructor "+x);
}
}
class B extends A
{ B(){
System.out.println("I am child constructor");
super(100);
}
}
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 use super() constructor in
second line of code in child class and it is not allowed so compiler generate error to us at compile
time.

Q. can we use this() and super() at same time?


No we cannot use this() and super() at same time because this() and super() must be first line of code
in calling constructor and it is not possible to give single line for two different statements so compiler
will generate compile time error to us if we use this() and super() at same time shown in following
code.
package org.techhub;
class A
{ A(int x){
System.out.println("I am parent constructor "+x);
}
}
class B extends A
{ B(){
super(100);
this();//need first line but user write on second line so generate compiler time error
System.out.println("I am child constructor");

}
}
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.

Q. what is method overriding?


Method overriding means if we define method in parent class and redefine same method again in
child class called as method overriding shown in following code.
class A
{ void show() {
System.out.println("I am show method in parent class");
}
}
class B extends A
{ void show() {
System.out.println("I am show method in child class");
}
}
If we think about above code we have two classes one is A and one is B and A is parent class and B is
child class and we void show() method in class A and again we define void show() in class B means
we define same method in parent and same method again in child so we can say show() is overridden
method.
Note: in the case of method overriding if we create object of child class and call overridden method
then by default child logic get executed shown in following code.
Source code
package org.techhub;
class A
{ void show() {
System.out.println("I am show method in parent class");
}
}
class B extends A
{
void show() {
System.out.println("I am show method in child class");
}
}
public class MethodOverridingApplication {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}
Output:
I am show method in child class
Code description
if we think about above code we created object of class B which is child class and call overridden
method name as show() using b1.show() statement then we get logic from child class method or child
version of show() method means here we can say child version override its logic on parent version

Q. is method overriding is beneficial or not?


Its depend on scenario and requirement of application some time it is beneficial but some not

Q. why use method overriding?


There are two major benefit of method overriding.
1) To customize parent logics in child class
2) To achieve dynamic polymorphism.

To customize parent logics in child class


Some time if child class want to modify parent logics in future as per his requirement then he can take
method signature from parent class and write own logics in it as per his requirement.
Suppose Consider we want to design application for Calculator and we have three classes name as
Value Add and Mul. Here Value class work as parent class and Add and Mul classes work as child
classes so Value contain two methods void setValue(int x,int y) and int getResult() here we can
Calculator can generate result using getResult() method but result vary from child to child means Add
class can generate different for value and mul class can generate different result for value so here we
have to override getResult() method in Add class and In Mul class and we can customize its result
logics shown in following code.
Example with source code
package org.techhub;
class Value
{ int a,b;
void setValue(int x,int y) {
a=x;
b=y;
}
int getResult() {
return 0;
}
}
class Add extends Value
{
int getResult() {
return a+b;
}
}
class Mul extends Value
{
int getResult() {
return a*b;
}
}
public class CalculatorApplication {
public static void main(String[] args) {
Add ad= new Add();
ad.setValue(5, 4);
int result=ad.getResult();
System.out.println("Addition is "+result);
Mul m = new Mul();
m.setValue(5,4);
result =m.getResult();
System.out.println("Multiplication is "+result);
}

}
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.

Example with compile time error in overriding


class A
{ void show() {
}
}
class B extends A
{ int show() {

}
}
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.

Q. if we define parent method as protected and can we override it as public?


yes it is possible because in overriding public access specifier has more preferences than protected
and default so if we define parent as protected or default and if we override it as public in child then
compiler not generate any compile time error it is allowed shown in following code.
class A
{ protected void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ public 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 two classes name as A and class B in class A we have method
protected void show() and in class B we override it as public void show() so it is allowed.

Q. can we define parent method as public and override as protected?


No it is not allowed because public has higher preferences than protected and default so if we parent
method is public then at the time of overriding child must be override it as public and if child try to
override it as protected or default then compiler will generate compile time error to us .
package org.techhub;
class A
{ public void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ protected 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();
}
}
Above code generate compile time error because we have class A is parent class and it contain one
method public void show () and we try to override as protected void show () in child class so it is not
allowed compiler will generate compile time error to us.

Q. can we define parent method as default and override as protected?


Yes it is allowed because default has less preference than protected and public so if we define parent
method as default and if we override it as public in child class then there is no problem it acceptable.
but vice versa not allowed means parent method protected and child method default not allowed.
class A
{ void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ protected 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 two classes name as A and class B in class A contain void
show() means we not use any access specifier with show() in parent so it work with default access
specifier and we override it as protected in child class so it allowed.

Q. can we override private method?


if we define parent method as private and if we define same method again in child class then it is not
method overriding means child define own self method same name as parent class name
private cannot override.
package org.techhub;
class A
{ private void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ void show() {
super.show();
System.out.println("I am show in child");
}
}
public class OverridingRulesApp {
public static void main(String[] args) {
new B().show();
}
}
above code generate compile time error to us because we try to show() method using super keyword
and show() is private in parent class and it is override or accessible in child so we cannot call it using
super keyword if we remove super.show() then there is no compile time error but there is overriding
also child class define own self method in its body.

Q. Can we override static method?


Yes we can override a static method
package org.techhub;
class A
{ static void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ static void show() {
System.out.println("I am show in child");
}
}
public class OverridingRulesApp {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}
if we think about above code we have two classes name as A and B in class A contain static void
show() and in class B contain static void show() again so we can say it is overriding and when we
create object of class B and call b1.show() then child version get executed automatically.
Note: Normally we override static method for method hiding purpose.
Q. what is method hiding in java?
Method hiding means if we override static method and if we create reference of parent class using
child object then parent logic get executed using parent reference called as method hiding.
package org.techhub;
class A
{ static void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ static void show() {
System.out.println("I am show in child");
}
}
public class OverridingRulesApp {
public static void main(String[] args) {
A b1 = new B();
b1.show();
}
}
Output: I am parent show
If we think about above code we have statement A b1 =new B() means here we have reference of
parent class name as b1 and we have object of child class name as new B() and we call b1.show() here
we get parent logic means here we hide the child logic called as method hiding.

Q. can we override final method?


No it is used for avoid method overriding in java
Normally if parent class want secure its logic from child modification by using overriding technique
then we can define parent method as final.

Q. Can we inherit final method?


Yes you can inherit final method
Inheritance we can reuse parent logic in child class and overriding means we can modify parent logic
in child class
Means final method can use by child class but cannot modify by child class using overriding so we
can say we can inherit final method.

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.

Abstract class and Abstract method

Q. what is abstract class and abstract method in java ?


Abstract class means class cannot create its object and abstract method means method cannot logics.

How to declare abstract class and abstract method in java


If we want to declare abstract class and abstract method in java we have abstract keyword
Syntax:
abstract class classname {
abstract return type function name(arguments);
}
e.g abstract class Vehicle{
abstract void engine ();
}
Q. what is use of abstract method?
The major use of abstract method is
1) To achieve abstraction:
2) To achieve dynamic polymorphism.
Q. what is abstraction?
Abstraction means to hide implementation detail from end user at designing level called as abstraction
means in short we can say in the case of abstraction we not provide any implementation of method in
parent class just we provide its proto type or template in parent class and we write its logic in child
class as per need of child.
Suppose consider if we think about Vehicle then we can say every Vehicle has engine () but we
cannot predict its design it is vary from Vehicle to Vehicle means if we think about Bike then Bike
has different engine capacity and if we think about Car then Car has different engine() capacity but
Bike and Car both are Category of Vehicle so we Can say Vehicle need engine with different design
so it is example of abstraction.
abstract class Vehicle{
abstract void engine ();
}
class Bike extends Vehicle
{ void engine(){
System.out.println(“1000 CC”);
}
}
class Car extends Vehicle
{ void engine(){
System.out.println(“100 CC”);
}
}
If we want to work with abstract class and abstract method in java we have some important points.
1) Abstract class cannot create its object
abstract class A{
}
public class AbstractionApp {
public static void main(String[] args) {
A a1 = new A();
}
}
Above code generate compile time error to us because we try to create object of abstract class A.
2) If method is abstract then class must be abstract
The meaning is we cannot declare abstract method in non abstract class and if we try to declare it then
There is compile time error.
class A
{ abstract void show();
}
public class AbstractionApp {
public static void main(String[] args) {
}
}
Above code generate compile time error to us because we have class A and it is not abstract method
and we declare abstract void show () in it so it will generate compile time error to us.
So if we avoid this problem we must be declare class A as abstract shown in given code.
package org.techhub;
abstract class A
{ abstract void show();
}
public class AbstractionApp {
public static void main(String[] args) {
}
}
Q. can we declare non abstract method in abstract class?
Yes we can declare non abstract method in abstract class if we declare some abstract and some non
abstract method in class then class mark as concrete class shown in following code.
package org.techhub;
abstract class A
{ abstract void show();
void display() {
System.out.println("I am display method");
}
}
public class AbstractionApp {
public static void main(String[] args) {
}
}
if we think about above code we have abstract class A with two methods abstract void show() and
void display() here in class A one method is abstract and one method is non abstract so we can say
class A is concrete class.

Q. can we write logic of abstract method?


No we cannot create logic of abstract method where we declare it but if we want to write logic of
abstract method we have to inherit abstract class in some another non abstract class and override
abstract method and we can write its logic.
Example:
package org.techhub;
abstract class Vehicle
{ abstract void engine();
}
class Bike extends Vehicle
{ void engine() {
System.out.println("1000 CC");
}
}
class Car extends Vehicle
{ void engine() {
System.out.println("100 CC");
}
}
public class AbstractionApp {
public static void main(String[] args) {
Car c = new Car();
c.engine();
Bike b = new Bike();
b.engine();
}
}
In above example we have abstract class Vehicle with abstract method engine () and we have two
child classes name as Bike and Car and override engine () method in Bike class and engine () method
in Car class and write its logic.
The benefit we can customize abstract method logic in every child class as per our need by using
method overriding technique as well as we can achieve dynamic polymorphism using overriding
technique
Note: we will discuss dynamic polymorphism later in this chapter.
Q. Can we declare abstract method as static?
No we cannot declare abstract method as static and if we try to declare it then we get compile time
error
abstract class Vehicle
{static abstract void engine();
}
If we think about above code we get compile time error to us because we declare abstract method as
static and it not possible.
Q. Why we cannot declare abstract method as static?
Because static method work with compile time polymorphism and abstract method work with
dynamic polymorphism using overriding
The another reason static method allocate memory before creating object of class and for method
memory allocation it must have definition and abstract method cannot have definition so cannot
declare abstract method as static.
Q. can we declare abstract method as final?
No we cannot declare abstract method as final and if we try to declare then compiler will generate
compile time error to us shown in given code
abstract class Vehicle
{ final abstract void engine();
}
If we think about above code we declare abstract method as final and it is not allowed so compiler
will generate compile time error to us.
Q. Why we cannot declare abstract method as final?
Because final method cannot override in child class but abstract method must be override in child
class
And it is opposite behavior of final and abstract so we can not declare abstract method as final.
Q. can we declare abstract method as private?
no we cannot declare abstract method as private and if we try to declare then compiler will generate
compile time error to us.
abstract class Vehicle
{private abstract void engine();
}
Above code generate compile time because we declare abstract method as private.
Q. why we cannot declare abstract method as private?
Because private method cannot support to inheritance as well as overriding but abstract method
cannot work without overriding and without inheritance so it is not possible.
Q. Can we use abstract keyword with variable or can we declare variable as abstract?
No we cannot declare variable as abstract and if we declare it we get compile time error
abstract class Vehicle
{ abstract int a=100;
abstract void engine();
}
Q. why we cannot declare variable as abstract
because the major goal of abstract keyword is achieve abstraction but we cannot achieve abstraction
using variable because variable normally refer for storing data so we cannot use abstract keyword
with variable.
Note: if abstract class contains more than one abstract method then all method must be override
where abstract class gets inherited if we not override all methods then compiler will generate compile
time problem or error to us if we not required abstract method then we must be override it as blank.
abstract class Vehicle
{ abstract void engine();
abstract void feature();
}
class Car extends Vehicle
{ void engine() {
System.out.println("1000 CC Required");
}
}
if we think about above code we get compile time error because we have abstract class Vehicle and
it contain two methods abstract void engine () and abstract void feature () but we override only one
method in Car class i.e. engine () but rule is must be override all abstract methods from parent to child
and we override feature () then we get compile time error.
So resolve this problem we have two approaches
1) Define method as blank in child class if we not required
abstract class Vehicle
{ abstract void engine();
abstract void feature();
}
class Car extends Vehicle
{ void engine() {
System.out.println("1000 CC Required");
}
void feature() {
}
}
if we think about above code we define feature () as blank so it is requirement of abstract class his all
method must be define but it is not good approach so we have one more option we can use adapter
class
2) Use adapter class
Q. what is adapter class?
Adapter class is intermediate class which contain all blank definition of abstract class methods and
which is responsible for provide specific method to abstract child class called as adapter class.
Example of Adapter class
package org.techhub.adapter;
abstract class ABC {
abstract void s1();
abstract void s2();
abstract void s3();
}
class ADP extends ABC {
@Override
void s1() { // TODO Auto-generated method stub
}
@Override
void s2() {
// TODO Auto-generated method stub
}
@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

Q. what is dynamic polymorphism?


Dynamic polymorphism means if we bind functionality with object at program run time called as
dynamic polymorphism.
If we want to achieve dynamic polymorphism we have to declare abstract class and abstract method
and override it in child classes and we have to create reference of parent class and object of child class
and using parent reference we call abstract method or parent method then child version get executed
whose address stored in parent reference
if we think about above code we code we have three class one is Vehicle which is abstract class and
parent of Car and Bike and it contain one abstract method name as abstract void engine() and which
override in Car and Bike class means engine() method has two different logics in two different classes
means we can say engine() method perform polymorphism so if we think about main method then we
have Vehicle v; here v is reference of Vehicle class and which is null and we have next statement
v=new Car() means v reference points to Car object again we have statement v.engine() means
engine() method get executed but from Car class version and we get output I am Car after that we
have statement v = new Bike() here we created object of Bike class and store its reference in v and
again we have statement v.engine() then we executed Bike method so we get output I am Bike
so think about above example we can say we have single method name as engine() with two different
logics i.e polymorphism but we decide the engine() at run time using Vehicle reference and which
engine() get executed is depend on child object so we can say it is dynamic polymorphism.

Q. what is actual benefit of dynamic polymorphism


It helps us to achieve loose coupling
Q. what is coupling?
Coupling means if one object is dependent on another object called as coupling
There are two types of coupling
1) Tight Coupling: Tight Coupling means if one class function 100% dependent on another class
object as parameter called as tight coupling.

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.

Now we want to see Example of Tight Coupling


If we think about above code we have three classes one is Bike one is Car and one is ShowRoom and
one more class name as CouplingApplication and in ShowRoom class we have method name as void
saleVehicle(Bike b) means this method contain parameter of type Bike object so if we think about
main method we created object of ShowRoom class and create object of Bike class and pass reference
as parameter in saleVehicle(b) method if we try to pass Car class reference in saleVehicle() method
then compiler will generate compile time error means we can say saleVehicle() method cannot accept
any other parameter except bike means saleVehicle() is 100% dependent on bike class reference and
saleVehicle() is a member of ShowRoom class means we can say ShowRoom class is 100%
dependent on Bike class so ShowRoom and Bike maintain tight coupling with each other
Tight coupling is not good approach
Means we can say as per our example ShowRoom can sale only Bikes but if ShowRoom wants to sale
bike as well as Car.
Q. how to solve this problem?
If we want to solve above problem we have two approaches
1) Use Compile time polymorphism means we can use function overloading technique
Means if we define two functions with same name in ShowRoom class name as
void saleVehicle(Bike bike)
void saleVehicle(Car car)
means here we have two version of saleVehicle() one is for bike and one is for car
if we create object of Bike class and pass in saleVehicle() then bike version get executed
and if we create object of Car class and pass in saleVehicle() then car version get executed.
means here ShowRoom can sale bike as well as car shown in following examples
package org.techhub.adapter;
class Bike
{
void feature() {
System.out.println("2 wheels");
}
}
class Car
{
void feature()
{
System.out.println("4 wheels");
}
}
class ShowRoom
{
void saleVehicle(Bike b) {
b.feature();
}
void saleVehicle(Car c) {
c.feature();
}
}
public class DynamicPolyApplication {
public static void main(String[] args) {
ShowRoom s = new ShowRoom();
Bike b = new Bike();
s.saleVehicle(b);
Car c = new Car();
s.saleVehicle(c);
}
}
compile time polymorphism is not feasible solution in above scenario suppose consider ShowRoom
want to sale Bike, Car, Tractor, Truck,Cycle, Skooty ,JCB etc
then we need to define number of saleVehicle() version to us means if ShowRoom want to sale
100 types of Vehicle then we need to define 100 version of saleVehicle() and it is not possible in real
time
so we want to single method can accept different types of object at run time means as per our example
we want to define single saleVehicle() method but this method can accept bike as parameter ,car as
parameter, truck as parameter etc then dynamic polymorphism comes in picture as well as abstract
class and abstract methods also comes in picture

2) Use Runtime Polymorphism and Dynamic polymorphism


package org.techhub.adapter;
abstract class Vehicle{
abstract void feature();
}
class Bike extends Vehicle
{ void feature() {
System.out.println("2 wheels");
}
}
class Car extends Vehicle
{ void feature()
{ System.out.println("4 wheels");
}
}
class ShowRoom
{ void saleVehicle(Vehicle v) {
v.feature();
}
}
public class DynamicPolyApplication {
public static void main(String[] args) {
ShowRoom s = new ShowRoom();
Vehicle v = new Bike();
s.saleVehicle(v);
v=new Car();
s.saleVehicle(v);
}
}
04/03/2023
Interface
Interface is same like as abstract class in java.

Q. Why Use Interface if we have abstract class in Java?


There are three major goal of interface
a) To achieve 100% abstraction:
Because if we think about interface then every method of interface is by default
abstract so we can say interface help us to achieve 100% abstraction.

B) To achieve dynamic polymorphism: using interface we can achieve dynamic polymorphism


same like as abstract class.
C) To implement multiple inheritance
Using interface we can implement multiple inheritance in java

Q. Why we cannot implement multiple inheritance using class in java?


Because of diamond problem
Q. What is diamond problem?
diamond problem means in multiple inheritance more than one parent classes and single child class so
there is possibility in different parent class may be contain same name method and if we create object
of child class and try to call parent method whose name same in different parent using child object
then compiler may be get confused this is called as diamond problem in shown in following diagram.

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.

How to use interface in java


If we want to use interface in java we have to use interface keyword.

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

1) Interface cannot create its object


2) Interface method cannot have logic
3) Interface variables are by default final
means if we declare any variable within interface it must have some value if we not initialize value to
interface variable then compiler will generate compile time = expected.
interface ABC
{ float PI;
void show();//public abstract void show()
}
if we think about above code we get compile time error because we declare variable within interface
but not initialize value at the time of declaration but it is final variable so it must have to initialize
some value in it so if we want to resolve above error we have to initialize value in PI as per our
example or interface variable.

interface ABC
{ float PI=3.14f;
void show();//public abstract void show()
}

Q. can we declare interface method as static?


No we cannot declare interface method as static because interface methods are by default abstract and
we cannot declare abstract method static so we cannot declare interface method as static.
Note:
interface ABC
{ float PI=3.14f;
static void show();//public abstract void show()
}
Above code generate compile time error to us because we declare interface method as static and it is
not allowed
Note: if we think about JDK 1.8 version of java then we can define static method in interface.

Q. Can we declare interface method as final?


No we cannot declare interface method as final because interface methods are abstract so they must be
override in child class or implementer class final cannot override so interface method cannot declare
as final.
interface ABC
{ float PI=3.14f;
final void show();//public abstract void show()
}
Above code generate compile time error to us because we declare its method as final and we cannot
declare interface method as final

Q. can we declare abstract method in abstract class protected?


Yes we can declare abstract method in abstract class protected
abstract class ABC
{ protected abstract void show();
}
Above code not generate any compile time error to us because we can declare abstract method as
protected when we declare it in class

Q. Can we declare interface method as protected?


No we cannot declare interface method as protected if we try to declare it then compiler will generate
compile time error
interface ABC
{ protected abstract void show();
}
Means above code will generate compile time error to us because we declare interface method as
protected.

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.

Q. can we create reference of interface?


Yes we can declare reference of interface for that we have to create object of its implementer class
Syntax:
interfacename ref = new implementorclass();

Shown in following Example

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 {

public static void main(String[] args) {


ABC a = new MNO();
a.show();
}
}

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

Q. what is benefit of interface reference?


To achieve dynamic polymorphism
Note: refer abstract class tutorial for dynamic polymorphism
Example of Dynamic polymorphism by using interface
package org.techhub;
interface Vehicle
{ void feature();
}
class Bike implements Vehicle
{ public void feature()
{System.out.println("2 wheels");
}
}
class Car implements Vehicle{
public void feature()
{System.out.println("4 wheels");
}
}
public class InterfaceTestApplication {
public static void main(String[] args) {
Vehicle v = new Bike();
v.feature();
v=new Car();
v.feature();
}
}
Example of Loose Coupling using Interface
package org.techhub;
interface Vehicle
{ void feature();
}
class Bike implements Vehicle
{ public void feature()
{ System.out.println("2 wheels");
}
}
class Car implements Vehicle
{ public void feature()
{ System.out.println("4 wheels");
}
}
class ShowRoom
{ void saleVehicle(Vehicle v) {
v.feature();
}
}
public class InterfaceTestApplication {
public static void main(String[] args) {
Vehicle v = new Bike();
ShowRoom s = new ShowRoom();
s.saleVehicle(v);
v=new Car();
s.saleVehicle(v);
}
}

Q. how to inherit interface to interface?


If we want to inherit interface to interface we have extends keyword
interface A
{void show();
}
interface B extends A
{ void display();
}
How to achieve multiple inheritances by using interface in java & how to resolve diamond
problem
Q. what is definition of multiple inheritance using java?
Multiple inheritance more than one parent and single child but in java in multiple parent there must be
single parent class and rest parents are interfaces.
Syntax of multiple inheritances

class classname extends parentclassname implements interface1,interface2…..interface….n


{
}
Example of multiple inheritances
interface A
{void show();
}
interface B
{ void show();
}
class C
{ void show();
}
class D extends C implements A,B
{ public void show(){
System.out.println (“I am D method”);
}
}
If we think about above code we have two classes name as D and C and two parent interfaces name as
A and B and we inherit class C in class D and implemented interface A and B so it is implementation
of multiple inheritance using java.

Q. how resolve diamond problem in above program?


if we think about above code we have two classes name as D and C and we interface name as A and
B and in interface A contain show() and interface B contain show() and class C also contain show()
method and we inherit class C in class D as well as we implemented interface A and interface B in
class D and override show() method so we think A,B and C they consider their own show method
override by class D and when we create object class D and cal the show() method then as per rule of
overriding when we create object of child class and call overridden method then by default child
logics get executed so there is change chance of occur diamond problem so java use interface for
multiple inheritance purpose.
Q. what is diff between abstract class and interface?

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

Q. what is diff between Abstraction and Encapsulation

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.

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

Q. what is diff between static and abstract

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.

Q. how many types of exception in java?


Basically there are three types of exception in java
1) Checked Exception: Those exceptions occur at program compile time called as checked exception
CheckedException help us to provide warning of exception at compile time
2) Unchecked Exception: Those exceptions occur at program run time called as unchecked
exception.
3) Error: Those exceptions never handle by programmer called as error.

Q. what is diff between Exception and Error?


1) Exception can handle by programmer but error cannot handle by programmer
2) Exception may be compile time or run time but error always runs time
3) Exception always occurs because of some logical error but error may be generate using some
logical error as well as may be generated by system also.

How to handle exception in java


If we want to handle exception in java for that purpose java provide some inbuilt classes and some
inbuilt keywords for handle exceptions

Class Hierarchy for exception handling

Above diagram indicate hierarchy of exception handling classes.


Keywords for Exception Handling
1) try: try is block in java which is normally use for writing logic in which exception may be occur
when exception generate in try block then JVM create one error object hand over to catch block for
further executions.
2) catch: catch is block which is used for writing logics those want to execute after exception in
program means we can say catch block execute by JVM when exception generate in program.
Syntax:
try{
write here logics in which exception may be occur
}
catch(exceptiontype ref)
{ write here your logics want to execute after exception
}
Note: Single try can have more than one catch block
try{
write here your logics in which exception may be occur
}
catch(exceptiontype ref)
{
}
catch(exceptiontype ref)
{
}

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
}

Q. can we write try without catch?


Yes using finally block shown in following code.

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

Source code with exception handling


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();
try{
c=a/b;
System.out.printf("Division is %d\n",c);
}
catch(ArithmeticException ex)
{ System.out.println("Error is "+ex);
}
System.out.println("Logic1");
System.out.println("Logic2");
}
}
Following diagram explain above code flow

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.

Q. what will be output of given code?


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);
}
catch(ArithmeticException ex) {

}
}
}
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

Catch using multiple exception class with single reference


it is used for avoid writing multiple catch with single try when user want to handle specific
exceptions.
Syntax:
try{
}
catch(exceptionclassname | exceptionclassname ref)
{
}

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.

How to design or create user defined exception in java?


If we want to create user defined exception in java we have create own exception class and inherit
inbuilt class in user class

class Userclassname extends inbuiltexceptionclass


{
}
Scenario
Suppose consider we want to design application for voting card generation and we want to provide
adhar number , birth year to voting card and using this two attributes we want to calculate age of voter
and if age of voter is less than 18 then we can generate run time error invalid voter otherwise generate
message welcome in voting booth

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 {

public static void main(String[] args) {


// TODO Auto-generated method stub
try {
ValidateVoter vv = new ValidateVoter();
vv.verifyVoter("1233AAAA", 2014);
}
catch(VoterException ex) {
System.out.println(ex.getVoterError());
}
}
}
Following diagram shows the flow of throws keyword
if we think about above code we have the class VoterException extends ArithmeticException means
we inherited ArithmeticException in VoterException means we can say VoterException is user
defined exception class and in this class we have method getVoterError() which return invalid voter
error message and we have two more class one is validateVoter this class contain one method name as
void verifyVoter(String adhar,int birthYear) in this method we check age of voter and we have
condition if age is <18 then system should generate exception at run time name as VoterException
and we have one more class name as VotingApplication and in this class contain main method and
here we created object of ValidateVoter class and we call method name as verifyVoter(String
adhar,int birthYear) and in our example we pass birthYear is 2014 and we have logic is age=2023-
2014 so we get age = 9 so after that we have if(age<18) means if(9<19) so it is true condition so we
created object VoterException and we throw it so this throw by JVM at function calling point means
as per our example this object can catch in main method because we call method in main and we
handle exception

Q. what is diff between throw and throws?

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

Q. what will be output of above code?


package org.techhub;
public class TestThrow {
public static void main(String[] args) {
try
{
}
catch(Integer val) {
}
}
}
Above code generate compile time error to us because we cannot pass any other class in catch block
who is not exception class and child of exception class.

Q. what will be output of given code?


package org.techhub;
public class TestThrow {
public static void main(String[] args) {
try
{
throw new Integer(0);
}
catch(Exception e) {

}
}
}
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

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(Exception e) {

}
}
}
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

Q. what will be output?


package org.techhub;

import java.util.InputMismatchException;

public class TestThrow {


public static void main(String[] args) {
try
{
throw new Exception();
}
catch(Exception e) {

}
}
}
Above code execute properly and handle exceptions

Q. what will be output of given code?


package org.techhub;
import java.util.InputMismatchException;
public class TestThrow {
public static void main(String[] args) {
try
{ throw new Throwable();
}
catch(Exception e) {
}
}
}
above code generate compile time warning to us because we try to throw object of Throwable class
but in catch we handle Exception and Exception is child of Throwable so if we throw parent object
then it cannot handle by child object compiler will generate compile time error if we want to solve
this error we have to handle Throwable in catch block shown in following code
import java.util.InputMismatchException;
public class TestThrow {
public static void main(String[] args) {
try {throw new Throwable();
}
catch(Throwable e) {
}
}
}
Q. what will be output of given 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) {
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.

Following Examples show how constructor call

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 ConsApplication {


public static void main(String[] args) {
A a1 = new A();
}
}
Note: if user not declare constructor in class then compiler add new constructor
automatically in class called as implicit constructor.

2) Parameterized constructor: if we pass parameter to constructor called as parameterized


constructor when we pass parameter to constructor then we have to pass parameter where
we create object of class.

Source code with Example


package org.techhub;
import java.util.*;
class Square
{ int no;
Square(int no){
this.no=no;
}
int getSquare() {
return no*no;
}
}
public class SquareApplication {
public static void main(String[] args) {
Scanner xyz = new Scanner(System.in);
System.out.println("Enter number");
int no=xyz.nextInt();
Square s1 = new Square(no);
int result = s1.getSquare();
System.out.println("Square is "+result);
}
}
Example : Now we want to create program create class name as ArraySum with
parameterized constructor and pass array as parameter to constructor and define one
method in class name as int getSum() this function can calculate sum of all elements of array
and return its sum at function calling point.

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 {

public static void main(String[] args) {


Employee emp = new Employee();
emp.setId(1);
emp.setName("ABC");
emp.setSal(1000);
Company c = new Company(emp);
c.show();
}

}
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 {

public static void main(String[] args) {


Employee emp = new Employee("ABC",1,1000);
Company c = new Company(emp);
c.show();
}
}
if we think about main method we create Employee emp = new Employee(“ABC”,1,1000);
means here we create object of Employee class and store its reference in emp and after that
we pass emp reference in Company class constructor as parameter but if we want to
optimize code you can create direct anonymous object in Company class class constructor
as parameter so we not need to Employee emp = new Employee() before company
constructor calling
means you can manage code Company c = new Company(new Employee(“ABC”,1,1000));
so this statement is equal Employee emp = new Employee(“ABC”,1,1000); Company c=new
Company(emp); shown in following code.
Source code with example
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 {
public static void main(String[] args) {
Company c = new Company(new Employee("ABC",1,1000));
c.show();
}
}
if we think about above code we create object of Company c = new Company(new
Employee("ABC",1,1000)) and we store reference of Company object in reference variable c
and after that we call c.show() method. Instead of this approach here we want to call only
one method of Company class here i.e show() so when we want to call only one method
using any object then we not need to use reference you can use short using anonymous
object shown in following 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.getS
al());
}
}
public class CompanyClassApplication {
public static void main(String[] args) {
new Company(new Employee("ABC",1,1000)).show();
}

}
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.

Now we want to perform constructor chaining using this () constructor


When we use this constructor then execution of constructor maintain in the form of stack.

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.

Example with source code


package org.techhub.chaining;
class A {
A() {
this(5);
System.out.println("I am default constructor");
}
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);
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
Output
I am float constructor 5.5
I am integer constructor 5
I am default constructor

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

1) Constructor cannot have return type


If you try to give return type to constructor then constructor consider as method means in
short we can say in java method name and constructor name may be same.
Example
package org.techhub.chaining;
class A {
void A() {
System.out.println("I am default constructor");
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
a1.A();
}
}
If we think about above code we have void A () statement in A class here we define function
with return type void means here we can say it is a function not constructor so we need to
call it using object name.

2) Constructor cannot support to recursion


because constructor call when we create object of class but recursion say we need to
perform calling within same definition means for recursion we required stack calling but for
constructor we required object for calling so this major reason constructor not support to
recursion.
Following code shown meaning of above concept
package org.techhub.chaining;
class A {
int count=0;
A() {
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.

4) We cannot override constructor


Means we cannot redefine parent class constructor again in child class and it we try to
perform overriding with constructor then it will generate compile time error to us
package org.techhub.chaining;
class A {
int count=0;
A() {
System.out.println("I am constructor");
}
}
class B extends A //here A is parent and B is child
{ A(){
}
}
public class ConsChainApp {
public static void main(String[] args) {
A a1 = new A();
}
}
if we think about above code we have two classes one is A as parent and B as child and we
have default constructor in class A and we try to override it in class B so it is not possible so
this is main reason compiler will generate compile time error to us
Q. Why constructors not override?
When we override a constructor then it will match its name child class and parent
constructor and child class name cannot match with each other 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.

1) What is Singleton Class?


Singleton class means class cannot create its more than one object in single application
called as Singleton class
Basically Singleton is a design pattern

Q. what is design pattern?


Design pattern are the some industry standard which is used for cover limitation of OOP.

Basically there are three types of design pattern in core java


i) Creational design pattern
ii) Structural design pattern
iii) Behavioral design pattern

How to Create Singleton class in java


If we want to create singleton class in java we have some following steps.
I) Declare class with private constructor
class ABC{
private ABC(){
System.out.println(“I am singleton class”);
}
}
ii) Declare on private static reference of same class in it.
class ABC{
private static ABC ab;
private ABC(){
System.out.println(“I am singleton class”);
}
}

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.

Source code Example


package org.techhub;
class Value
{ int a,b;
void setValue(int x,int y) {
this.a=x;
this.b=y;
}
}
class Add extends Value
{ int getAdd() {
return a+b;
}
}
class Mul extends Value
{ int getMul() {
return a*b;
}
}
public class InheritenceApplication {

public static void main(String[] args) {


// TODO Auto-generated method stub
Add ad = new Add();
ad.setValue(10,20);
Mul m = new Mul();
m.setValue(5, 3);
System.out.println("Addition is "+ad.getAdd());
System.out.println("Multiplication is "+m.getMul()); }
}
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.

Output of above code


package org.techhub;
class A
{ A(int x){
System.out.println("I am parent constructor "+x); }
}
class B extends A
{ B(){
super(100);
System.out.println("I am child constructor");
}
}
public class ConsWithInheritenceApp {
public static void main(String[] args) {
B b1 = new B();
}
}
Note: super () constructor must be first line of code in child class constructor if we not use super() in
first line of child class constructor then we get compile time error shown in following code.
package org.techhub;
class A
{ A(int x){
System.out.println("I am parent constructor "+x);
}
}
class B extends A
{ B(){
System.out.println("I am child constructor");
super(100);
}
}
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 use super() constructor in
second line of code in child class and it is not allowed so compiler generate error to us at compile
time.

Q. can we use this() and super() at same time?


No we cannot use this() and super() at same time because this() and super() must be first line of
code in calling constructor and it is not possible to give single line for two different statements so
compiler will generate compile time error to us if we use this() and super() at same time shown in
following code.
package org.techhub;
class A
{ A(int x){
System.out.println("I am parent constructor "+x);
}
}
class B extends A
{ B(){
super(100);
this();//need first line but user write on second line so generate compiler time error
System.out.println("I am child constructor");

}
}

}
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.

Q. what is method overriding?


Method overriding means if we define method in parent class and redefine same method again in
child class called as method overriding shown in following code.
class A
{ void show() {
System.out.println("I am show method in parent class");
}
}
class B extends A {
void show() {
System.out.println("I am show method in child class");
}
}
If we think about above code we have two classes one is A and one is B and A is parent class and B is
child class and we void show() method in class A and again we define void show() in class B means we
define same method in parent and same method again in child so we can say show() is overridden
method.
Note: in the case of method overriding if we create object of child class and call overridden method
then by default child logic get executed shown in following code.
Source code
package org.techhub;
class A
{ void show() {
System.out.println("I am show method in parent class");
}
}
class B extends A
{
void show() {
System.out.println("I am show method in child class");
}
}
public class MethodOverridingApplication {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}
Output:
I am show method in child class
Code description
if we think about above code we created object of class B which is child class and call overridden
method name as show() using b1.show() statement then we get logic from child class method or
child version of show() method means here we can say child version override its logic on parent
version

Q. is method overriding is beneficial or not?


Its depend on scenario and requirement of application some time it is beneficial but some not

Q. why use method overriding?


There are two major benefit of method overriding.
1) To customize parent logics in child class
2) To achieve dynamic polymorphism.

To customize parent logics in child class


Some time if child class want to modify parent logics in future as per his requirement then he can
take method signature from parent class and write own logics in it as per his requirement.
Suppose Consider we want to design application for Calculator and we have three classes name as
Value Add and Mul. Here Value class work as parent class and Add and Mul classes work as child
classes so Value contain two methods void setValue(int x,int y) and int getResult() here we can
Calculator can generate result using getResult() method but result vary from child to child means Add
class can generate different for value and mul class can generate different result for value so here we
have to override getResult() method in Add class and In Mul class and we can customize its result
logics shown in following code.
Example with source code
package org.techhub;
class Value
{ int a,b;
void setValue(int x,int y) {
a=x;
b=y;
}
int getResult() {
return 0;
}
}
class Add extends Value
{
int getResult() {
return a+b;
}
}
class Mul extends Value
{
int getResult() {
return a*b;
}
}
public class CalculatorApplication {
public static void main(String[] args) {
Add ad= new Add();
ad.setValue(5, 4);
int result=ad.getResult();
System.out.println("Addition is "+result);
Mul m = new Mul();
m.setValue(5,4);
result =m.getResult();
System.out.println("Multiplication is "+result);
}

}
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.

Example with compile time error in overriding


class A
{ void show() {
}
}
class B extends A
{ int show() {

}
}
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.

Q. if we define parent method as protected and can we override it as public?


yes it is possible because in overriding public access specifier has more preferences than protected and
default so if we define parent as protected or default and if we override it as public in child then
compiler not generate any compile time error it is allowed shown in following code.
class A
{ protected void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ public 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 two classes name as A and class B in class A we have method
protected void show() and in class B we override it as public void show() so it is allowed.

Q. can we define parent method as public and override as protected?


No it is not allowed because public has higher preferences than protected and default so if we parent
method is public then at the time of overriding child must be override it as public and if child try to
override it as protected or default then compiler will generate compile time error to us . package
org.techhub;
class A
{ public void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ protected 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();
}
}
Above code generate compile time error because we have class A is parent class and it contain one
method public void show () and we try to override as protected void show () in child class so it is not
allowed compiler will generate compile time error to us.

Q. can we define parent method as default and override as protected?


Yes it is allowed because default has less preference than protected and public so if we define
parent method as default and if we override it as public in child class then there is no problem it
acceptable.
but vice versa not allowed means parent method protected and child method default not allowed.
class A
{ void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ protected 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 two classes name as A and class B in class A contain void
show() means we not use any access specifier with show() in parent so it work with default access
specifier and we override it as protected in child class so it allowed.

Q. can we override private method?


if we define parent method as private and if we define same method again in child class then it is not
method overriding means child define own self method same name as parent class name
private cannot override.
package org.techhub;
class A
{ private void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ void show() {
super.show();
System.out.println("I am show in child");
}
}
public class OverridingRulesApp {
public static void main(String[] args) {
new B().show();
}
}
above code generate compile time error to us because we try to show() method using super keyword
and show() is private in parent class and it is override or accessible in child so we cannot call it using
super keyword if we remove super.show() then there is no compile time error but there is overriding
also child class define own self method in its body.

Q. Can we override static method?


Yes we can override a static method
package org.techhub;
class A
{ static void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ static void show() {
System.out.println("I am show in child");
}
}
public class OverridingRulesApp {
public static void main(String[] args) {
B b1 = new B();
b1.show();
}
}
if we think about above code we have two classes name as A and B in class A contain static void
show() and in class B contain static void show() again so we can say it is overriding and when we
create object of class B and call b1.show() then child version get executed automatically.
Note: Normally we override static method for method hiding purpose.
Q. what is method hiding in java?
Method hiding means if we override static method and if we create reference of parent class using
child object then parent logic get executed using parent reference called as method hiding. package
org.techhub;
class A
{ static void show() {
System.out.println("I am parent show");
}
}
class B extends A
{ static void show() {
System.out.println("I am show in child");
}
}
public class OverridingRulesApp {
public static void main(String[] args) {
A b1 = new B();
b1.show();
}
}
Output: I am parent show
If we think about above code we have statement A b1 =new B() means here we have reference of
parent class name as b1 and we have object of child class name as new B() and we call b1.show()
here we get parent logic means here we hide the child logic called as method hiding.

Q. can we override final method?


No it is used for avoid method overriding in java
Normally if parent class want secure its logic from child modification by using overriding technique
then we can define parent method as final.

Q. Can we inherit final method?


Yes you can inherit final method
Inheritance we can reuse parent logic in child class and overriding means we can modify parent logic in
child class
Means final method can use by child class but cannot modify by child class using overriding so we
can say we can inherit final method.

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.

Abstract class and Abstract method


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

How to declare abstract class and abstract method in java


If we want to declare abstract class and abstract method in java we have abstract keyword
Syntax:
abstract class classname {
abstract return type function name(arguments);
}
e.g abstract class Vehicle{
abstract void engine ();
}
Q. what is use of abstract method? The
major use of abstract method is
1) To achieve abstraction:
2) To achieve dynamic polymorphism.
Q. what is abstraction?
Abstraction means to hide implementation detail from end user at designing level called as abstraction
means in short we can say in the case of abstraction we not provide any implementation of method in
parent class just we provide its proto type or template in parent class and we write its logic in child
class as per need of child.
Suppose consider if we think about Vehicle then we can say every Vehicle has engine () but we cannot
predict its design it is vary from Vehicle to Vehicle means if we think about Bike then Bike has different
engine capacity and if we think about Car then Car has different engine() capacity but Bike and Car both
are Category of Vehicle so we Can say Vehicle need engine with different design so it is example of
abstraction.
abstract class Vehicle{
abstract void engine ();
}
class Bike extends Vehicle
{ void engine(){
System.out.println(“1000 CC”);
}
}
class Car extends Vehicle
{ void engine(){
System.out.println(“100 CC”);
}
}
If we want to work with abstract class and abstract method in java we have some important points.
1) Abstract class cannot create its object
abstract class A{
}
public class AbstractionApp {
public static void main(String[] args) {
A a1 = new A();
}
}
Above code generate compile time error to us because we try to create object of abstract class A.
2) If method is abstract then class must be abstract
The meaning is we cannot declare abstract method in non abstract class and if we try to declare it
then
There is compile time error.
class A
{ abstract void show();
}
public class AbstractionApp {
public static void main(String[] args) {
}
}
Above code generate compile time error to us because we have class A and it is not abstract method
and we declare abstract void show () in it so it will generate compile time error to us.
So if we avoid this problem we must be declare class A as abstract shown in given code.
package org.techhub;
abstract class A
{ abstract void show();
}
public class AbstractionApp {
public static void main(String[] args) {
}
}
Q. can we declare non abstract method in abstract class?
Yes we can declare non abstract method in abstract class if we declare some abstract and some non
abstract method in class then class mark as concrete class shown in following code.
package org.techhub;
abstract class A
{ abstract void show();
void display() {
System.out.println("I am display method");
}
}
public class AbstractionApp {
public static void main(String[] args) {
}
}
if we think about above code we have abstract class A with two methods abstract void show() and
void display() here in class A one method is abstract and one method is non abstract so we can say
class A is concrete class.
Q. can we write logic of abstract method?
No we cannot create logic of abstract method where we declare it but if we want to write logic of
abstract method we have to inherit abstract class in some another non abstract class and override
abstract method and we can write its logic.
Example:
package org.techhub;
abstract class Vehicle
{ abstract void engine();
}
class Bike extends Vehicle
{ void engine() {
System.out.println("1000 CC");
}
}
class Car extends Vehicle
{ void engine() {
System.out.println("100 CC");
}
}
public class AbstractionApp {
public static void main(String[] args) {
Car c = new Car();
c.engine();
Bike b = new Bike();
b.engine();
}
}
In above example we have abstract class Vehicle with abstract method engine () and we have two
child classes name as Bike and Car and override engine () method in Bike class and engine () method in
Car class and write its logic.
The benefit we can customize abstract method logic in every child class as per our need by using
method overriding technique as well as we can achieve dynamic polymorphism using overriding
technique
Note: we will discuss dynamic polymorphism later in this chapter.
Q. Can we declare abstract method as static?
No we cannot declare abstract method as static and if we try to declare it then we get compile time
error
abstract class Vehicle
{static abstract void engine();
}
If we think about above code we get compile time error to us because we declare abstract method as
static and it not possible.
Q. Why we cannot declare abstract method as static?
Because static method work with compile time polymorphism and abstract method work with
dynamic polymorphism using overriding
The another reason static method allocate memory before creating object of class and for method
memory allocation it must have definition and abstract method cannot have definition so cannot
declare abstract method as static.
Q. can we declare abstract method as final?
No we cannot declare abstract method as final and if we try to declare then compiler will generate
compile time error to us shown in given code
abstract class Vehicle
{ final abstract void engine();
}
If we think about above code we declare abstract method as final and it is not allowed so compiler
will generate compile time error to us.
Q. Why we cannot declare abstract method as final?
Because final method cannot override in child class but abstract method must be override in child
class
And it is opposite behavior of final and abstract so we can not declare abstract method as final.
Q. can we declare abstract method as private?
no we cannot declare abstract method as private and if we try to declare then compiler will generate
compile time error to us.
abstract class Vehicle
{private abstract void engine();
}
Above code generate compile time because we declare abstract method as private.
Q. why we cannot declare abstract method as private?
Because private method cannot support to inheritance as well as overriding but abstract method
cannot work without overriding and without inheritance so it is not possible.
Q. Can we use abstract keyword with variable or can we declare variable as abstract?
No we cannot declare variable as abstract and if we declare it we get compile time error
abstract class Vehicle
{ abstract int a=100;
abstract void engine();
}
Q. why we cannot declare variable as abstract
because the major goal of abstract keyword is achieve abstraction but we cannot achieve abstraction
using variable because variable normally refer for storing data so we cannot use abstract keyword with
variable.
Note: if abstract class contains more than one abstract method then all method must be override
where abstract class gets inherited if we not override all methods then compiler will generate compile
time problem or error to us if we not required abstract method then we must be override it as blank.
abstract class Vehicle
{ abstract void engine();
abstract void feature();
}
class Car extends Vehicle {
void engine() {
System.out.println("1000 CC Required");
}
}
if we think about above code we get compile time error because we have abstract class Vehicle and it
contain two methods abstract void engine () and abstract void feature () but we override only one
method in Car class i.e. engine () but rule is must be override all abstract methods from parent to child
and we override feature () then we get compile time error.
So resolve this problem we have two approaches
1) Define method as blank in child class if we not required
abstract class Vehicle
{ abstract void engine();
abstract void feature();
}
class Car extends Vehicle
{ void engine() {
System.out.println("1000 CC Required");
}
void feature() {
}
}
if we think about above code we define feature () as blank so it is requirement of abstract class his
all method must be define but it is not good approach so we have one more option we can use
adapter class
2) Use adapter class
Q. what is adapter class?
Adapter class is intermediate class which contain all blank definition of abstract class methods and
which is responsible for provide specific method to abstract child class called as adapter class.
Example of Adapter class
package org.techhub.adapter;
abstract class ABC {
abstract void s1();
abstract void s2();
abstract void s3();
}
class ADP extends ABC {
@Override
void s1() { // TODO Auto-generated method stub }
@Override
void s2() {
// TODO Auto-generated method stub

}
@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

Q. what is dynamic polymorphism?


Dynamic polymorphism means if we bind functionality with object at program run time called as
dynamic polymorphism.
If we want to achieve dynamic polymorphism we have to declare abstract class and abstract method
and override it in child classes and we have to create reference of parent class and object of child class
and using parent reference we call abstract method or parent method then child version get executed
whose address stored in parent reference
if we think about above code we code we have three class one is Vehicle which is abstract class and
parent of Car and Bike and it contain one abstract method name as abstract void engine() and which
override in Car and Bike class means engine() method has two different logics in two different classes
means we can say engine() method perform polymorphism so if we think about main method then we
have Vehicle v; here v is reference of Vehicle class and which is null and we have next statement v=new
Car() means v reference points to Car object again we have statement v.engine() means engine()
method get executed but from Car class version and we get output I am Car after that we have
statement v = new Bike() here we created object of Bike class and store its reference in v and again we
have statement v.engine() then we executed Bike method so we get output I am Bike so think about
above example we can say we have single method name as engine() with two different logics i.e
polymorphism but we decide the engine() at run time using Vehicle reference and which engine() get
executed is depend on child object so we can say it is dynamic polymorphism.

Q. what is actual benefit of dynamic polymorphism It


helps us to achieve loose coupling
Q. what is coupling?
Coupling means if one object is dependent on another object called as coupling
There are two types of coupling
1) Tight Coupling: Tight Coupling means if one class function 100% dependent on another class
object as parameter called as tight coupling.

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.

Now we want to see Example of Tight Coupling


If we think about above code we have three classes one is Bike one is Car and one is ShowRoom and
one more class name as CouplingApplication and in ShowRoom class we have method name as void
saleVehicle(Bike b) means this method contain parameter of type Bike object so if we think about main
method we created object of ShowRoom class and create object of Bike class and pass reference as
parameter in saleVehicle(b) method if we try to pass Car class reference in saleVehicle() method then
compiler will generate compile time error means we can say saleVehicle() method cannot accept any
other parameter except bike means saleVehicle() is 100% dependent on bike class reference and
saleVehicle() is a member of ShowRoom class means we can say ShowRoom class is 100% dependent
on Bike class so ShowRoom and Bike maintain tight coupling with each other Tight coupling is not
good approach
Means we can say as per our example ShowRoom can sale only Bikes but if ShowRoom wants to sale
bike as well as Car.
Q. how to solve this problem?
If we want to solve above problem we have two approaches
1) Use Compile time polymorphism means we can use function overloading technique
Means if we define two functions with same name in ShowRoom class name as
void saleVehicle(Bike bike)
void saleVehicle(Car car)
means here we have two version of saleVehicle() one is for bike and one is for car
if we create object of Bike class and pass in saleVehicle() then bike version get executed and
if we create object of Car class and pass in saleVehicle() then car version get executed.
means here ShowRoom can sale bike as well as car shown in following examples
package org.techhub.adapter;
class Bike
{
void feature() {
System.out.println("2 wheels");
}}
class Car {
void feature()
{
System.out.println("4 wheels"); }
}
class ShowRoom
{
void saleVehicle(Bike b) {
b.feature();
}
void saleVehicle(Car c) {
c.feature();
}
}
public class DynamicPolyApplication {
public static void main(String[] args) {
ShowRoom s = new ShowRoom();
Bike b = new Bike();
s.saleVehicle(b);
Car c = new Car();
s.saleVehicle(c);
}
}
compile time polymorphism is not feasible solution in above scenario suppose consider ShowRoom
want to sale Bike, Car, Tractor, Truck,Cycle, Skooty ,JCB etc
then we need to define number of saleVehicle() version to us means if ShowRoom want to sale
100 types of Vehicle then we need to define 100 version of saleVehicle() and it is not possible in real
time
so we want to single method can accept different types of object at run time means as per our
example we want to define single saleVehicle() method but this method can accept bike as parameter
,car as parameter, truck as parameter etc then dynamic polymorphism comes in picture as well as
abstract class and abstract methods also comes in picture

2) Use Runtime Polymorphism and Dynamic polymorphism


package org.techhub.adapter;
abstract class Vehicle{
abstract void feature();
}
class Bike extends Vehicle
{ void feature() {
System.out.println("2 wheels");
}
}
class Car extends Vehicle
{ void feature()
{ System.out.println("4 wheels");
}
}
class ShowRoom
{ void saleVehicle(Vehicle v) {
v.feature();
}
}
public class DynamicPolyApplication {
public static void main(String[] args) {
ShowRoom s = new ShowRoom();
Vehicle v = new Bike();
s.saleVehicle(v);
v=new Car();
s.saleVehicle(v);
}
}
Interface
Interface is same like as abstract class in java.

Q. Why Use Interface if we have abstract class in Java?


There are three major goal of interface
a) To achieve 100% abstraction:
Because if we think about interface then every method of interface is by default
abstract so we can say interface help us to achieve 100% abstraction.

B) To achieve dynamic polymorphism: using interface we can achieve dynamic polymorphism


same like as abstract class.
C) To implement multiple inheritance
Using interface we can implement multiple inheritance in java

Q. Why we cannot implement multiple inheritance using class in java?


Because of diamond problem
Q. What is diamond problem?
diamond problem means in multiple inheritance more than one parent classes and single child class so
there is possibility in different parent class may be contain same name method and if we create object
of child class and try to call parent method whose name same in different parent using child object
then compiler may be get confused this is called as diamond problem in shown in following diagram.
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.

How to use interface in java


If we want to use interface in java we have to use interface keyword.

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

1) Interface cannot create its object


2) Interface method cannot have logic
3) Interface variables are by default final
means if we declare any variable within interface it must have some value if we not initialize value to
interface variable then compiler will generate compile time = expected.
interface ABC
{ float PI;
void show();//public abstract void show()
}
if we think about above code we get compile time error because we declare variable within interface
but not initialize value at the time of declaration but it is final variable so it must have to initialize some
value in it so if we want to resolve above error we have to initialize value in PI as per our example or
interface variable.

interface ABC
{ float PI=3.14f;
void show();//public abstract void show() }

Q. can we declare interface method as static?


No we cannot declare interface method as static because interface methods are by default abstract
and we cannot declare abstract method static so we cannot declare interface method as static. Note:
interface ABC
{ float PI=3.14f;
static void show();//public abstract void show()
}
Above code generate compile time error to us because we declare interface method as static and it is
not allowed

Note: if we think about JDK 1.8 version of java then we can define static method in interface.

Q. Can we declare interface method as final?


No we cannot declare interface method as final because interface methods are abstract so they
must be override in child class or implementer class final cannot override so interface method
cannot declare as final.
interface ABC
{ float PI=3.14f;
final void show();//public abstract void show()
}
Above code generate compile time error to us because we declare its method as final and we cannot
declare interface method as final

Q. can we declare abstract method in abstract class protected?


Yes we can declare abstract method in abstract class protected
abstract class ABC
{ protected abstract void show();
}
Above code not generate any compile time error to us because we can declare abstract method as
protected when we declare it in class

Q. Can we declare interface method as protected?


No we cannot declare interface method as protected if we try to declare it then compiler will
generate compile time error
interface ABC
{ protected abstract void show();
}
Means above code will generate compile time error to us because we declare interface method as
protected.

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.

Q. can we create reference of interface?


Yes we can declare reference of interface for that we have to create object of its implementer class
Syntax:
interfacename ref = new implementorclass();

Shown in following Example

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 {

public static void main(String[] args) {


ABC a = new MNO();
a.show();
}
}

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

Q. what is benefit of interface reference?


To achieve dynamic polymorphism
Note: refer abstract class tutorial for dynamic polymorphism
Example of Dynamic polymorphism by using interface
package org.techhub;
interface Vehicle
{ void feature();
}
class Bike implements Vehicle
{ public void feature()
{System.out.println("2 wheels");
}
}
class Car implements Vehicle{
public void feature()
{System.out.println("4 wheels");
}
}
public class InterfaceTestApplication {
public static void main(String[] args) {
Vehicle v = new Bike();
v.feature();
v=new Car();
v.feature();
}
}
Example of Loose Coupling using Interface
package org.techhub;
interface Vehicle
{ void feature();
}
class Bike implements Vehicle
{ public void feature()
{ System.out.println("2 wheels"); }
}
class Car implements Vehicle
{ public void feature()
{ System.out.println("4 wheels");
}
}
class ShowRoom
{ void saleVehicle(Vehicle v) {
v.feature();
}
}
public class InterfaceTestApplication {
public static void main(String[] args) {
Vehicle v = new Bike();
ShowRoom s = new ShowRoom();
s.saleVehicle(v);
v=new Car();
s.saleVehicle(v);
}
}
Q. how to inherit interface to interface?
If we want to inherit interface to interface we have extends keyword
interface A
{void show();
}
interface B extends A
{ void display();
}
How to achieve multiple inheritances by using interface in java & how to resolve diamond
problem
Q. what is definition of multiple inheritance using java?
Multiple inheritance more than one parent and single child but in java in multiple parent there must
be single parent class and rest parents are interfaces.
Syntax of multiple inheritances

class classname extends parentclassname implements interface1,interface2…..interface….n {


}
Example of multiple inheritances
interface A
{void show(); }
interface B
{ void show();
class C
{ void show();
}
}
class D extends C implements A,B
{ public void show(){
System.out.println (“I am D method”);
}
}
If we think about above code we have two classes name as D and C and two parent interfaces name as
A and B and we inherit class C in class D and implemented interface A and B so it is implementation of
multiple inheritance using java.

Q. how resolve diamond problem in above program?


if we think about above code we have two classes name as D and C and we interface name as A and B
and in interface A contain show() and interface B contain show() and class C also contain show()
method and we inherit class C in class D as well as we implemented interface A and interface B in class
D and override show() method so we think A,B and C they consider their own show method override
by class D and when we create object class D and cal the show() method then as per rule of overriding
when we create object of child class and call overridden method then by default child logics get
executed so there is change chance of occur diamond problem so java use interface for multiple
inheritance purpose.

Q. what is diff between abstract class and interface?

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

Q. what is diff between Abstraction and Encapsulation

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

Q. what is diff between static and abstract

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.

There are two types of conversion in Wrapper classes


i) Auto boxing: auto boxing means if we convert primitive type value to reference value automatically
called as auto boxing.
ii) Auto unboxing: when we convert any reference type value to primitive type value called as auto
unboxing.
Following Example demonstrate use of auto boxing and auto unboxing.
package org.techhub;
public class ConversionApplication {
public static void main(String[] args) {
int a=100;
Integer b=a; //auto boxing
System.out.printf("B is %d\n", b);
Integer c=200;
int d=c;//auto unboxing.
System.out.printf ("D is %d\n",d);
}
}

Source code with example


package org.techhub;
public class TestWrapperApp {
static int a; //primitive type of variable
static Integer b; //reference type variable
public static void main(String[] args) {
System.out.println("A is "+a);
System.out.println("B is "+b);
}
}
if we think about above code we have two variable one is int a; it is primitive type of variable
and we have one more is Integer b; it is one type of reference variable
so when we print System.out.println(“A is “+a); we get output is 0 and we have one is
System.out.println(“B is “+b); // we get null value because reference always null.

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);
}
}

double doubleValue(): convert any type of reference in to primitive type double.


package org.techhub;
public class TestWrapperApp {
public static void main(String[] args) {
Long l=5L;
double d=l.doubleValue();
System.out.println("D is "+d);
}
}
long longValue(): this method is used for convert any reference value to primitive type of long.

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);
}
}

short shortValue(): convert any numeric reference to short type


byte byteValue(): convert any numeric to byte value.

How to convert primitive value to reference value


if we want to convert any primitive value to reference value we have statement or we have
method name as valueOf()
valueOf() method present in every wrapper class and it is static method .

Example: we want to convert primitive type of integer value to string type.


package org.techhub;
public class TestWrapperApp {
public static void main(String[] args) {
int a=12345;
String s=String.valueOf(a);//convert primitive type of integer to string
System.out.println(s);
Float f=Float.valueOf(a);//conovert primitive type integer to float
System.out.println(f);
}
}
How to convert any String value to primitive type
if we want to convert any string value to primitive value we have parseXXX() method
and it is static method present in every wrapper class;
Example:
int var =Integer.parseInt(String)
float var=Float.parseFloat(String)
double var=Double.parseDouble(String);

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

There are two ways to create String.


I) by using initialization technique:
Syntax: String ref =”value”;
Example: String s=”abcd”;
ii) By using new keyword:
String ref =new String(“value”);

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.

String s=new String("abc");


String s1=new String("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 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.

Q. what is string pool constant?


String pool constant is part of JVM memory and it is also subjection of heap area and it is used for
provide specially for string constant when we create string object without new keyword then it is stored
under string pool constant and string pool constant is part of heap memory
Means we can say string pool help us to reuse memory whose value is same.

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:

public class StringHandlngApplication {


static String s=new String();
public static void main(String[] args) {
System.out.println(s);
}
}
If we think about given code we have statement String s = new String (); here we get output blank

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

int length(): this method is used for calculate length of string.

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.

In above diagram we show we have two different object s and s1 in memory


String concat(String): this method is used for combine two strings and generate new string from it.
package org.techhub;
public class ConcatApplication {
public static void main(String[] args) {
String s="abc";
String s1="mno";
s.concat(s1);
System.out.println(s);
}
}
Output: abc
if we think about above code we get output abc we expected abc mno but it is not possible because
string is immutable class means we cannot modify value of string so if we want to proper output we
need to use one extra variable at left hand side of string so you syntax like as

String result = s.concat(s1); shown in following code and diagram.

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: we want to check string is ends with sh or not


package org.techhub;
public class ConcatApplication {
public static void main(String[] args) {
String s="ganesh";
boolean b=s.endsWith("sh");
if(b) {
System.out.println("String ends with sh");
}
else { System.out.println("String not ends with sh");
}
}
}

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;

public class ConcatApplication {


public static void main(String[] args) {
String s=" good morning india";
s=s.trim();
System.out.println(s);

}
}
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

Input: String s=”I am india I like india and india is my country”;


Output: india inda india country
Number of stop words are : 7
Note: first search 100 stop words from google and store in one string array or in collection after that you
have split string by space means we get words then compare every word in collection where we store
stop words again we have to create one new temporary collection if we not found stop word then store
word in temporary collection and at end fetch all string data from collection and concat in one new
string and maintain one more temparary variable for stop word counting.

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

StringBuffer and StringBuilder?


2) Reference type conversion: That conversion between objects called as referential conversion.
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.
Exception is an event occurs during program execution which disturbs the normal flow of the
program.
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.
It help programmer to detect error at run time
Errors are not user friendly so to get better experience to the user we show him simple error
message by using exception handling
Use to continue our regular flow of the program by handling exception

Q. how many types of exception in java?


Basically there are three types of exception in java
1) Checked Exception: Those exceptions occur at program compile time called as checked exception
CheckedException help us to provide warning of exception at compile time
2) Unchecked Exception: Those exceptions occur at program run time called as unchecked
exception.
3) Error: Those exceptions never handle by programmer called as error.

Q. what is diff between Exception and Error?


1) Exception can handle by programmer but error cannot handle by programmer
2) Exception may be compile time or run time but error always runs time
3) Exception always occurs because of some logical error but error may be generate using some
logical error as well as may be generated by system also.

How to handle exception in java


If we want to handle exception in java for that purpose java provide some inbuilt classes and some
inbuilt keywords for handle exceptions

Class Hierarchy for exception handling


Above diagram indicate hierarchy of exception handling classes.
Keywords for Exception Handling
1) try: try is block in java which is normally use for writing logic in which exception may be occur
when exception generate in try block then JVM create one error object hand over to catch block for
further executions.
2) catch: catch is block which is used for writing logics those want to execute after exception in
program means we can say catch block execute by JVM when exception generate in program.
Syntax:
try{
write here logics in which exception may be occur
}
catch(exceptiontype ref)
{ write here your logics want to execute after exception
}
Note: Single try can have more than one catch block
try{
write here your logics in which exception may be occur
}
catch(exceptiontype ref)
{
}
catch(exceptiontype ref)
{
}

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
}

Q. can we write try without catch?


Yes using finally block shown in following code.

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

Source code with exception handling


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();
try{
c=a/b;
System.out.printf("Division is %d\n",c);
}
catch(ArithmeticException ex)
{ System.out.println("Error is "+ex);
}
System.out.println("Logic1");
System.out.println("Logic2");
}
}

Following diagram explain above code flow


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.

Q. what will be output of given code?


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);
}
catch(ArithmeticException ex) {

}
}
}
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

Catch using multiple exception class with single reference


it is used for avoid writing multiple catch with single try when user want to handle specific
exceptions.
Syntax:
try{
}
catch(exceptionclassname | exceptionclassname ref)
{
}

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

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.

How to design or create user defined exception in java?


If we want to create user defined exception in java we have create own exception class and inherit
inbuilt class in user class

class Userclassname extends inbuiltexceptionclass


{
}
Scenario
Suppose consider we want to design application for voting card generation and we want to provide
adhar number , birth year to voting card and using this two attributes we want to calculate age of
voter and if age of voter is less than 18 then we can generate run time error invalid voter otherwise
generate message welcome in voting booth

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 {

public static void main(String[] args) {


// TODO Auto-generated method stub
try {
ValidateVoter vv = new ValidateVoter();
vv.verifyVoter("1233AAAA", 2014);
}
catch(VoterException ex) {
System.out.println(ex.getVoterError());
}
}
}
Following diagram shows the flow of throws keyword
if we think about above code we have the class VoterException extends ArithmeticException means
we inherited ArithmeticException in VoterException means we can say VoterException is user
defined exception class and in this class we have method getVoterError() which return invalid voter
error message and we have two more class one is validateVoter this class contain one method name
as void verifyVoter(String adhar,int birthYear) in this method we check age of voter and we have
condition if age is <18 then system should generate exception at run time name as VoterException
and we have one more class name as VotingApplication and in this class contain main method and
here we created object of ValidateVoter class and we call method name as verifyVoter(String
adhar,int birthYear) and in our example we pass birthYear is 2014 and we have logic is age=2023-
2014 so we get age = 9 so after that we have if(age<18) means if(9<19) so it is true condition so we
created object VoterException and we throw it so this throw by JVM at function calling point means
as per our example this object can catch in main method because we call method in main and we
handle exception

Q. what is diff between throw and throws?

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

Q. what will be output of above code?


package org.techhub;
public class TestThrow {
public static void main(String[] args) {
try
{
}
catch(Integer val) {
}
}
}
Above code generate compile time error to us because we cannot pass any other class in catch block
who is not exception class and child of exception class.

Q. what will be output of given code?


package org.techhub;
public class TestThrow {
public static void main(String[] args) {
try
{
throw new Integer(0);
}
catch(Exception e) {

}
}
}
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

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(Exception e) {

}
}
}
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

Q. what will be output?


package org.techhub;

import java.util.InputMismatchException;

public class TestThrow {


public static void main(String[] args) {
try
{
throw new Exception();
}
catch(Exception e) {

}
}
}
Above code execute properly and handle exceptions

Q. what will be output of given code?


package org.techhub;
import java.util.InputMismatchException;
public class TestThrow {
public static void main(String[] args) {
try
{ throw new Throwable();
}
catch(Exception e) {
}
}
}
above code generate compile time warning to us because we try to throw object of Throwable class
but in catch we handle Exception and Exception is child of Throwable so if we throw parent object
then it cannot handle by child object compiler will generate compile time error if we want to solve
this error we have to handle Throwable in catch block shown in following code
import java.util.InputMismatchException;
public class TestThrow {
public static void main(String[] args) {
try {throw new Throwable();
}
catch(Throwable e) {
}
}
}
Q. what will be output of given 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) {
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.

Note: if we think about array then we some limitations


1) Array size is fixed means we cannot modify array at size run time
2) need to implement data structure algorithm manually like as searching, sorting etc

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.

Q. what is purpose of java.lang.Iterable?


The major goal of this interface is to fetch data from collection if we think about any collection like
as Stack, Queue, LinkedList data fetching or view is common operation on any collection so java
design one parent interface for fetch data from collection name as Iterable and Iterable interface
provide one method to us name as iterator() and this method return reference of Iterator interface
internally
interface Iterable
{ Iterator iterator();
}
Iterator interface provide following method to us for fetch data from collection

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.

Example for fetch data from ArrayList collection

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

Methods of Collection interface


public abstract boolean add(E):this method help us to add new element at the end of ArrayList.
public abstract int size() : this method can return count of total element present in collection.
Example using add and size method.

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

We have three types of Collection in java

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.

Now we want to discuss about List Collection

Methods of List Collection

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.

2) Cross verify index before deletion value from List collection


if we think about list collection then in list collection you can delete data by using index of value.
We have method in List interface i.e E remove(int index) suppose if we want to delete value using its
index but if we think real time so it is not possible to remember index of every value in collection
so before deletion of value using index as programmer your responsibility is to find index using value
and after that you can delete it.
Following diagram shows above statement meaning

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.

Q. what is thread safe?


Thread safe means only one thread can use at time sequentially not more than one thread can use
simultaneously at time called as thread safe collection and it is achieve by using synchronized
keyword.
If we want to work with Vector we have following constructor provided by java

Constructor of Vector class

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

Shown in following code and diagram.


Source code
package org.techhub;
import java.util.*;
public class VectorTestApplication {
public static void main(String[] args) {
Vector v = new Vector();
int capacity = v.capacity();
System.out.println("Initial capacity is "+capacity);
}
}
Note: Vector allocates double memory than its current capacity when capacity cross.
package org.techhub;
import java.util.*;
public class VectorTestApplication {
public static void main(String[] args) {
Vector v = new Vector();
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 code we added 12 elements in collection so vector allocate double memory
Than its current capacity so the current capacity of vector is 20

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);
}
}

How to fetch data from collection


If we want to fetch data from Collection we have some cursor or iteraters provided by Java to us
1) Fetch Data using Enumeration : Enumeration is a interface from java.util package it is read only
cursor means using Enumeration we can fetch data from collection we cannot perform any other
operation on collection using Enumeration and it is only work with legacy collection.
If we want to create reference of Enumeration we have elements () method and this method return
reference of Enumeration
Syntax: Enumeration elements ();

Methods of Enumeration interface.


boolean hasMoreElements(): this method check element present in collection or not if
present return true otherwise return false.
Object nextElement(): this method is used for fetch data from collection and move cursor
on next element
Following diagram shows working of Enumeration interface.

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

Syntax: Iterator iterator();


Methods of Iterator interface
boolean hasNext(): this method can check data present in collection or not if present return
true otherwise return false.
Object next(): fetch data from collection and move cursor on next element.
void remove(): this method remove data from collection at the time of traversing.
Example:
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("Data from collection");
Iterator i=v.iterator();
while(i.hasNext()) {
Object obj = i.next();
System.out.println(obj);
}
}
}

Q. What is diff between Enumeration and Iterator?

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.

Methods of ListIterator collection


boolean hasNext(): check data present in collection or not in forward direction
boolean hasPrevious(): check data present in collection or not in backward direction
Object next(): fetch data in forward direction and move cursor on next element
Object previous(): fetch data in backward direction and move cursor on previous element
void remove(): remove data from collection at the time of traversing
void set(E): replace element in collection
void add(E): add new element in collection using ListIterator.
int previousIndex():
int nextIndex();
Example: we want to create vector with 5 elements and fetch its data in backward direction

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.

Following code shown meaning of above description.


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();
int index = v.indexOf(data);
if(index!=-1) {
System.out.println("Data found");
}
else {
System.out.println("Data not found");
}
}
}

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.

4) Fetch data from user defined objects using a getter () method.


Iterator i = v.iterator();
while(i.hasNext()
{ Object obj = i.next();
Employee e =(Employee)obj;
System.out.println(e.getName()+"\t"+e.getId()+"\t"+e.getSal());
}

Shown in following diagram.

Following code shows storing employee object in collection and retrieve it


package org.techhub;
import java.util.*;
class Employee{
private int id;
private String name;
private int sal;
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;
}

}
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);

Employee emp2 = new Employee();


emp2.setId(2);
emp2.setName("XYZ");
emp2.setSal(20000);

Employee emp3 = new Employee();


emp3.setId(3);
emp3.setName("PQR");
emp3.setSal(30000);

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.

Steps to create above application


1) Create POJO class name as Player
package org.techhub;
public 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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int run;
private int age;
}
2) Create one more class with main method name as PlayerDriverApplication
package org.techhub;
public class PlayerDriverApplication {
public static void main(String[] args) {
}
}
3) Create Collection which we want to use
package org.techhub;
import java.util.*;
public class PlayerDriverApplication {
public static void main(String[] args) {
Vector v = new Vector();
}
}
4) Create array of object of Player and assign its size at run time and store data in player object
and store in 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++) {
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]);
}

}
}
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());
}
}
}

6) Remove the player from collection whose age is greater than 35


Steps: 1) fetch data from collection using single single object.
2) Convert Object class in to Player class.
3) Fetch age from Player object.
4) remoe player object using iterator method
5) display the list of player after deletion of record.

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

Interview Question on Vector?

Q. what is default capacity of Vector?


Q. what happen if Vector cross its capacity?
Q. Is Vector thread safe or not?
Q. is Vector is legacy collection?
Q. is Vector synchronized Collection?
Q. what is threshold of vector?
Threshold of Vector is 1 means 100%. Threshold normally represent in the form of probability
In the case of collection threshold represent memory required after capacity cross by collection
Here initially capacity of vector is 10 so when we try to add more element than its capacity then
vector allocate double memory than its current capacity means allocate 100% memory than its
current capacity so in terms of probability we can say threshold is 1

Q. what is logic of double capacity increment of Vector?


newcapacity= size > currentCapacity ? currentCapacity+currentCapacity: currentCapacity;

ArrayList: ArrayList is same like as Vector with some major differences.

Q. what is diff between ArrayList and Vector?


ArrayList Vector
1) ArrayList is non legacy collection Vector is legacy collection
2) ArrayList is a synchronized collection Vector is synchronized collection
3) ArrayList is occupy half memory than its Vector occupy double memory than current capacity
current capacity when capacity get cross when capacity cross
4) threshold of ArrayList is 0.5 Threshold of Vector is 1
5) logic of capacity increment of ArrayList is like Logic of capacity increment of Vector is like as
as Newcapacity=size>currentCapacity?currentCapacity+c
Newcapacity = urrentCapacity?currentCapacity.
size>currentCapacity?currentCapacity+currentC
apacity>>1:currentCapacity

Q. what are similarities between ArrayList and Vector?


1) Both are implementer class of List interface or List collection
2) Default capacity of Vector and ArrayList is 10
3) Both work as dynamic array.
Constructor of ArrayList
1) ArrayList (): Create ArrayList with default capacity 10
Example using above contstructor?
package org.techhub;
import java.util.*;
public class ArrayListApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList al = new ArrayList();
al.add(10);
al.add(20);
al.add(30);
for(Object obj:al) {
System.out.println(obj);
}
}
}
Note: default capacity of ArrayList is 10 so when user want to set its initial capacity then he can
constructor given below.

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.

Now we want to start mini project using ArrayList


Objective: we want to design VotingApplication using ArrayList Collection The Major motive of this
project is 1) Add voter 2) View Voter 3) Delete Voter 4) Search Voter etc
Task
1) Add New Voter (voter details – name, age, address (plot no, ward, village, taluka, district, state),
email, contact, voterid, gender)
2) View All Voters
3) View ward wise voter
4) View taluka wise voter count
5) View village wise voter count
6) View Age wise Voter count
7) Delete voter using voter id
8) Update voter using voterid.

Steps to implement above scenario

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.

Source code of Voter class


package org.techhub.model;
public class Voter {
private int voterId;
private String name;
Address address;//Voter has address
public int getVoterId() {
return voterId;
}
public void setVoterId(int voterId) {
this.voterId = voterId;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getContact() {


return contact;
}

public void setContact(String contact) {


this.contact = contact;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public String getGender() {


return gender;
}

public void setGender(String gender) {


this.gender = gender;
}

private String email;


private String contact;
private int age;
private String gender;
}
Source code of Address
package org.techhub.model;
public class Address {
private int plotNo;
private int wardNo;

public int getPlotNo() {


return plotNo;
}

public void setPlotNo(int plotNo) {


this.plotNo = plotNo;
}

public int getWardNo() {


return wardNo;
}

public void setWardNo(int wardNo) {


this.wardNo = wardNo;
}

public String getVillage() {


return village;
}

public void setVillage(String village) {


this.village = village;
}

public String getTaluka() {


return taluka;
}

public void setTaluka(String taluka) {


this.taluka = taluka;
}

public String getDistrict() {


return district;
}

public void setDistrict(String district) {


this.district = district;
}
public String getState() {
return state;
}

public void setState(String state) {


this.state = state;
}

public int getVoterid() {


return voterid;
}

public void setVoterid(int voterid) {


this.voterid = voterid;
}
private String village;
private String taluka;
private String district;
private String state;
private int voterid;
}
2) Create Repository class
Repository is term in development where we perform all database logics means adding data in
database, retrieving data from database, search data from database etc here we use collection as
temporary database means here we create one more class name as VoterRepository in this class we
create object of ArrayList collection and we define methods in Repository class for perform different
operation on collection.
package org.techhub.repository;
import java.util.*;
import org.techhub.model.Voter;
public class VoterRepository {
ArrayList al = new ArrayList();
void addNewVoter(Voter voter) {
al.add(voter);
}
}
3) Create one more class name as Driver class or main method where we create object POJO store
data in it and as well as create object of repository and pass POJO object to repository for perform
different operation.

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
}
}

Ward wise voter list logic


package org.techhub.repository;
import java.util.*;
import org.techhub.model.Address;
import org.techhub.model.Voter;

public class VoterRepository {


ArrayList al = new ArrayList();
public void wardWiseVoterCount() {
ArrayList wardNoColl=new ArrayList();
for(Object obj:al) {
Voter v =(Voter)obj;
Address ad=(Address)v.getAddress();
boolean b= wardNoColl.contains(ad.getWardNo());
if(!b) {
wardNoColl.add(ad.getWardNo());
}
}
for(Object obj:wardNoColl) {
Integer wardNo=(Integer)obj;
System.out.println("Ward No "+wardNo+" ");

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

Q. what is diff between LinkedList and ArrayList?

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;

public class Product {

private String name;

public Product(String name,int id,int price) {


this.name=name;
this.id=id;
this.price=price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public int getPrice() {


return price;
}

public void setPrice(int price) {


this.price = price;
}
private int id;
private int price;
}
package org.techhub;
import java.util.*;
public class LinkedListApp {
public static void main(String[] args) {
LinkedList lst = new LinkedList();
lst.add(new Product("ABC",1,10));
lst.add(new Product("MNO",2,20));
lst.add(new Product("PQR",3,30));
for(Object obj:lst) {
Product p=(Product)obj;
System.out.println(p.getId()+"\t"+p.getName()+"\t"+p.getPrice());
}
}
}

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.

Constructor of Stack: Stack has only one constructor


Stack (): this constructor is used for create empty stack.
Methods of Stack
void push(E): this method is used for push element in stack.
Object pop(): this method is used for remove top most element from stack.
boolean isEmpty(): this method check stack is empty or not if empty return true otherwise return
false.
Object peek(): this method can fetch only top most data not remove.
Example: we want to perform following operation on Stack
Case 1: Add New Element in Stack
Case 2: View All Elements From Stack
Case 3: Remove element from Stack
Case 4: Peek element from a Stack.

Source code
package org.techhub;

import java.util.*;

public class StackApplication {

public static void main(String[] args) {


// TODO Auto-generated method stub
Stack s = new Stack();
do {
Scanner xyz = new Scanner(System.in);
System.out.println("1:Add New Element");
System.out.println("2:View All Element");
System.out.println("3:Remove Top Most element");
System.out.println("4:Peek Top Most element");
System.out.println("Enter your choice");
int choice = xyz.nextInt();
switch (choice) {
case 1:
System.out.println("Enter value in Stack");
int value=xyz.nextInt();
s.push(value);
break;
case 2:
ListIterator li=s.listIterator(s.size());
while(li.hasPrevious()) {
Object obj = li.previous();
System.out.println(obj);
}
break;
case 3:
boolean b= s.isEmpty();
if(b) {
System.out.println("Stack is empty");
}
else {
Object obj = s.pop();
System.out.println("Delete value is "+obj);
}
break;
case 4:
b= s.isEmpty();
if(b) {
System.out.println("Stack is empty");
}
else {
Object obj = s.peek();
System.out.println("Top value is "+obj);
}
break;
default:
System.out.println("wrong choice");
}
} while (true);// infinite loop
}
}
Collections class

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.

Methods of Collections class


public static void sort(List): this method is used for sort the list collection with primitive data type
value like as integer,float etc
public static void sort(List,Comparator): this method is used for sort the list collection with user
defined objects.
public static Object max(Collection): find maximum value from Collection means this can work with
any type of collection in it.
public static Object min(Collection): find minimum value from Collection means this can work wity
any type of Collection.
public static void reverse(List): this method is used for reverse the list collection
public static List synchronizedList(List): this method is used for convert asynchronous collection
object in to synchronous collection object.
public static Set synchronizedSet(Set): this method is used for convert asynchronous collection
object in to synchronous collection object.
public static Map synchronizedMap(Map): this method is used for convert asynchronous Map to
synchronized map.
public static List unmodifiableList(List): this method is used for convert mutable list collection to
immutable list collection.
public static Set unmodifiableSet(Set): this method is used for convert mutable set collection to
immutable set collection.
public static Map unmodifiableList(Map ): this method is used for convert mutable Map to
immutable Map collection.
etc
Example: WAP to create ArrayList Collection and store 5 values in it and find Maximum and
Minimum Value using Collections class.
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);
Object maxValue=Collections.max(al);
Object minValue=Collections.min(al);
System.out.println("Maximum value is "+maxValue);
System.out.println("Minimum value is "+minValue);
}
}
Example: Create ArrayList collection with 5 values and reverse it using Collections class.
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 Reverse ");
for(Object obj:al) {
System.out.print(obj+"\t");
}
Collections.reverse(al);
System.out.println("\nAfter Reverse ");
for(Object obj:al) {
System.out.print(obj+"\t");
}
}
}

Q. When to use synchronized methods like as synchronizedList(),synchronizedSet() etc?


Normally this method refer when developer want to mark asynchronous collection as synchronous
collection
Example: if we think about ArrayList it is by default Asynchronous collection but if we want to
convert ArrayList object from asynchronous to synchronous we can use synchronizedList() method
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);
List list=Collections.synchronizedList(al);
//here list reference is synchronized.
}
}
Q. what is use of unmodifiableList() method?
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);
List list=Collections.unmodifiableList(al);
//here list reference is un modifiable means we cannot perform any operation on
//list reference in line 11 and if we ty to modify it then we get exception UnSupportedException at
run //time.

}
}
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);
}
}
}

Example: Create ArrayList and store 5 employee data in it and sort it .


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

public String getName() {


return name;
}
public int getId() {
return id;
}
public int getSal() {
return sal;
}
}
public class ArrayListApp {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Employee("ABC",3,1000));
al.add(new Employee("MNO",4,5000));
al.add(new Employee("PQR",2,3000));
al.add(new Employee("STV",5,9000));
al.add(new Employee("XYZ",1,2000));
System.out.println("Before Sorting");
for(Object obj:al) {
Employee emp=(Employee)obj;
System.out.println(emp.getId()+"\t"+emp.getName()+"\t"+emp.getSal());
}
Collections.sort(al);
System.out.println("After Sorting");
for(Object obj:al) {
Employee emp=(Employee)obj;
System.out.println(emp.getId()+"\t"+emp.getName()+"\t"+emp.getSal());
}
}
}
if we think about above code we have ClassCastException at run time because we try to sort()
Collection whose contain user defined object and Collections.sort() method cannot perform sorting
by default on user defined object if we think about above code we have Employee class which
contain three attribute id,name and sal and we store 5 object in ArrayList of employee class we have
statement Collections.sort(al) so here we get ClassCastException because Collections.sort() method
cannot predict on which field sorting apply means employee data can be sort by id,by name or by sal
so this type of decision cannot take collections.sort() method it is choice of user so this major reason
we get ClassCastException at run time.
Means we can say if Collection contain user defined objects then Collections.sort() method cannot
sort by default so if we want to solve this problem Java Provide two ways to us means if we want to
sort collection with user defined objects then java provide two ways
1) Use Comparable interface
2) Use Comparator interface
Comparable and Comparator interface specially design apply sorting on user defined objects.

Now we want to discuss about Comparable interface


Steps to Comparable interface
1) Add java.lang package in application
import java.lang.*;
Note: java.lang is default package of java means so user not needs to import it.

2) Create POJO class and implements Comparable interface in it


package org.techhub;
import java.util.*;
class Employee implements Comparable
{
private int id;
private String name;
private int sal;
Employee(String name,int id,int sal){
this.name=name;
this.id=id;
this.sal=sal;
}

public String getName() {


return name;
}
public int getId() {
return id;
}
public int getSal() {
return sal;
}
}
3) Override its compareTo () method and perform comparison
int compareTo(Object): this method accept single object as parameter for comparison and return
result in the form of integer.
Rules of compareTo()
1) If first object is greater than second object then return 1
2) If first object is less than with second object then return -1
3) If first object is equal with second object return 0

Example: we want to sort employee by using its id.


package org.techhub;
import java.util.*;
class Employee implements Comparable {
private int id;
private String name;
private int sal;

Employee(String name, int id, int sal) {


this.name = name;
this.id = id;
this.sal = sal;
}

public String getName() {


return name;
}

public int getId() {


return id;
}

public int getSal() {


return sal;
}

@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;
}
}
}

public class ArrayListApp {


public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Employee("ABC", 3, 1000));
al.add(new Employee("MNO", 4, 5000));
al.add(new Employee("PQR", 2, 3000));
al.add(new Employee("STV", 5, 9000));
al.add(new Employee("XYZ", 1, 2000));
System.out.println("Before Sorting");
for (Object obj : al) {
Employee emp = (Employee) obj;
System.out.println(emp.getId() + "\t" + emp.getName() + "\t" +
emp.getSal());
}
Collections.sort(al);
System.out.println("After Sorting");
for (Object obj : al) {
Employee emp = (Employee) obj;
System.out.println(emp.getId() + "\t" + emp.getName() + "\t" +
emp.getSal());
}
}
}

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.*;

class Player implements Comparable {


private int id;
private String name;

public Player(String name, int id, int run) {


this.name = name;
this.id = id;
this.run = run;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getRun() {


return run;
}
public void setRun(int run) {
this.run = run;
}
private int run;
@Override
public int compareTo(Object o) {
Player p = (Player) o;
if (this.getRun() > p.getRun()) {
return 1;
} else if (this.getRun() < p.getRun()) {
return -1;
} else {
return 0;
}
}
}

public class PlayerApplication {


public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Player("ABC", 1, 5000));
al.add(new Player("MNO", 3, 2000));
al.add(new Player("PQR", 2, 4000));
al.add(new Player("STV", 4, 6000));
System.out.println("display player record before sorting");
for (Object obj : al) {
Player p = (Player) obj;
System.out.println(p.getId() + "\t" + p.getName() + "\t" + p.getRun());
}
Collections.sort(al);
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());
}
}
}
Comparator interface

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

1) Add java.util package in application


2) Create different class and implement Comparator interface in it
Example: Suppose we have Player with attribute name , id and run and we want to sort player by id
on case 1 and by run on case 2.
So here we have to create three classes one is Player pojo , one class sort sorting by id , one class for
sorting by run so we have to implement Comparator interface in SortById class and SortByRun class.

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;
}
SortPlayerById.java
package org.techhub;
public class SortPlayerById implements Comparator {
}
SortPlayerByRun.java
package org.techhub;
public class SortPlayerByRun implements Comparator {
}
3) Override compare () method of Comparator interface
int compare(Object obj1,Object obj2): this method accept two objects as parameter and compare it
Rules of compare
1) If first object is greater than second object return 1
2) If first object is less than second object return -1
3) If first object is equal with second object return 0

Example Logic sort by Id


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;
}
}
}
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.

4) Use Collections.sort() in given fashion


Syntax: Collections.sort(List,Comparator): this method contain two parameters
List: this parameter contain all user defined objects
Comparator: we can pass here implementer class object of Comparator or Comparator reference.

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;

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;


}

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.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;
}
}
}

public class PlayerApplication {


public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Player("ABC", 1, 5000));
al.add(new Player("MNO", 3, 2000));
al.add(new Player("PQR", 2, 4000));
al.add(new Player("STV", 4, 6000));
Scanner xyz = new Scanner(System.in);
System.out.println("1:Sort Player By Id");
System.out.println("2:Sort Player By Run");
System.out.println("Enter your choice");
int choice = xyz.nextInt();

System.out.println("display player record before sorting");


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

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

Q .What is difference between Collections and Collection?


Collections Collection
Collections is a utility class Collection is interface
Several utility methods that are used to operate It is used to represent a group of individual
on collection objects as single unit.
Collections are a utility class which contains only The collection is an interface contain default
static methods. methods, static methods and abstract methods

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) {

ArrayList al = new ArrayList();


al.add(10);
al.add(20);
HashSet hs = new HashSet(al);
System.out.println(hs);
}
}

Q. Create ArrayList Collection and remove duplicated from ArrayList?


In this case you can pass ArrayList or any List collection in Set Collection as parameter then Set
removes duplicated value because Set not allowed elements
package org.techhub;
import java.util.*;
public class HashSetCollectionApp {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);
al.add(20);
al.add(10);
al.add(30);
al.add(20);
HashSet hs = new HashSet(al);
al.clear(); //remove all elements
al.addAll(hs);
System.out.println(al);
}
}
if we think about above code then we store data in ArrayList which contain duplicated values and we
pass ArrayList as reference in HashSet so HashSet removes duplicated values and we clear all data of
ArrayList again we store all data of HashSet in ArrayList using addAll() methods so we get all unique
data from HashSet to ArrayList.

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

Q. what is Object class?


Object class is parent of every class in java.

Q. Can you create application or program without inheritance in java?


No because in 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 means we not need to import it in program.

Q. why Object class is parent of every class in Java?


Because Object class contain some inbuilt methods which is necessary to all class or every class in
java
Methods of Object class?
int hashCode()
boolean equals()
String toString()
Object clone()
void wait()
void wait(int)
void notify()
void notifyAll()
Class getClass()
void finalize()
static{
}

Now we want to discuss about int hashCode() and equals() method


Before start hashcode and equals method we have one example

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.

Syntax: long variable = System.identityHashCode(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.

Q. can we compare two objects in java using == symbol?


No

Q. how we can perform Object comparison in java?


if we want to perform comparison or compare two objects with each other in java then we have to
use
boolean equals() method and int hashCode()

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.

Thumb rules of Object comparison in java


1) if two objects same then hash code of objects must be same
2) if hash code of object same then their values must be same.

How to use equals() method


if we want to use equals() method we have to override() equal() method in class who objects we
want to compare.

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;
}
}

public class ObjectclassTestApp {


public static void main(String[] args) {
Test t1 = new Test(100);
Test t2 = new Test(200);
System.out.println("JVM Hashcode of t1 " + System.identityHashCode(t1));
System.out.println("JVM HashCode of t2 " + System.identityHashCode(t2));

if (t1.equals(t2)) // hashcode of t1 ==hashcode of t2


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

}
}
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;

public boolean equals(Object obj) {


Player p=(Player)obj;
if(p.id==this.id && p.name.equals(this.name) && p.run==this.run) {
return true;
}
else {
return false;
}
}
public int hashCode() {
return id*100;
}
}
public class SetWithUserDefinedObjectApplication {

public static void main(String[] args) {


LinkedHashSet hs = new LinkedHashSet();
Player p1 = new Player("ABC",1,1000);//100
Player p2 = new Player("MNO",2,2000);//200
Player p3 = new Player("PQR",3,2000);//300
Player p4 = new Player("ABC",1,1000);//100
hs.add(p1);
hs.add(p2);
hs.add(p3);
hs.add(p4);
for(Object obj:hs) {
Player p=(Player)obj;
System.out.println(p.getId()+"\t"+p.getName()+"\t"+p.getRun()+"\t"+System.identityHashCode(p));
}

}
Object cloning concept
Object cloning means if create duplicated copy of object called as object clone

Q. why we need to use Object cloning concept?


Some time if we apply multiple references on single object then there is possibility object original
content may be loss
because when we apply multiple reference with same object and if we try to change object content
using any reference then previous content of object may be get loss and if we want to solve this
problem we have object cloning concept provided by java to us.

Example single object with multiple references

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.

How to Create Object clone in JAVA

if we want to perform object clone in java we have following steps.


1) add java.lang package in application
2) Create user defined class and implements Cloneable interface
Note: Cloneable is marker interface in java
Q. what is marker interface?
Marker interfaces means interfaces having some special run time enviourment provided by JVM
class Square implements Cloneable
{ int no;
void setValue(int x) {
no=x;
}
void showSquare() {
System.out.printf("Square is %d\n", no*no);
}
}
3) Create one user define method and return same class object from it and handle
CloneNotSupportedException

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();
}
}

Above diagram shows implementation of object 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) {

ArrayList al = new ArrayList();


al.add(new Player("A",1,10000));
al.add(new Player("B",2,20000));
al.add(new Player("C",3,30000));
al.add(new Player("D",4,40000));
al.add(new Player("E",5,50000));
System.out.println(al);

}
}

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.

Example: package org.techhub;

public class PlayerApplication {


static {
System.out.println("I am static block");
}
public static void main(String[] args) {

System.out.println("I am main method");

}
}
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.

How to store different type of data in collection in the case of generics


If we want to store different type of data in collection using a generics we have to create POJO class
and store POJO objects in collection and in that POJO object can store different data and we can use
POJO class name with generics and collection

Source code example


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

public String toString() {


return "[" + name + "," + id + "," + per + "]";
}
}
public class GenericApplication {
public static void main(String[] args) {
ArrayList<Data> al = new ArrayList<Data>();
al.add(new Data("A", 1, 50.5f));
al.add(new Data("B", 2, 55.5f));
al.add(new Data("C", 3, 50.5f));
for (Data d : al) {
System.out.println(d);
}
}
}
Types of Generics
1) Class with Generics:
2) Interface with Generics
3) Wildcard Generics
a) Bounded generics
b) Unbounded generics
If we want to work generics type we have some inbuilt classes which work as generic type
a) E: this generic element class denoted generic types normally this E we use when we want
to send generic value as parameter in function or constructor
b) T: this is generic type and T denote generate type of value and we use it when we want
to return generic values
c) K – generic key
d) V – generic value

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

2) lower bounded: lower bounded generics only allow child objects


syntax: ? super parentname
Example:
package org.techhub.gen;
import java.util.*;
abstract class Value
{ int a,b;
abstract void setValue(int x,int y);
abstract int getResult();
}
class Add extends Value
{ @Override
void setValue(int x, int y) {
this.a=x;
this.b=y;
}
@Override
int getResult() {
return a+b;
}
}
class Mul extends Value
{ @Override
void setValue(int x, int y) {
this.a=x;
this.b=y;
}
@Override
int getResult() {
return a*b;
}

}
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 {

public static void main(String[] args) {


HashMap <Integer,String> map = new HashMap<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());
}

}
}

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.

Example using LinkedHashMap


package org.techhub;
import java.util.*;
public class HashMapApplication {
public static void main(String[] args) {
LinkedHashMap <Integer,String> map = new LinkedHashMap<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());
}

}
}
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.

Source code Example


package org.techhub;
import java.util.*;
public class MapWithCollectionApplication {

public static void main(String[] args) throws Exception


{ LinkedHashMap<String,ArrayList> map = new LinkedHashMap<String,ArrayList>();
ArrayList<String> india = new ArrayList<String>();
india.add("Rohit");
india.add("Virat");
india.add("Hardik");
ArrayList<String> aus = new ArrayList<String>();
aus.add("Steve");
aus.add("Warnar");
aus.add("Finch");
map.put("India", india);
map.put("Aus", aus);
Set<Map.Entry<String, ArrayList>> data=map.entrySet();
for(Map.Entry<String, ArrayList> d:data) {
String teamName=d.getKey();

System.out.println("========================"+teamName+"======================
==");
ArrayList<String>playerList=d.getValue();
for(String pName:playerList)
{
System.out.println(pName);
}
}
}
}

Example: Map within Map

Source code Example


package org.techhub;
import java.util.*;
public class MapWithinMapApplication {

public static void main(String[] args) {


LinkedHashMap<String, LinkedHashMap<Integer, String>> map;
map = new LinkedHashMap<String, LinkedHashMap<Integer, String>>();

LinkedHashMap<Integer, String> cseStud = new LinkedHashMap<Integer, String>();


cseStud.put(1, "a");
cseStud.put(2, "b");
cseStud.put(3, "c");

LinkedHashMap<Integer, String> etcStud = new LinkedHashMap<Integer, String>();


etcStud.put(1, "a");
etcStud.put(2, "b");
etcStud.put(3, "c");
map.put("CSE", cseStud);
map.put("ETC", etcStud);
Set<Map.Entry<String, LinkedHashMap<Integer, String>>> data = map.entrySet();
System.out.println("=======================================");
for (Map.Entry<String, LinkedHashMap<Integer, String>> d : data) { String
deptName = d.getKey(); System.out.println(deptName);
System.out.println("===========================");
LinkedHashMap<Integer, String> studData = d.getValue();
Set<Map.Entry<Integer, String>> stud = studData.entrySet();for
(Map.Entry<Integer, String> s : stud) {
System.out.println(s.getKey() + " ------------ >" + s.getValue());
} System.out.println("================================");
}
}
}
Q. what is diff and similarties between HashMap ,LinkedHashMap and TreeMap?

Property HashMap LinkedHashMap TreeMap


Time Complexity O(1) O(1) O(1)
of(Big o noation)
Get,put,contains
key and
remove()
method
Iteration order Random According to user Arrange in Ascending
sequence order
Null keys Allow Allow Not Allowed
Implemented Map Map Map,SortedMap and
interfaces NavigableMap
Synchronization Not synchronized and if Not synchronized and if Not synchronized and if
we want to make we want to make we want to make
synchronized use synchronized use synchronized use
Collections.synchronized Collections.synchronized Collections.synchronized
Map() method Map() method Map() method
Data structure List of buckets if more DoublyLinkedList with list Red-Black (it is like self-
than 8 entries in bucket of buckets balancing binary search
then java 8 will switch to tree) implemented of
balanced tree from Binary Tree. this data
linkedlist structure offer O(lon n)
for insertion ,deletion
and search operation and
O(n) space complexity
Application General purpose, fast Can be use as LRU cache Algorithms where sorted
retrival,non synchronized others places insertion or for Navigable feature are
access order matter required
Requirements Equals() and hashcode() Equals() and hashcode() Comparator needs to
for keys method need to method need to override supplied for key
overridden implementation
otherwise natural order
will be used to sort keys
Multithreading: before multi threading we need know
Q. what is thread?
___________________________________________________________
Thread is subpart of process or we can say it is light weight process
Q. what is process?
Running program in ram called as process.
Q. what is multi threading?
To utilize idle period of processor or we can say to execute multiple thread simultaneously in waiting of each other
called as multi threading.
Note: Threading is a concept of Operating system and java is language which implement concept of threading.
If we want to implement thread in java we have two ways

1) Using Thread class


2) Using Runnable interface.

How to implement thread practically using Thread class?


_________________________________________________________________________________
If we want to implement thread using a Thread class we have some following steps.

1) Add java.lang package in application


import java.lang.*;
Note: java.lang is a default package of means we not need to import it.

2) Create class and inherit Thread class in it.


class MyThread extends Thread
{
}

3) Override run () method for writing Thread logics


run() is a method which specially design for execute thread logics or run thread logic written by programmer.
run() is not a method Thread class it is originally method of Runnable interface and Thread is a implementer class of
Runnable interface.
Internal class hierarchy
interface Runnable {public abstract void run();
}
class Thread implements Runnable{
}

class MyThread extends Thread{


public void run(){
for(int i=1; i<=5; i++)
{ System.out.printf(“I =%d\n”,i);
}
}
}

4) Create object of thread class child class


MyThread thread = new MyThread();

5) Use Thread methods for work with thread.


1) void start() 2) static void sleep(int milliseconds) 3) void stop() 4) void join() 5)boolean isAlive()
6) void wait(int) 7 ) void notify() 8)void notifyAll() 9)boolean yield(int)
etc
Now we want to discuss about start(), sleep() ,stop(),join() and isAlive() methods

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();
}
}

Synchronization in Thread and asynchronization in Thread


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

Q. what is resource?
_________________________________________________________________________
Here resource indicate object

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

wait(),notify() and notifyAll() method


_______________________________________________________________________
wait() method help us to thread execution for specified time period
wait() is a method of Object class and Object class is parent of every class in java and it is member of java.lang
package.
There are two types of wait in java
1) Conditional wait: conditional wait means if thread re-execute it self after specified time period called as
conditional wait.
Syntax: void wait(int milliseconds);

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

Q. what is diff between notify () and notifyAll()?


________________________________________________________________________
notify () can call only one thread at time in queue format means first waited thread call first and notifyAll() call all
waited thread at a time in last in first out format in the form of stack.

Q. what is similarities between notify () and notifyAll()?


1) Both are member of Object class
2) Both uses for send request for waited thread for re-execution if threads in un conditional wait
3) Both need synchronized 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.

int getPriority(): this method return current priority of thread

Important points related thread and priority


1) Every thread has normal priority as default priority
2) Every Program must have one thread by default called as main thread.

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);
}
}

Q. what is daemon thread?


Daemon thread means thread execute as background thread called as daemon thread means daemon work as
service provider thread.
e.g Garbage collector of JVM is best example of daemon thread,finalizer etc

if we want to mark your thread as background thread we have method name as


void setDaemon(boolean): if we pass true value in it then your thread work as background thread.
boolean isDaemon(): this method return true if your thread is daemon otherwise return false.

How to implement thread by using a Runnable interface


___________________________________________________________________________
if we want to implement thread by using a Runnable interface we have following steps
before that we need to know

Q. Why we need to implement thread using a Runnable interface?


___________________________________________________________
if we use Thread class for thread implementation purpose then there is possibility of multiple inheritance and in java
we cannot achieve multiple inheritance by using classes
so we want to avoid this problem we have solution is interface so java provide Runnable interface to us for
implement thread shown in following example.
Example with thread possibility for multiple inheritances
abstract class A{
}
class B extends A,Thread{
}
if we think about above code this code indicate of multiple inheritance but it is not possible in java by classes so you
can solve above problem like as

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

Steps to implement thread by using a Runnable interface


1) Add java.lang.* package
2) Create class and implement Runnable interface in it
3) Override its run() method and write its logic
4) Create object of Thread child class
5) Create object of Thread class and pass thread child object in its constructor
6) Call start() method and use thread methods for manage thread.
IOStreams/File Handling:
Q. what is stream?
Stream means if we transfer data from one location to another location called as stream means if we
transfer data between one memory to another memory or from one computer to another computer in
network called as streaming.
Using iostream we can store your program output in hard disk file or you can read your hard disk data by
java program.
Means using iostream you can store data permanently on hard disk.
if we want to work with iostream in java we have package name as java.io package and in this package
contain some classes and interfaces those help us to work with files using java language.
if we want to transfer data from one machine to another machine or from one memory to another
memory we need to know its path.
if we want to work with path in java we have class name as File it is member of java.io package.

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 ");
}
}
}

How to create folder using File class?


if we want to create folder using file class we have following method
boolean mkdir(): this method is used for create new folder
boolean exists(): this method is used for check folder or file is present on specified path or not if present
return true otherwise return false.

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 .................................... ");
}
}

How to write data in file or how to read data from file

If we want to work with file in java we have two ways

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.

How to write or read in text 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.

Methods of Writer class


void write(char): this method help us to write single character data in file at time.
void write(String data): this method help us to write string data in file
void write(char[]): this method help us to write character array data in file
void write(char[],int offset,int length): this method help us to write specified length of data in file.
Parameter details
char[]: this parameter is used for hold character array means in this parameter contain complete
character array data.
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 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.

Now we want to discuss about FileWriter class

Constructor of FileWriter class


FileWriter(String path): this constructor help us to accept file path using a string format.
FileWriter(File path): this constructor help us to accept file path using File class reference.
FileWriter(String path, boolean mode):
Parameter details
String path: accept file path using file class reference
boolean mode: mode decide which operation we want to perform on file if we pass true then we can use
append operation with file and if we false then we can use write mode with file.
by default FileWriter class work with append mode.

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.

FileWriter(File path, boolean mode):


Parameter details
File path: accept file path using file class reference
boolean mode: mode decide which operation we want to perform on file if we pass true then we can use
append operation with file and if we false then we can use write mode with file.
by default FileWriter class work with write mode.

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

it. 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\\demo.txt");fw.write(data);
fw.close();
System.out.println("Record Save Success. ................ ");
}
}

Above code demonstrate example of write mode.


Example of append
mode. 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\\demo.txt",true); fw.write(data);
fw.close();
System.out.println("Record Save Success. ................ ");
}
}
if we think about FileWriter class then we can add data in file using single line means we cannot
add data on new line in file using a FileWriter so if we want to add data on new line in file we have
BufferedWriter class

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

Reader class is used for read textual data from file


Reader is abstract class and it is parent of all text data reading classes in java and it contain some
abstract methods which help us to read textual content from file.
Following diagram shows hierarchy of Reader class.

Methods of 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.

Constructor of BufferedReader class


BufferedReader (Reader): this constructor accepts reference of any class which is child of Reader class.
package org.techhub;
import java.io.*;
public class ReadDataLineByLineApp {
public static void main(String[] args)throws IOException,InterruptedException {
FileReader fr = new FileReader("C:\\Program Files\\Java\\jdk1.8.0_291\\bin\\TestABC.java");
BufferedReader br = new BufferedReader(fr);
String line;
while((line=br.readLine())!=null)
{ System.out.println(line);
Thread.sleep(500);
}
}
}
Stream classes

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

Following class Hierarchy shows the 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.

Methods of OutputStream class


void write(byte): this method is used for write single single byte in
file. void write(byte[]): this method is used for write byte array data in
file.
void write(byte[],int offset,int length): write a specified size of byte data in file
void close(): close the byte stream or file.
Now we want to discuss about FileOutputStream class

Constructor of FileOutputStream class

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

InputStream class help us to read data byte by byte from file.


Following class diagram shows the 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.

Methods of InputStream class

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.

1) Add java.io package in application


import java.io.*;
2) Create POJO class and implements Serializable interface in
it. package 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;
}
3) Create Object of ObjectOutputStream class : ObjectOutputStream class is used for write object
data in file
Constructor of ObjectOutputStream
class Syntax:
ObjectOutputStream(OutputStream): this constructor is used accept stream class object
as parameter.
FileOutputStream fout = new
FileOutputStream("D:\\OCT2022\\JAVA"); ObjectOutputStream oout =
new ObjectOutputStream(fout);

4) Call its writeObject() method and store data in file


if we want to store object data in file we have writeObject() method of ObjectOutputStream class

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.

How to Perform Deserialization


If we want to perform deserialization in java we have ObjectInputStream class and its
readObject() method.

Constructor of ObjectInputStream class


ObjectInputStream(InputStream): this constructor accept any child of input stream or input stream
reference.
Object readObject(): this method can read any class data just we need to cast it in its original format.
package 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,
ClassNotFoundException{ FileInputStream finf = new
FileInputStream("D:\\OCT2022\\JAVA\\emp.txt"); ObjectInputStream
oinf = new ObjectInputStream(finf);
Object obj = oinf.readObject();
if(obj!=null) {
Employee e =(Employee)obj;
System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getSal());
}
}
}
Assignments

You might also like