Java Ebook by Durga Sir
Java Ebook by Durga Sir
com
Java E-Book
Durga Software Solution
By- Durga Sir, Ameerpet Hyderabad
Point to be remember-
JRE- Java Runtime Environment. It is the implementation of JVM. It physically exists.
It contains set of libraries + other files that JVM uses at runtime.
Page 1
https://gits-sln.blogspot.com Durga sir Java Notes
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVM=Interpreter + JIT compiler
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
Page 2
https://gits-sln.blogspot.com Durga sir Java Notes
Note- JIT (just in time compiler) is used to increase the speed of execution of a java program.
Classloader-
Used to load class files. There are three built-in classloaders in Java.
1) Bootstrap ClassLoader: It loads the rt.jar file which contains all class files of Java Standard
Edition
2) Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of
System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3) System/Application ClassLoader: It loads the classfiles from classpath. By default, classpath
is set to current directory.
Page 3
https://gits-sln.blogspot.com Durga sir Java Notes
Page 4
https://gits-sln.blogspot.com Durga sir Java Notes
Page 5
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
Inheritance concept applicable for the main method hence while executing the child class if
child does’t contain main() method then parent class main method will be executed.
Overloading method is applicable for main()
Overriding is applicable for main() but it is not overriding it is known as method hiding .
Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
Page 6
https://gits-sln.blogspot.com Durga sir Java Notes
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Note-If you do not specify any access level, it will be the default.
Page 7
https://gits-sln.blogspot.com Durga sir Java Notes
Synchro Yes(blo No
nized ck)
Native Yes No
Transicn Yes
t
Page 8
https://gits-sln.blogspot.com Durga sir Java Notes
Volatile Yes
If a member declare as protected then we can access that member anywhere within current
package but only in the child classes of outside the package.
Protected= default + kids
We can access protected members within the current package anywhere by using parent
reference or child reference but outside package we can access protected member only in
child classes and we should use child reference only.
package com.java.test;
public class A
{
protected void m()
{
System.out.println("the most misunderstood method");
}
}
class B extends A
{
public static void main(String args[])
{
A a=new A();
a.m();
B b=new B();
b.m();
A a1=new B();
a1.m();
}
}
Page 9
https://gits-sln.blogspot.com Durga sir Java Notes
package com.java.test;
import com.java.test.A;
class C extends A
{
}
class D extends C
{
public static void main(String args[])
{
//A a=new A();
//a.m();
//A a1=new C();
//a1.m();
//C c=new C();
//c.m();
D d=new D();
d.m();//only this case is valid other all possible cases not valid
}
}
Identifiers
class A
{
public static void main(String[] args)
{
int x=10;
}
}
In the above program we are using 5 identifiers which are in yellow highlighting colour.
Rules of Identifiers-
1. Only allowed character are a to z, A to Z, 0 to 9, $, _ (underscore sign).
2. Naming term can’t start with digit.
3. Case sensitive.
4. No length limit of identifiers (i.e. naming term length limit)
5. We cannot used reserved word.
6. All predefined java class name and interface name we can used as a identifiers.
Reserve word
It is represent a special meaning and functionality.
All the reserved word in a lower case.
In java we have only new keyword but there is no delete keyword because destruction of
useless object is the responsibility of garbage collector.
Variable
There are three types of variables in java:
1. local variable-
declared inside the body of the method. It scope is on the block level.
Before using of local variable we should be initialize the value of local variable otherwise
compiler giver compile time error.
Cannot be defined with "static" keyword.
Only applicable modifier for local variable is final modifier. If we are using final local
variable the before using of this variable should be initialization must be require. Otherwise
compile given a compile time error.
Every thread separated copy is created hence it is thread safe.
2. instance variable-
declared inside the class but outside the body of the method
cannot be defined with "static" keyword.
Page 11
https://gits-sln.blogspot.com Durga sir Java Notes
instance
Primitive
static
reference
local
class Test
{
int x=0;//instance primitive
static String s=”Ram”;//static reference
public static void main(String[] args)
{
Int[] y=new int[];//local reference
}
}
Data Types
1.Primitive data types It is predefined by the language and is named by a reserved keyword. The
primitive data types include boolean, char, byte, short, int, long, float and double. Total-8
2.Non-primitive data types: They refer to objects and hence they are called reference types. The
non-primitive data types include String, Arrays, Classes, and Interfaces.
Page 12
https://gits-sln.blogspot.com Durga sir Java Notes
When we compare with old languages java is pure object oriented language.
But when we consider alone java is not pure object oriented language because several oops
feature is not supported by java as operator overloading, multiple inheritance.
Data type of number type (integer and float) is signed type means +ve or –ve.
Character data type uses letter and number.
Boolean data type uses true and false.
byte-
size 1 byte(8 bit)
range - 28-1 to 28-1-1
short-
size 2 byte
best suitable for 16 bit processor like 8085 but this time out of dated.
Int-
Size 4 byte
long-
size 8 byte
it is used for calculation of a very long distance such as satellite.
The number of character present in a big file may exceed int range hence the return method is
long but not int. long l=f.length();
float-
size 4 byte
if we want to 5 to 6 decimal point accuracy.
double-
Page 13
https://gits-sln.blogspot.com Durga sir Java Notes
size 8 byte
if we want to 14 to 15 decimal point accuracy.
boolean-
size NA
range NA (but allowed value is true, false)
boolean b=true;
boolean b=0; CE: incompatible type found :int required: boolean
boolean b=”True” CE: incompatible type found: java.lang.string required: boolean
boolean b=True; CE: cannot find symbol symbol: variable True location: class Test
int x=0;
if(x) CE: incompatible type found :int required: boolean
sop(“hi”);
else
sop(“hello”);
char-
size 2 byte
used Unicode character set.
Note- null is the default value of any object type or object reference. So we cannot applied for
primitive data type.
Char c=null; CE: incompatible type format:<nulltype> required : char
Literal
int x=10;
intdatatype/ keyword
x variable/ identifiers
10 constant value/ literal
Page 15
https://gits-sln.blogspot.com Durga sir Java Notes
Memory representation of integer data type and float data type is completely different.
float f=10l;
Sop(f); 10.0
Page 16
https://gits-sln.blogspot.com Durga sir Java Notes
The purpose of command line argument is customized the behaviour of the main()
method.
Example-1
class Test
{
public static void main(String[] args)
{
int n=Integer.parseInt(args[0]);
System.out.println(n*n);
}
}
Java Test 5
--25
Example-2
class Rnd3
{
public static void main(String[] args)
{
for(int i=0;i<=args.length;i++)
{
System.out.println(args[i]);
}
}
}
Java Test A B C
A
B
C
RE:Array Index out of bound
Java Test A B
A
B
RE: Array Index out of bound
Java Test
RE: Array Index out of bound
If we taken < in the place of <= then no RE found in any cases.
Example-3
class Rnd3
{
public static void main(String[] args)
{
String[] argh= {"X","Y","Z"};
args=argh;
for(String s:args)
{
System.out.println(s);
}
}
}
Java Test A B C
X
Y
Z
Java Test A B
X
Page 17
https://gits-sln.blogspot.com Durga sir Java Notes
Y
Z
Java Test
X
Y
Z
Example-4
class Test
{
public static void main(String[] args)
{
System.out.println(args[0]+args[1]);
}
}
Java Test 10 20
-1020
Note- command line argument is available in string format.
Example-4
class Test
{
public static void main(String[] args)
{
System.out.println(args[0]);
}
}
Java Test “note book”
--note book
Java Test note book
--note
Class name
Page 18
https://gits-sln.blogspot.com Durga sir Java Notes
Operator in Java
Increment and Decrement Operator
Applicable only for variable not for constant value.
Applicable for all primitive data type except Boolean type.
Int x=10; Int x=10;
Int y=++x; Int y=++10; CE
Int x=10; Final int x=10;
Int y=++(++x); CE X=11; CE
Sop(x);
Page 19
https://gits-sln.blogspot.com Durga sir Java Notes
Arithmetic operator
If we are applying any arithmetic operation between two variable then result can be
found by
Example
byte a=10;
byte b=20;
byte c=a+b;//CE:PLP because a+b generate int and int to byte change is PLP
Sop(c);
The correct formation of above line is byte c=(byte)(a+b);
Example
byte b=10;
b=b+1;//CE
sop(b);
we can solve compile time error by using b=(byte)(b+1);
Example
byte b=10;
b++;
Sop(b);-11
It is internally follow as b=(type of b)(b+1);
Note-increment and decrement operator typecasting perform internally automatic.
Java Arrays
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java
We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.
To
Page 20
https://gits-sln.blogspot.com Durga sir Java Notes
Solve this problem, collection framework is used in Java which grows automatically.
Syntax to Declare an Array in Java
dataType[] arr; (or) it is a recommended (int[] x; because x is a int type array )
dataType []arr; (or)
dataType arr[];
arrayRefVar=new datatype[size];
Example 1:
int[] x;
x=new int[10];
Example 2:
int[] x=new int[10];//at the time of array creation we should create a size otherwise
compiler error found.
int[] x=new int[0];
sop(x.length); 0
int[] x=new int[-3]; RE: negative array size
at the time of declaration we can’t provide the size of array Example int[6] x;
2D array
int[][] x;
int [][]x;
int x[][];
int[] []x;
int[] x[];
int []x[];
Note: Every array type corresponding class are available under these class part of java
language not available for programmer level.
Page 21
https://gits-sln.blogspot.com Durga sir Java Notes
int[][] [ [I
double[] [ D
short[] [ S
byte[] [ B
boolean[] [ Z
int[] x={10,20,30};
Page 22
https://gits-sln.blogspot.com Durga sir Java Notes
char[] ch={‘a’,’b’,’c’};
int[] b=x;
int[] c=ch; CE:
Because element level promotion is valid in variable assignment but array level
promotion is not valid.
char --- int
char[] --- int[]
int - double
int[] -double[]
float -int
float[] - int[]
String - Object
String[] - Object[]
Anonymous array
For one time of users purpose.
For instant use purpose of an array.
Without use of naming.
Example:
public class Rnd3
{
public static void sum(int[] x)
{
int total=0;
for(int x1:x)
{
total+=x1;
}
System.out.println(total);
}
public static void main(String[] args)
{
sum(new int[] {10,20,30});
}
}
Object type array
Object[] a=new Object[10];
a[0]=new Object();
a[1]=new String(“Ram”);
a[2]=new Integer(10);
Page 23
https://gits-sln.blogspot.com Durga sir Java Notes
Uninitialized Array
For instance level
class test
{
int [] x;//instance reference variable
public static void main(string[] args)
{
test t=new test();
sop(t.x);//null
sop(t.x[0]);//RE:NPE
}
}
If we taken int[] x=new int[3];
Sop(t.x);//-[I@hashcode
Sop(t.x[0]);//-0
Page 24
https://gits-sln.blogspot.com Durga sir Java Notes
Sop(x[0]);//-0
Equivalance between varargs para method and 1-D paramenthod
m(int[] x)===m(int. . . x)
#####
That means 1D array method can be replaced in varargs method.
main(String[] args)=main(String. . .args)
but carefully understand that varargs method cannot replaced with 1D array mehod.
Class Test
{
Public static void main(string[] args)
{
Int[] a={10,20,30};
Int[] b={40,50,60};
m(a,b);
}
Public static void m(int[] . . .x)
{
for(int[] x1:x)
{
Sop(x1[0]);//---10,40
}
}
}
Method:-
1-instance method-
Instance method(s) belong to the Object of the class not to the class i.e. they can be called
after creating the Object of the class.
Every individual Object created from the class has its own copy of the instance method(s) of
that class.
Page 26
https://gits-sln.blogspot.com Durga sir Java Notes
Instance methods are not stored on a per-instance basis, even with virtual methods.
They’re stored in a single memory location, and they only “know” which object they belong
to because this pointer is passed when you call them.
They can be overridden since they are resolved using dynamic binding at run time.
// Example to illustrate accessing the instance method .
import java.io.*;
class Foo{
this.name = name;
}
}
class GFG {
public static void main (String[] args) {
GeeksforGeeks
class Geek{
geekName = name;
}
Page 27
https://gits-sln.blogspot.com Durga sir Java Notes
class GFG {
public static void main (String[] args) {
}
}
Output:
vaibhav
mohit
package com.java.test;
Note: Static variables and their values (primitives or references) defined in the class are stored
in PermGen space of memory.
Q-What if static variable refers to an Object ?
static int i = 1;
static Object obj = new Object();
In first line, the value 1 would be stored in PermGen section. In second line, the reference obj would
be stored in PermGen section and the Object it refers to would be stored in heap section.
Page 28
https://gits-sln.blogspot.com Durga sir Java Notes
Wrapper classes
A Wrapper class is a class which contains the primitive data types (int, char, short, byte,
etc). In other words, wrapper classes provide a way to use primitive data types (int, char, short,
byte, etc) as objects. These wrapper classes come under java.util package.
Why we need Wrapper Class
Wrapper Class will convert primitive data types into objects. The objects are necessary if
we wish to modify the arguments passed into the method (because primitive types are passed
by value).
The classes in java.util package handles only objects and hence wrapper classes help in
this case also.
Data structures in the Collection framework such as ArrayList and Vector store only the
objects (reference types) and not the primitive types.
The object is needed to support synchronization in multithreading.
Autoboxing
is used to convert primitive data types into corresponding objects.
Output
10 10
Unboxing
is used to convert the Wrapper class object into corresponding primitive data types
Page 29
https://gits-sln.blogspot.com Durga sir Java Notes
Output
10 10
}
public static int display1(int a,int b)//class method
{
return(a+b);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int d,d1,d2,d3,d4,d5;
//d=display(1,2); //can not call non-static method in this way
d1=display1(1,2);//can be call static method in this way
rnd obj=new rnd();
d2=obj.display(1, 2);
d3=obj.display1(1, 2);
//d4=rnd.display(1, 2);//can not call non-static method in this way
d5=rnd.display1(1, 2);
System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
System.out.println(d5);
Page 30
https://gits-sln.blogspot.com Durga sir Java Notes
// Driver code
public static void main(String args[])
{
// Calling the varargs method with different number
// of parameters
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}
Output:
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0
Page 31
https://gits-sln.blogspot.com Durga sir Java Notes
Note: A method can have variable length parameters with other parameters too, but one should
ensure that there exists only one varargs parameter that should be written last in the parameter list of
the method declaration.
// Java program to demonstrate varargs with normal
// arguments
class Test2
{
// Takes string as a argument followed by varargs
static void fun2(String str, int ...a)
{
System.out.println("String: " + str);
System.out.println("Number of arguments is: "+ a.length);
System.out.println();
}
Page 32
https://gits-sln.blogspot.com Durga sir Java Notes
2) Object is a real world entity such as pen, Class is a group of similar objects.
laptop, mobile, bed, keyboard, mouse, chair
etc.
Page 33
https://gits-sln.blogspot.com Durga sir Java Notes
4) Object is created through new keyword mainly Class is declared using class
e.g. keyword e.g.
Student s1=new Student(); class Student{}
6) Object allocates memory when it is created. Class doesn't allocated memory when
it is created.
7) There are many ways to create object in java There is only one way to define class in
such as new keyword, newInstance() method, java using class keyword.
clone() method, factory method and
deserialization.
2. By method-
In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method. Here, we are displaying the
state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
Page 34
https://gits-sln.blogspot.com Durga sir Java Notes
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
3. By constructor
##########
Page 35
https://gits-sln.blogspot.com Durga sir Java Notes
The main way is 5 way which are 1-by using new operator, 2-by using newInstance() method,
3-by using factory method, 4-by using clone method, 5-by using deserialization.
By using Factory method
Runtime r=Runtime.getRuntime();
DateFormat df=DateFormat.getInstance();
By using deserialization
FileInputStream fis=new FileInputStream(“abc.sec”);
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d=ois.readObject();
Constructors in Java
Every time an object is created using the new() keyword, at least one constructor is called it is
known a Default Constructor if there are no any constructor in a class then only default
constructor automatically called. It constructs the values at the time of object creation.
Rules for creating Java constructor
There are two rules defined for the constructor.
1-Constructor name must be the same as its class name
2-A Constructor must have no explicit return type
3-A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
1-Default constructor (no-arg constructor)-
Class_Name()
{
---------------
}
Default constructor will be automatically called/ invoked at the time of object creation.
Provide the default values to the object like 0, null, etc., depending on the type
2-Parameterized constructor
Class_Name(data_type arg, data_type arg)
{
---------------
}
Page 36
https://gits-sln.blogspot.com Durga sir Java Notes
Constructor vs method
Java Constructor Java Method
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default The method is not provided by the
constructor if you don't have any constructor compiler in any case.
in a class.
The constructor name must be same as the The method name may or may not
class name. be same as the class name.
Page 37
https://gits-sln.blogspot.com Durga sir Java Notes
Output:
111 Karan
111 Karan
II. Copying values without constructor
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
new vs constructor
Studend s=new Student(“Durga”,101);
new=> used to create an object
Student(“Durga”,101)=>to initialize the object that means it is used to initialize
the value of a constructor
First object will be created by using new operator and then initialization will be
performed by constructor.
Page 38
https://gits-sln.blogspot.com Durga sir Java Notes
chi
Not
Page 39
https://gits-sln.blogspot.com Durga sir Java Notes
Constructor Chaining
Suppose there is a class which inherits another class, in this case if you create the object of
child class then first super class (or parent class) constructor will be invoked and then child
class constructor will be invoked.
Y=20
999 Y=20
t1 t2
Note-
Page 40
https://gits-sln.blogspot.com Durga sir Java Notes
We can’t access instance member directly in static area but we can access from instance
area directly.
We can access static member from both instance and static area directly.
class test
{
int x=10;
static int y=20;
public void m()
{
sop(x);
sop(y);
}
public static void m1()
{
sop(x);
sop(y);
}
}
Question- consider the following declaration
1. Int x=10;
2. Static int x=10;
3. Public void m(){sop(x);}
4. Public static void m(){sop(y);}
There can be following possibility occur
I. 1 and 2
II. 1 and 3
III. 1 and 4
IV. 2 and 3
V. 2 and 4
VI. 3 and 4
Page 41
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
1-Inheritance concept is applicable for static method including main() method. Hence while
executing child class if child doesn’t contain main() method then parent class main method will
be executed.
Class P
{
Public static void main(String[] args)
{
Sop(“parent main”);
}
}
Class c extends p
{
}
Save as p.java
Javac p.java
p.class and c.class created
java p
parent main
java c
parent main
2-overriding concept is appear in the static method but it is not overriding but it is method
hiding
Class P
{
Public static void main(String[] args)
{
Sop(“parent main”);
}
}
Class c extends p
{
Public static void main(String[] args)//It is method hiding but not overriding
{
Sop(“child main”);
}
}
Save as p.java
Javac p.java
p.class and c.class created
java p
Page 42
https://gits-sln.blogspot.com Durga sir Java Notes
parent main
java c
child main
3-static method vs instance method
Inside method implementation if we are using at least one instance variable then that method
talk about a particular object hence we should declare as instance method.
Inside method implementation if we are not using any instance variable then this method is no
way related to particular object hence we have to declare such type method as static method
irrespective of whether we are using static variable or not.
class student
{
string name;
int rollno
int marks;
static string cname;
getstudentinfo()
{
return name+” “+marks; //instance method
}
getcollegeinfo()
{
return cname; //static method
}
getaverage(int x, int y)//here we are not using instance nor static variable of class
{
return (x+y)/2; //static method
}
getcompleteinfo()
{
return name+””+rollno+””+marks; //instance method
}
}
4-For static method implementation should be available but abstract method implementation
not available. Hence static abstract combination is illegal.
3. Block
Is used to initialize the static data member.
It is executed before the main method at the time of classloading.
static{
//----------------
}
Can we execute a program without main() method?
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is
not possible to execute a java class without the main method.
Page 43
https://gits-sln.blogspot.com Durga sir Java Notes
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Output:
4. Nested class
Inner class can be static but outer class or top class can’t be static.
Note-If we take parameters and instance variable both difference then we have no need of
using this keywords.
2. this can be used to invoke current class method (implicitly)-this.method();
If you don't use the this keyword, compiler automatically adds this keyword while invoking the
method.
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
Page 44
https://gits-sln.blogspot.com Durga sir Java Notes
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
Output:method is invoked
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello a
10
4. this() Calling parameterized constructor from default constructor:
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
Output:
5
hello a
Page 45
https://gits-sln.blogspot.com Durga sir Java Notes
5. this() used to reuse the constructor from the constructor i.e. used for the
constructor chaining.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor //constructor call must be first in constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
Output:
Page 46
https://gits-sln.blogspot.com Durga sir Java Notes
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
8. this can be used to return the current class instance from the method.
//Java code for using 'this' keyword
//to return the current class instance
class Test
{
int a;
int b;
//Default constructor
Test()
{
a = 10;
b = 20;
}
Page 47
https://gits-sln.blogspot.com Durga sir Java Notes
{
Test object = new Test();
object.get().display();
}
}
Output:
a = 10 b = 20
Inheritance in Java
one object acquires all the properties and behaviors of parent object.
When you inherit from an existing class, you can reuse methods and fields of parent class,
and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship
Aggregation in Java
Aggregation is a special form of association. It is a relationship between two
classes like association, however its a directional association, which means it is
strictly a one way association. It represents a HAS-A relationship.
Example-
Consider two classes Student class and Address class. Every student has an
address but Address doesn’t need to have a Student necessarily. Student Has-A
Address
class Address
Page 48
https://gits-sln.blogspot.com Durga sir Java Notes
{
int streetNum;
String city;
String state;
String country;
Address(int street, String c, String st, String coun)
{
this.streetNum=street;
this.city =c;
this.state = st;
this.country = coun;
}
}
class StudentClass
{
int rollNum;
String studentName;
//Creating HAS-A relationship with Address class
Address studentAddr;
StudentClass(int roll, String name, Address addr){
this.rollNum=roll;
this.studentName=name;
this.studentAddr = addr;
}
public static void main(String args[]){
Address ad = new Address(55, "Agra", "UP", "India");
StudentClass obj = new StudentClass(123, "Chaitanya", ad);
System.out.println(obj.rollNum);
System.out.println(obj.studentName);
System.out.println(obj.studentAddr.streetNum);
System.out.println(obj.studentAddr.city);
System.out.println(obj.studentAddr.state);
System.out.println(obj.studentAddr.country);
}
}
Output:
123
Chaitanya
55
Agra
UP
India
Why we need Aggregation?
To maintain code re-usability. To understand this lets take the same example again.
Suppose there are two other classes College and Staff along with above two
classes Student and Address. In order to maintain Student’s address, College Address and Staff’s
address we don’t need to use the same code again and again. We just have to use the
reference of Address class while defining each of these classes like:
Page 49
https://gits-sln.blogspot.com Durga sir Java Notes
class Address
{
int streetNum;
String city;
String state;
String country;
Address(int street, String c, String st, String coun)
{
this.streetNum=street;
this.city =c;
this.state = st;
this.country = coun;
}
}
class StudentClass
{
int rollNum;
String studentName;
//Creating HAS-A relationship with Address class
Address studentAddr;
StudentClass(int roll, String name, Address addr){
this.rollNum=roll;
this.studentName=name;
this.studentAddr = addr;
}
...
}
class College
{
String collegeName;
//Creating HAS-A relationship with Address class
Address collegeAddr;
College(String name, Address addr){
this.collegeName = name;
this.collegeAddr = addr;
}
...
}
class Staff
{
String employeeName;
//Creating HAS-A relationship with Address class
Address employeeAddr;
Staff(String name, Address addr){
this.employeeName = name;
this.employeeAddr = addr;
}
...
}
As you can see that we didn’t write the Address code in any of the three classes
Note-Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the
objects involved; otherwise, aggregation is the best choice.
Page 50
https://gits-sln.blogspot.com Durga sir Java Notes
Note-In java, Method Overloading is not possible by changing the return type of the method
only.
Operator overloading possible?
The + operator is overloaded in Java. However, Java does not support user-defined
operator overloading. The + operator can be used to as an arithmetic addition operator to add
numbers. It can also be used to concatenate strings.
Output-string[]
Promotion of one data type to another data type follow the following rules
If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.
class OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}
Page 51
https://gits-sln.blogspot.com Durga sir Java Notes
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Example-the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could
provide 8%, 7%, and 9% rate of interest.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
Page 52
https://gits-sln.blogspot.com Durga sir Java Notes
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed); //invoke parent class instance
variable
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
Page 53
https://gits-sln.blogspot.com Durga sir Java Notes
super.message();
}
}
Page 54
https://gits-sln.blogspot.com Durga sir Java Notes
Note-We can also have multiple IIBs in a single class. If compiler finds multiple IIBs, then they all are executed
from top to bottom i.e. the IIB which is written at top will be executed first.
Page 55
https://gits-sln.blogspot.com Durga sir Java Notes
1. The instance initializer block is created when instance of the class is created.
2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after
super() constructor call).
3. The instance initializer block comes in the order in which they appear.
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B2 extends A{
B2(){
super();
System.out.println("child class constructor invoked");
}
1. Final variable-
1. Used to create a constant variable i.e. we can’t change the value of final variable.
Page 56
https://gits-sln.blogspot.com Durga sir Java Notes
2. Uninitialized final variable can be initialize inside a)-at the time of declaration, b)-
instance-initializer block, c)-inside constructor.
3. A blank final static variable can be initialized inside static block.
System.out.println(a);
System.out.println(b);
System.out.println(PI);
System.out.println(area);
}
}
Output-
2
3
3.14
2.5
Class Student
{
String name;
Int roll_no; //instance variable value varies from object to object.
Static String cname; //static instance variable only one copy is created and share every objects
of
//the class.
Page 57
https://gits-sln.blogspot.com Durga sir Java Notes
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
Polymorphism in Java
Polymorphism means many forms. In Java polymorphism is mainly divided into
two types:
Compile time Polymorphism-method overloading== If you overload a static method
That’s means it is follow static binding.
Page 58
https://gits-sln.blogspot.com Durga sir Java Notes
A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For Example:
interface I{}
class A{}
class B extends A implements I{}
Example-
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
Output:
Output:
90
Page 59
https://gits-sln.blogspot.com Durga sir Java Notes
class Dog{
private void eat(){System.out.println("dog is eating...");}
Java instanceof
This operator is used only for object reference variables. The operator checks whether the object
is of a particular type (class type or interface type). This operator return true or false value.
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
Page 60
https://gits-sln.blogspot.com Durga sir Java Notes
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract methods (without body) and non-abstract methods (with body).
o We can declare zero no of abstract method in any abstract class. Example- HttpServelet
class, Adapter class
o Every Abstract method implementation should take place in child class.
o It cannot be instantiated (i.e. we can’t create an object of any abstract class).
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
Page 61
https://gits-sln.blogspot.com Durga sir Java Notes
Abstract provide an Illegal combination with final, native, static, private, strictfp,
synchronized. Example- abstract final void run();-compile time error-illegal
combination of modifiers.
Abstract class can contain a final method but in final class can not contain an abstract
method.
Private abstract combination in not a legal combination for method because private
method is not available to the child class. Example-
Private abstract void run();
Interface in Java
The interface in Java is a mechanism to achieve abstraction.
methods in an interface are declared without body.
Variable declare under interface compulsory initialize at the time of declaration.
We can create full method definition body by using default or static keyword in interface.
Represents the IS-A relationship.
It cannot be instantiated just like the abstract class (means cannot be used to create
objects) but we can make reference of it .
It don’t support constructor (as it cannot be used to create objects).
By interface, we can support the functionality of multiple inheritance.
A class can implement more than one interface.
An interface can extends another interface or interfaces (more than one interface)
Note-Interface fields by default= public, static and final,
Interface methods by default= public, abstract, default, static.
interface printable{
void print();
}
Page 62
https://gits-sln.blogspot.com Durga sir Java Notes
Output:
Hello
A class can extends another class and/ can implement one and more than one interface.
interface intfB
{
void m2();
}
@Override
public void m2()
Page 63
https://gits-sln.blogspot.com Durga sir Java Notes
{
System.out.println("Welcome: inside the method m2");
}
}
class GFG
{
public static void main (String[] args)
{
sample ob1 = new sample();
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Output:
ROI: 9.15
Some Special cases-
If an interface contain a variable then the way of changing the value of these
variable in implemented class
interface Left{
int a=10;
}
public class Rnd3 implements Left {
public static void main(String args[]){
//a=20;//wrong way because it is by default final
int a=30;
//System.out.println(a);//this case show an error
}
Page 64
https://gits-sln.blogspot.com Durga sir Java Notes
If two interface contain contain same variable then accessing concept of these
value in implementing class
interface Left{
int a=10;
}
interface Right{
int a=20;
}
//Creating a Test class which calls abstract and non-abstract methods
public class Rnd3 implements Left,Right{
public static void main(String args[]){
//System.out.println(a);//this case show an error
System.out.println(Left.a);//because it is by default static final so we can access by class
System.out.println(Right.a);
}
}
#if two interface contain the same method with same signature and same
return type then when we implements both interface in a class then only one
method need to provide own definition .
interface left
{
public void m();
}
interface right
{
public void m();
}
class test implements left,right
{
public void m()
{
-------
}
public static void main(String args[]){
}
If method same but signature is differ of given method in interface then both
method declaration is compulsory in class implementation.
interface left
{
public void m();
}
interface right
{
public void m(int a);
}
class test implements left,right
{
public void m()
{
Page 65
https://gits-sln.blogspot.com Durga sir Java Notes
-------
}
public void m(int a)//method overloading
{
-------
}
public static void main(String args[]){
}
If two interface contain method name and signature are same but they differ in
return type then both method declaration is in class implementation is not
possible.(it is an exception or loop hole case of that java class can implements
number of interface)
interface left
{
public void m();
}
interface right
{
public int m();
}
class test implements left,right
{
public void m()
{
-------
}
public int m()//provide a compile time error
{
-------
}
public static void main(String args[]){
}
Multiple inheritance in Java by interface
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
Page 66
https://gits-sln.blogspot.com Durga sir Java Notes
obj.show();
}
}
Output:Hello
Welcome
@Override
public void geekInstitute()
{
System.out.println("JIIT");
}
Page 67
https://gits-sln.blogspot.com Durga sir Java Notes
Note-An interface which has no member is known as a marker or tagged interface, for example,
Serializable, Cloneable, Remote, etc. They are used to provide some essential information to the JVM so
that JVM may perform some useful operation.
1) Abstract class can have Interface can have only abstract methods. Since Java
abstract and non- 8, it can have default and static methods also.
abstract methods.
3) Abstract class can have Interface has only static and final variables.
final, non-final, static and
non-static variables.
6) An abstract class can An interface can extend another Java interface only.
extend another Java class and
implement multiple Java
Page 68
https://gits-sln.blogspot.com Durga sir Java Notes
interfaces.
8) A Java abstract class can Members of a Java interface are public by default.
have class members like
private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
Page 69
https://gits-sln.blogspot.com Durga sir Java Notes
a.c();
a.d();
}}
Output:
I am a
I am b
I am c
I am d
Marker interface(or ability interface or tag interface)
If an interface doesn’t contain any method and by implementing the interface if our object will get some
extra ability is known as marker interface.Example- Serializable, Cloneable.
RandomAccess,SingleThreadModel.
By implementing serializable interface our object can be save to the file and can travel across the
network.
By implementing cloneabale interface are in a position to produce exactly duplicate clone object.
Internally JVM is a responsible to provide required ability to reduce the complexity of programmer
and to make java languages as simple.
It is also possible to create on maker interface but customization of JVM must be required.
Adapter classes
It is a simple java class that implements an interface with only empty implementation.
interface X{
void m1();
void m2();
.
.
void m1000();
}
abstract class Adapter implements X
{
public void m1() {}
public void m2() {}
.
.
public void m1000() {}
}
If implements an interface for each and every interface compulsory we should provide implementation
whether it is required or not required.
class Test implements X
{
public void m2()
{
------10 line
}
public void m1() {}
public void m2() {}
public void m4() {}
.
.
public void m1000() {}
}
The problem in this approach is it increases length of the code and reduces readability.
Page 70
https://gits-sln.blogspot.com Durga sir Java Notes
We can solve the problem by using adapter classes instead of implementing interface if we
extends adapter class we have to provide implementation only for required method and we are
not responsible to provide implementation for each and every method of interface.so that length
of the code will be reduced.
class Test extends Adapter
{
X
m3()
{
------
Adapter
}
}
class Sample extends Adapter Test
{
m7()
{
------ Servlet
}
}
We can develop a servlet in the following the three ways-
MyServlet GenericServlet
1. By implementing servlet (interface)
2. By extending Generic Servlet (Adapter class)
3. By extending HttpServlet (Adapter class) HttpServlet
If we implements servlet interface for each and every method of that interface
We should provide implementation it increases length of the code and reduces readability.
Instead of implementing servlet interface directly if we extends generic servlet we have to
provide implementation only for service method and all remaining method we have not required
to provide implementation hence more or less generic servlet access adapter class for servlet
interface.
Note- marker interface and adapter class simplify complexity of programming and these a bet
utility of the programmer and programmer life will become simple.
Page 71
https://gits-sln.blogspot.com Durga sir Java Notes
If we don’t know anything about implementation just we have requirement specification then we
should go for interface. Example- Servlet
If we talking about implementation but not completely (partial implementation) then we should
go for abstract class. Example- GenericServelt, HttpServet
If we are talking about implementation completely and ready to provide of this then we should
go for concrete class. Example- MyownServlet.
Question: we cannot create object for abstract class but abstract class can contain constructor.
What is need?
Answer: Yes.
Without having constructor in parent class (more code
redundancy)
Page 72
https://gits-sln.blogspot.com Durga sir Java Notes
Page 73
https://gits-sln.blogspot.com Durga sir Java Notes
Abstract class can contain instance variable which are required for child object.
To perform initialization of those instance variable constructor is required to abstract
class. But every variable present inside interface is always public static final whether we
are declaring or not and there is no chance of existing instance variable inside interface.
Hence constructor concept not required for interface.
Note- Whenever we are creating child class object parent object want be created just
parent class constructor will be executed for the child object purpose only.
Question:-Inside interface every method is always abstract and we can take only
abstract method in abstract class also then what is difference between interface and
abstract class that is it is possible to replace interface to abstract class.
Answer:- We can replace interface with abstract class but it is not a good programming
practice and this is something like recruitment IAS officer for swapping activity.
Note-If everything is abstract then it is highly recommended to go for an interface
because object creation in interface taken a minimum time. So for this reason working of
interface in fast as compared with abstract.
Question: we cannot create object for abstract class directly but indirectly we can create. Is it
valid?
Answer: we cannot create object directly or indirectly of abstract class.
Question: whenever we are creating child class object automatically parent class object will be
created. Is it valid?-
Answer: not valid , only parent class constructor will be executed automatically.
Page 74
https://gits-sln.blogspot.com Durga sir Java Notes
Question: Anywhere we cannot create object for abstract class and interface. But abstract class
can contain constructor but interface doesn’t. Why?
Answer: because interface contain any variable is by default public static final so there is no
chance of existing instance variable so for this reason constructor concept not required for
interface.
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Type of package-
1. Build in package (such as java, lang, awt, javax, swing, net, io, util, sql etc.)
2. User defined package
Encapsulation in Java
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. It
is also known as combination of data-hiding + abstraction. To achieve this, you must:
File: Account.java
//A Account class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
Page 75
https://gits-sln.blogspot.com Durga sir Java Notes
class Account {
//private data members
private long acc_no;
private String name,email;
private float amount;
//public getter and setter methods
public long getAcc_no() {
return acc_no;
}
public void setAcc_no(long acc_no) {
this.acc_no = acc_no;
}
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 float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
File: TestAccount.java
//A Java class to test the encapsulated class Account.
public class TestEncapsulation {
public static void main(String[] args) {
//creating instance of Account class
Account acc=new Account();
//setting values through setter methods
acc.setAcc_no(7560504000L);
acc.setName("Sonoo Jaiswal");
acc.setEmail("[email protected]");
acc.setAmount(500000f);
//getting values through getter methods
System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" "+acc.getAmount());
}
Page 76
https://gits-sln.blogspot.com Durga sir Java Notes
Page 77
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(i*2);
//String lenght
System.out.println(s.length());
System.out.println("Hi".length());
//String concatination
System.out.println(s+", "+s1);
System.out.println(s+" my quite");
System.out.println(s.concat(" "+s1));
System.out.println("3+3="+3+3);
System.out.println(3+3);
//character formation
char c1=s.charAt(2);
System.out.println(c1);
char c2[]=s.toCharArray();
for(int j=0;j<s.length();j++)
{
System.out.print(c2[j]);
}
System.out.println("\n");
System.out.println(s.substring(0,3));
//searching and replacing string
System.out.println(s.indexOf("draw"));//searching index of first occurance
System.out.println(s.lastIndexOf("draw"));//searching index of last occurance
System.out.println(s1.replace('h','n'));
System.out.println(s1.replace("how","cow"));
System.out.println(s1.replace(s1.substring(0,3),"cow"));
System.out.println(s1.isEmpty());
//converting any number value into string
int num=1234;
String nts=Integer.toString(num);
System.out.println(nts);
System.out.println(nts+1);
}
Output-
3+3=33
We
21
false
Page 78
https://gits-sln.blogspot.com Durga sir Java Notes
1234
12341
2. StringBuffer (mutable, synchronized-thread safe)
StringBuffer is mutable means one can change the value of the object .
The object created through StringBuffer is stored in the heap .
StringBuffer has the same methods as the StringBuilder , but each method in StringBuffer is
synchronized that is StringBuffer is thread safe .
Due to this it does not allow two threads to simultaneously access the same method . Each
method can be accessed by one thread at a time .
But being thread safe has disadvantages too as the performance of the StringBuffer hits due
to thread safe property . Thus StringBuilder is faster than the StringBuffer when calling the
same methods of each class.
StringBuffer value can be changed.
String Buffer can be converted to the string by using toString() method.
StringBuffer demo1 = new StringBuffer(“Hello”) ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer(“Bye”);
// Above statement is right as it modifies the value which is allowed in the StringBuffer
3) StringBuffer is thread-safe and StringBuilder is not. You can not share Instances of
StringBuilder class between multiple threads. If such synchronization is required then it is better
to use StringBuffer class.
4) StringBuffer is old class, its there in JDK from very first release, while StringBuilder is
relatively newer class, introduced much later in release of JDK 1.5
Page 79
https://gits-sln.blogspot.com Durga sir Java Notes
By using JOptionPane
String radiusStr;
double radius, area;
// Read input String from dialog box
radiusStr = JOptionPane.showInputDialog("Enter the radius of the circle");
radius = Double.parseDouble(radiusStr); // Convert String to double
area = radius*radius*Math.PI;
System.out.println("The area is " + area);
Page 80
https://gits-sln.blogspot.com Durga sir Java Notes
1. protected Object clone() - Used to create and return a copy of this object.
2. boolean equals(Object obj) - Used to indicate whether some other object is
"equal to" this one.
3. protected void finalize() - garbage collector calls this method on an object when
it determines that there are no more references to the object.
4. Class<?> getClass() - Used to get the runtime class of this Object.
5. int hashCode() - Used to get a hash code value for the object.
6. void notify() - Used to wake up a single thread that is waiting on this object's
monitor.
7. void notifyAll() - Used to wake up all threads that are waiting on this object's
monitor.
8. String toString() - Used to get a string representation of the object.
9. void wait() - marks the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
10. void wait(long timeout) - marks the current thread to wait until either
another thread invokes the notify() method or the notifyAll() method for this
object, or a specified amount of time has elapsed.
11. void wait(long timeout, int nanos) - marks the current thread to wait until
another thread invokes the notify() method or the notifyAll() method for this
object, or some other thread interrupts the current thread, or a certain amount of
real time has elapsed.
return (num1+num2);
Page 81
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(t.sum());
}
}
Output:
We can declare a class as abstract strictfp combination because its combination is legal at class
level but illegal at method level.
public abstract strictfp class Test //provide a legal syntex
{
Synchronized keyword
It is only applicable for method and block.
If the multiple thread simultaneously operate on the same object then what will happen-
Data inconsistence problem this is called raised condition. So we remove this problem
by using synchronized keyword. If a method is block by using synchronized then only one
thread is allowed to execute of that object at a time so that data inconsistency problem is
resolve.
But main disadvantage of this keyword is it increases waiting time of thread and create
performance problem. Hence if there is no specific requirement avoid it use.
Synchronized method should contain implementation of data.
Abstract synchronized is an illegal in use.
Native keyword
It is applicable only for method.
The native method is implemented in non-java(mostly C or C++)
The main objective of native keyword are-
I. To improve performance of the system (if any particular area is critical in java then
we can use native term to improve for this particular area to improve performance.
)
II. To achieve Machine or memory level communication
III. To use already existing code in non-java like c or c++
Pseudo code to use native keyword in java
I. Load native libraries.
II. Declare (not a definition) a native method-The method which are already
implemented in c or c++ we are not responsible to implementation. example- public
native void m();
Note- abstract native combination in illegal. Example- public abstract native void
m();
Native strictfp combination is illegal. Example- public strictfp native void m();
III. Invoke a native method.
Disadvantage- it breaks the platform independent nature of java.
Page 82
https://gits-sln.blogspot.com Durga sir Java Notes
Transicnt keyword
Applicable only for variable.
It is used in serialization context.
At the time of serialization if u don’t want to save the value of a particular variable to meet
security constraint then we should declare the variable as transicnt.
At the time of serialization JVM ignore the value of transicnt variable and save default
value to the file. Hence transicnt means not to serialize.
Usename-Durga serialization
Password-12$12#
transicnt Usename-Durga
Password-null
a1
asc.scr
Usename-Durga deserialization
Password-null
a2
Volatile keyword
If the value of a variable keep on changing by multiple threads then there may be a
chance of data inconsistency problem. We can solve these problem using volatile
keywords.
If a variable is declare as volatile then for every thread JVM will create a separate local
copy.
Every modification performed by threads will takes place in local copy so there is no effect
on remaining threads.
Advantage- to overcome data inconsistency problem.
Disadvantage- creating and maintaining a separate copy of every threads increases the
complexity of programming and create performance problem. hence if there is no specific
requirement never recommended to use volatile keyword and it is almost depreciated
keywords.
final volatile variable combination is illegal.
Oops concept
Data Hiding
Outside person cannot access our internal data directly or our internal data should not go
out directly this oops features nothing but data hiding. After validation or Authentication
outside person can access our internal data.
Advantage- we can achieved security.
Page 83
https://gits-sln.blogspot.com Durga sir Java Notes
Example-1 After providing proper user name and password we can able to access our
gmail inbox information.
Example-2 Even though we are valid customer of bank we can able to access our
account information and we can access others account information.
By declaring data member (variable) as private (highly recommended modifiers) we can
achieved data hiding.
public class Account
{
private double balance;
:
:
public double getBalance()
{
//validation
return balance;
}
}
Abstraction
Hiding internal implementation and just highlight the set of services what we are offering
is concept of abstraction.
Example- Bank ATM GUI screen bank people are highlighting the set of services what
they are offering without highlighting the internal implementation.
Advantage:
1. We can achieved security because we are not highlighting our internal
implementation.
2. Without affecting outside person we can able to perform any type of changes our
internal system and hence enhancement easy.
3. In improve maintainability of the application.
4. It improve easiness to use our system.
Note-By using interface and abstract classes we can implement abstraction.
Encapsulation
The process of binding data and corresponding method into a single unit is nothing but
Encapsulation.
Example- Every java class in java follow Encapsulation rules.
Class Student
{
Data member;
Corresponding method;
}
Page 84
https://gits-sln.blogspot.com Durga sir Java Notes
If any component follow data hiding and abstraction such type of component is said to
be encapsulated component.
Encapsulation= Data hiding + Abstraction
Page 85
https://gits-sln.blogspot.com Durga sir Java Notes
class B extends A
{
private int b=20; //not tightly encapsulated
}
class C extends B
{
private int c=30; //not tightly encapsulated
}
Note-If the parent class in not tightly encapsulated then there is no chance of any child
class is tightly encapsulated.
class D
{
private int d=40; ////tightly encapsulated
}
Note- Data hiding, Abstraction, Encapsulation, tightly encapsulated class are main
feature is security.
Is-A relation ship
1. It is also known as Inheritance.
2. The main advantage of Is-A relation is code reusability.
3. By using extends keyword we can implements Is-A relationship.
class P
{
public void m1()
{
System.out.println("parent");
}
}
class C extends P
{
public void m2()
{
System.out.println("child");
}
}
public class Rnd3
{
public static void main(String[] args)
{
P p=new P();
p.m1();
//p.m2();//by using parent reference we cannot call child method
C c=new C();
c.m1();// by using child reference we can call all child and parent method
c.m2();
P p1=new C();
p1.m1();
//p1.m2();//because p1 is reference of parent class so it can access only own class method
//C c1=new P(); because we can not convert from parent to child
}
}
Page 86
https://gits-sln.blogspot.com Durga sir Java Notes
Conclusion
1. Whatever method parent has by default available to the child and hence a child
reference we can call both parent and child class method.
2. Whatever method child has by default not available to the parent and hence on the
parent reference we cannot call child specific method.
3. Parent reference can be used to hold child object but using that reference we
cannot call child specific method but we can call the method present in parent
class.
4. Parent reference can be used to hold child object but child reference cannot be
used to parent object.
Note-
The most common method which are applicable for any type of child, we have to
define in parent class.
The specific method which are applicable for a particular child we have to define in
child class.
Total Java API is based on Inheritance concept and Object class is a root class of any
class by default. So in Object class contain 11 method to available for any type of class
(because every class in java is child class of Object is directly or indirectly)by default.
A java class cannot extends more then one class at a time. Hence java don’t support
multiple inheritance in class.
Page 87
https://gits-sln.blogspot.com Durga sir Java Notes
If a java class not extends any class then by default it extends to Object class
class A// here class A extends internally by default Object class
{
--
}
But if a java class extends to any class then it is not extends to Object class any way.
class B extends A //here class B extends only class A not extends Object class
{
Cyclic inheritance
Cyclic inheritance in java is not allowed. Example-
1. Class A extends A{ }
2. Class A extends B{ }
Class B extends A{ }
Page 88
https://gits-sln.blogspot.com Durga sir Java Notes
Has-A relationship
1. It is also known as composition or aggregation.
2. There is no specific keyword to implement Has-A relation but most of the time we
are depending on new keyword.
3. The main advantage of Has-A relationship is reusability of code.
class Engine
{
//Engine specific functionality
}
class Car
{
Engine e=new Engine();
}
Method Signature
It consist of method name followed by argument types. Example-
Page 89
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
Test t=new Test();
t.m(10);// int argu
t.m(10.5f);//float argu
t.m(‘a’);//int argu means argument promotion
//because if argu method is not found then argument value promoted to upper value
t.m(10l);//float argu means argument promotion
while resolving overloaded method if exact match of method is not available then we will
not get compile time error immediately because first it will promote argument to the
next level and check whether method is available or not if method available then it will
Page 90
https://gits-sln.blogspot.com Durga sir Java Notes
be consider and if match method is not available is not available then compile promote
argument once again to the next level. This process will be continue until all possible
promotion. Still if the match method not available then we will get compile time error.
}
}
Test t=new Test();
t.m(10,15.5f);//int-float argu
t.m(15.5f,10);//float-int argu
t.m(10,15);//CE because no promotion rule applicable for second argument
t.m(10.5,15.5);// CE because no any demotion rule applicable for first argument
}
}
Test t=new Test();
t.m();//varargs method because it is used to pass no value or number of value
t.m(10,20); //varargs method
t.m(10);//both method taken value but priority wise general method show only
}
}
Test t=new Test();
t.m(new Object());// object version
t.m(“durga”);//string version
t.m(null);//string version because null value hold both object and string classes but
precedence given by compile to string (child level).
Since Object is a parent class of String class.
While resolving overloaded method compile will always give the precedence for child
type argument then compare with parent type argument.
Case-5: Automatic precedence fail in method overloading if argument is same
level
Class Test
{
Public void m(String s)
{
Sop(“String version”);
}
Public void m(StringBuffer sb)
{
Sop(“StringBuffer version”);
}
Page 92
https://gits-sln.blogspot.com Durga sir Java Notes
}
Test t=new Test();
t.m(“durga”);//string version
t.m(new StringBuffer(“pp”))// StringBuffer version
t.m(null);// CE because null value hold both String and StringBuffer level but String and
StringBuffer is belong on same level so confuse and givern error.
Case-6:
Class Animal
{
}
Class Monkey extends Animal
{
}
Class Test
{
Public void m(Animal a)
{
Sop(“Animal version”);
}
Public void m(Monkey m)
{
}
Public static void main(String[] args)
{
Test t=new Test();
Animal a=new Animal();
t.m(a);// Animal version
Monkey m=new Monkey();
t.m(m);// Monkey version
Animal a1=new monkey();
t.m(a1);// Animal version
}
}
Overriding
Whatever method has by default available to the child though inheritance if child class
not satisfied with the parent class implementation then child is allowed to redefined that
method based on its requirement this process is called overriding.
The parent class method which is overridden is called overridden method and the child
class method which is overriding is called overriding method.
Class P
{
Public void property()
Page 93
https://gits-sln.blogspot.com Durga sir Java Notes
{
Sop(“cash+land+gold”);
}
Public void marry()//overridden method
{
Sop(“mariya”);
}
}
Class C extends P
{
Public void marry()//overriding method
{
Sop(“trisha|richa|mona”);
}
}
Class Test
{
Public static void main(String[] args)
{
P p=new P();
p.marry();//parent method
C c=new C();
c.marry();//child method
P p1=new C();
P1.marry();// child method
//first reference p1 taken parent marry() at compile time but in run time JVM check
object is created for child class so JVM execute child class method at run time.
}
}
In overriding method resolution is always based on runtime object.
Overriding is also known as run time polymorphism or dynamic
polymorphism or late binding.
Page 94
https://gits-sln.blogspot.com Durga sir Java Notes
}
class c extends p
{
public string m()
{
return null;
}
}
3.
Parent Object Number String Double
class
method
return
type
Child Object|String|StringBuffer Number|Integer Object int
class
method
return
type
Valid Valid Invalid Invalid
4. Co-variant return type concept applicable only for object type but not for primitive
types.
5. Parent class private method is not available to the child and hence overriding
concept not applicable for private method. That means if a private method with
same name present in both parent and child class then this is valid case but it is
not a method overriding.
6. If a parent class method if final then we cannot override this method.
7. Parent class abstract method we should override in child class to provide
implementation.
Abstract class P
{
Public abstract void m();
}
Class C extends P
{
Public abstract void m()
{
……….
}
}
8. We can override non abstract method as abstract
class p
{
public void m()
Page 95
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
abstract class c extends p
{
public abstract void m();
}
The main advantage of this approach is we can stop the availability of parent
method implementation to the next level child classes.
9.
10. While overriding we cannot reduce the scope of access modifiers but we can
increase the scope.
class P
{
public void m()
{
}
}
class C extends P
{
void m()// can not override
{
}
}
Page 96
https://gits-sln.blogspot.com Durga sir Java Notes
method
Runtime exception and error are unchecked and excepted these term all are checked
term.
If child class method throws checked any exception compulsory parent class method
should throws same checked exception are its parent otherwise we will get compile time
error but there are not restriction for unchecked exception.
Page 97
https://gits-sln.blogspot.com Durga sir Java Notes
import java.io.*;
class Parent
{
public void m() throws IOException
{
System.out.println("parent");
}
}
class Child extends Parent
{
public void m() throws EOFException,InterruptedException
{
System.out.println("child");
}
}
This code will given error but we can remove the error by using these code in this way
import java.io.*;
Page 98
https://gits-sln.blogspot.com Durga sir Java Notes
class Parent
{
public void m() throws IOException, InterruptedException
{
System.out.println("parent");
}
}
class Child extends Parent
{
public void m() throws EOFException,InterruptedException
{
System.out.println("child");
}
}
Overriding with static method
1) We cannot override a static method as non-static otherwise we will get compile
time error
If parent class method static and child class method non-static
class Parent
{
public static void m()//static method//overridden method
{
System.out.println("parent");
}
}
class Child extends Parent
{
public void m() //non static method//overriding method
{
System.out.println("child");
}
}
Given compile time error
If parent and child both class method static then we want get any compile time error it
seems overriding concept applicable for static method but it is not overriding but it is
method hiding.
class Parent
{
public static void m()//static method//overridden method
Page 99
https://gits-sln.blogspot.com Durga sir Java Notes
{
System.out.println("parent");
}
}
class Child extends Parent
{
public static void m() //static method//overriding method
{
System.out.println("child");
}
}
public class Test
{
Note-
In overriding old copy replace with new copy and old copy gone
In hiding old copy just hide with new copy if you want I can show both copy
Page 100
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
Page 101
https://gits-sln.blogspot.com Durga sir Java Notes
Page 102
https://gits-sln.blogspot.com Durga sir Java Notes
Polymorphism
Page 103
https://gits-sln.blogspot.com Durga sir Java Notes
d)
Page 104
https://gits-sln.blogspot.com Durga sir Java Notes
Page 105
https://gits-sln.blogspot.com Durga sir Java Notes
Coupling
The degree of dependence between the components is called coupling.
If dependence is more than it is consider as tightly coupling and if dependency is less
than it is consider as loosely coupling.
Example-
class A
{
static int i=B.j;
}
class B
{
static int j=C.k;
}
class C
{
static int k=D.m;
}
Page 106
https://gits-sln.blogspot.com Durga sir Java Notes
class D
{
public static in m()
{
return 10;
}
}
The above component are said to be tightly coupled with each other because
dependency between the components is more.
Tightly coupling is not a good programming practices because it has several serious
disadvantages.
a) Without affecting remaining component we cannot modifies any component and
hence enhancement become difficult.
b) It separates reusability.
c) It reduces maintainability of the application.
Hence we have to maintain dependence between the components as less as possible that
is loosely coupling is a good programming practices.
Cohesion
For every component a clear well defined functionality is defined then the component is
said to be follow high cohesion.
High cohesion is always a good programming practices because it has several advantage
a) Without affecting remaining component we can modified any component hence
enhancement will become essay.
b) It promote reusability of the code (wherever validation is required we can reuse
the same validate servlet without rewriting)
c) It improve maintainability of the application.
Page 107
https://gits-sln.blogspot.com Durga sir Java Notes
Note- loosely coupling and high cohesion are good programming practices.
Object casting
We can use parent reference to hold child object
Object o=new String(“Durga”);
We can use interface reference to hold implemented class object.
Runnable r=new Thread();
A a=(C)d;
Where a,d reference variable name
A,C class| interface name
Compile time checking 1
The type of ‘d’ and ‘C’ must have some relation either child to parent or parent to child
or same type otherwise we will get compile time error : inconvertible type
Example-1 valid expression
Object o=new String(“Durga”);
StringBuffer sb=(StringBuffer)o;
Example-2 invalid expression (CE: inconvertible type)
String s=new String(“Durga”);
StringBuffer sb=(StringBuffer)s;
Compile time checking 2
‘C’ must be either same or derived type of ‘A’ otherwise we will get compile time error
saying: incompatible type
Example-1 valid expression
Object o=new String(“Durga”);
StringBuffer sb=(StringBuffer)o;
Example-2 invalid expression (CE: incompatible type)
Object o=new String(“Durga”);
StringBuffer sb=(String)o;
Runtime checking 3
Runtime object type of ‘d’ must be either same or derived type of ‘C’ otherwise we will
get runtime exception saying : class cast exception
Example-1 invalid expression (RE: class cast exception)
Object o=new String(“Durga”);
Page 108
https://gits-sln.blogspot.com Durga sir Java Notes
StringBuffer sb=(StringBuffer)o;
Example-2 valid expression
Object o=new String(“Durga”);
Object o1=(String)o;
###
By using type casting we are not creating any new object for the existing object we are
providing another type reference variable that means we are performing type casting but
not object casting.
Example-1
String s=new String(“Durga”);
Object o=(Object)s;
Instead of above two line we can use a single line
Object o=new String(“Durga”);
Example-2
Integer I=new Integer(10);
Number n= (Number)I;
Object o=(Object)n;
Sop(I==n); //true
Sop(n==o); //true
Page 109
https://gits-sln.blogspot.com Durga sir Java Notes
The above two line can be combine into single line as Number n= new Integer(10);
We can also combine above three line into single line as Object o= new Integer(10);
Note-
If A is root parent, B is child of A and C is child of B.
A <---- B <----- C
C c=new C();
If we using casting as (B)C means B b=new C();
If we are using casting as (A)((B)C) means A a= new C();
Example
If P is parent class C is child class
m1() is P class method and m2() is C class method
C c=new C();
c.m1(); //valid
c.m2(); //valid
((p)c).m1(); //valid
The full expression of above line is
P p=new C();
p.m1();
((p)c).m2(); //invalid
The full expression of above line is
P p=new C();
p.m2();//because we cannot call child class method by using parent class reference
variable
Example
Page 110
https://gits-sln.blogspot.com Durga sir Java Notes
Given method is overridden so method is call by object creation but not by reference
variable. In the above example all the term create C class object.
Example
The above example show method hiding not a method overriding.so method is call by
using reference variable. In the above three line first show class C reference variable,
second show class B reference variable, third show class A reference variable.
Page 111
https://gits-sln.blogspot.com Durga sir Java Notes
Example
Variable call is based on reference type but not based on runtime object.
Page 112
https://gits-sln.blogspot.com Durga sir Java Notes
11. goto pass-13 and redirect to goto pass-14 and execute 20 (j=20)
12. goto pass-15 and execute main method block
13. the step-11 and step-12 of pass-13 to pass-15 follow rule no-3
Direct read- within a static block if we are trying to read any variable is called direct
read.
Example-
static
{
Sop(i);
}
Indirect read- when I am calling a method and method description we are trying to
read any variable is called indirect read.
Example-
static
{
m();
}
public static void m()
{
Sop(j);
}
Read indirectly write only- if a variable is just identified but original value is not
assigned
If a variable is just identified by the JVM and the original value not yet assign then
the variable is said to be in read indirectly and write only state (RIWO)
If a variable is in read indirectly write only state then we cannot perform direct
read but we can perform indirect read.
Page 113
https://gits-sln.blogspot.com Durga sir Java Notes
If we are trying to read directly then we will get compile time error saying illegal
forward reference.
Static block
It is executed at the time of class loading hence at the time of class loading if we want to
perform any activities we have to define that inside static block.
Example-1
At the time of java class loading the corresponding native library should be loaded hence
we have to define this activity inside static block.
Class test
{
Systic.loadLibrrary(“native library path”);
}
Example-2
After loading every database driver class we have to register driver class with driver
manger but inside data base driver class there is a static block to perform this activities
and we are not responsible to register explicitly.
Class DbDriver
{
Static
{
Register this driver with driver manager
}
}
Page 114
https://gits-sln.blogspot.com Durga sir Java Notes
Note- within a class we can declare any number of static block all these static block will
be executed from top to bottom.
Question-Without writing main method is it possible to print some statement in the
console.
Answer-Yes by using static block.
class Test
{
static
{
Sop(“static block”);
System.exit(0);// without this line showing output with runtime exception
for main method
}
}
Question- without writing main method and static block is it possible to print some
statement to the console.
Answer- yes, there are multiple way to do
Class Test
{
Static int x=m();
Public static int m()
{
Sop(“hello”);
System.exit(0);
Return 10;
}
}
Page 115
https://gits-sln.blogspot.com Durga sir Java Notes
Note- from 1.7 version on wards main method is mandatory to start a program
execution hence form 1.7 version on wards without main method it is impossible to print
some statement to the console.
class Base
{
P-1 static int i=10; p-12
P-2 static
{
m1(); p-13
System.out.println("base class static block"); p-15
}
P-3 public static void main(String[] args)
{
m1();
System.out.println("base class main");
}
P-4 public static void m1() p-14
{
System.out.println(j);
}
P-5 static int j=20; p-16
}
class Derived extends Base
{
P-6 static int x=100; p-17
P-7 static
{
m2(); p-18
System.out.println("Derived class first static block"); p-20
}
P-8 public static void main(String[] args)
{
m2(); p-23
System.out.println("Derived class main"); p-25
}
P-9 public static void m2()
{
System.out.println(y); p-19 p-24
}
P-10 static
{
System.out.println("Derived class second static block"); p-21
}
Page 116
https://gits-sln.blogspot.com Durga sir Java Notes
i=0[RIWO]
j=0[RIWO]
x=0[RIWO]
y=0[RIWO]
the above four line are form pass-1 to pass-11 follow rule no-1
p-12 i=0[R&W]
p-13 redirect to p-14 given 0 (j=0)
p-15 given Base class static block
p-16 j=20[R&W]
p-17 x=100[R&W]
p-18 redirect to p-19 given 0 (y=0)
p-20 Derived class first static block
p-21 Derived class second static block
p-22 y=200[R&W]
rule no-2 taken place from p-12 to p-22
Page 117
https://gits-sln.blogspot.com Durga sir Java Notes
Note-whenever we are loading child class automatically parent class will be loaded but
whenever we are loading parent class child class would not loaded because parent class
member is by default available to the child but child class member not available to the
parent class.
Output-
If we creating object of class then
I=0[RIWO]
J=0[RIWO]
The above two term come from p-1 to p-8
p-9 given i=10[R&W]
p-10 redirect to p-11 and given 0(j=0)
p-12 given first instance block
Page 118
https://gits-sln.blogspot.com Durga sir Java Notes
0
first instance block
second instance block
constructor
main
if we are not creating any object then output will be come on the basis of static control
flow terminology because it is a base term of execution of program.
main
Note-
static control flow is one time activity which will be perform at the time of class loading .
but instance control flow is not one time activity and it will be perform for every object
creation.
Object creation is the most costly operation if there is no specific requirement then it is
not recommended to create object.
Page 119
https://gits-sln.blogspot.com Durga sir Java Notes
package com.java.test;
class parent
{
int i=10;//instance variable
{//instance block
m1();
System.out.println("parent first instance block");
}
parent()
{
System.out.println("parent constructor");
}
public static void main(String[] args)
{
parent r=new parent ();
System.out.println("parent main");
}
public void m1()
{
System.out.println(j);
}
Page 120
https://gits-sln.blogspot.com Durga sir Java Notes
parent main
Page 121
https://gits-sln.blogspot.com Durga sir Java Notes
Page 122
https://gits-sln.blogspot.com Durga sir Java Notes
{
System.out.println("second instance block");
}
}
Output-
first static block
second static block
first instance block
second instance block
constructor
main
first instance block
second instance block
constructor
Output-
2
3
1
package com.java.test;
class Rnd3
{
private static String m1(String msg)
Page 123
https://gits-sln.blogspot.com Durga sir Java Notes
{
System.out.println(msg);
return msg;
}
static String m=m1("1");
{
m=m1("2");
}
static
{
m=m1("3");
}
public static void main(String[] args)
{
Object o=new Rnd3();
}
}
Output-
1
3
2
Note-
From static area we cannot access instance member directly because while executing
static area JVM may not identified instance member
class Rnd3
{
int x=10;
public static void main(String[] args)
{CE
System.out.println(x);//CE
}
}
But is we are creating an object then
class Rnd3
{
int x=10;
public static void main(String[] args)
{
Constructor
Once we create an object compulsory we should perform initialization then only object is in a
position to respond properly.
Page 124
https://gits-sln.blogspot.com Durga sir Java Notes
Whenever we are creating an object some piece of code will be executed to perform
initialization of the object this piece of the code nothing but constructor. Hence the main
purpose is to perform initialization of an object.
class student
{
string name;
int rollnumber;
student(string name, int rollnumber)
{
this.name=name;
this.rollnumber=rollnumber;
}
public static void main(string[] args)
{
student s1=new student(“ram”,101);
student s2=new student(“shyam”,102);
}
}
Note-
The main purpose of constructor is to perform initialization of an object but not to create
an object.
}
Rnd3(int i)
{
Page 125
https://gits-sln.blogspot.com Durga sir Java Notes
Rnd3(double d)
{
}
public static void main(String[] args)
{
Rnd3 t1=new Rnd3();
Rnd3 t2=new Rnd3(10);
Rnd3 t3=new Rnd3(10.5);
System.out.println(count);
}
}
Output-3
}
}
public class Test public class Test
{ {
void Test() public Test()
{ {
super();
} }
} void Test()
{
super();
}
}
class Test class Test
{ {
Test() Test()
{ {
super();
} }
} }
class Test class Test
{ {
Test(int i) Test()
{ {
super(); super();
} }
} }
Note-The first line inside every constructor should be either super() or this() and if we
are not writing anything then compiler will always plays super().
Case-1 we can take super() or this() only in first line of constructor if we are trying to
take
Anywhere else we will get compile time error.
Page 127
https://gits-sln.blogspot.com Durga sir Java Notes
Case-2 Within constructor we can take either super() or this() but not both
simultaneously.
Case-3 We can use super() or this() only inside constructor if we are trying to use
outside of constructor we will get compile time error. That is we can call a constructor
directly from another constructor.
super(),this() super,this
These are constructor call to call These are keyword to use refer
super class and current class super class and current class
constructor. instance member.
We can use only in constructor as first We can use anywhere except static
line area.
We can use only once in constructor We can use any number of time.
Overloaded constructor
Within a class we can declare multiple constructor and all these constructor having same
name but different type of argument hence all these constructor consider as overloaded
constructor. Hence overloading concept applicable for constructor.
class Rnd3
{
Rnd3()
{
this(10);
System.out.println("no arg");
}
Rnd3(int i)
{
this(10.5);
System.out.println("int arg");
}
Rnd3(double d)
{
System.out.println("double arg");
}
public static void main(String[] args)
{
Rnd3 t1=new Rnd3();
System.out.println("-----------------");
Rnd3 t2=new Rnd3(10);
System.out.println("-----------------");
Rnd3 t3=new Rnd3(10.5);
System.out.println("-----------------");
Rnd3 t4=new Rnd3(10L);
System.out.println("-----------------");
//System.out.println("-----------------");
}
}
Page 128
https://gits-sln.blogspot.com Durga sir Java Notes
Output-
double arg
int arg
no arg
-----------------
double arg
int arg
-----------------
double arg
-----------------
double arg
-----------------
Note-
For constructor inheritance and the overriding concept are not applicable but overloading
concept is applicable.
Every class in java including abstract class can contain constructor but interface cannot
contain constructor.
Case-1
It is a recursive method calling program
class Rnd3
{
public static void m1()
{
System.out.println("in m1()");
m2();
}
public static void m2()
{
System.out.println("in m2()");
m1();
}
Page 129
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
Case-3 if parent class constructor through in checked exception then compulsory child
class constructor should through the same checked exception or its parent otherwise the
code won’t compile.
Page 130
https://gits-sln.blogspot.com Durga sir Java Notes
Singleton classes
For any java class if we are allowed to create only one object such type of class is called
singleton class.
Example-
Page 131
https://gits-sln.blogspot.com Durga sir Java Notes
Page 132
https://gits-sln.blogspot.com Durga sir Java Notes
At any point of time for test class we can create only one object hence test class is
singleton class.
If a class is not final but we are not allowed to create to child classes how it is
possible?
By declaring every constructor as private we can restrict child class creation.
class p
{
private p()
{
}
}
For the above class it is impossible to create child class.
File I/O
1. File
2. FileWriter
3. FilwReader
4. BufferWriter
5. BufferReader
6. PrintWriter
Page 133
https://gits-sln.blogspot.com Durga sir Java Notes
File
Page 134
https://gits-sln.blogspot.com Durga sir Java Notes
Page 135
https://gits-sln.blogspot.com Durga sir Java Notes
Page 136
https://gits-sln.blogspot.com Durga sir Java Notes
FileWriter
Page 137
https://gits-sln.blogspot.com Durga sir Java Notes
FileReader
Page 138
https://gits-sln.blogspot.com Durga sir Java Notes
Page 139
https://gits-sln.blogspot.com Durga sir Java Notes
BufferWriter
Page 140
https://gits-sln.blogspot.com Durga sir Java Notes
Page 141
https://gits-sln.blogspot.com Durga sir Java Notes
Page 142
https://gits-sln.blogspot.com Durga sir Java Notes
BufferReader
PrintWriter
Page 143
https://gits-sln.blogspot.com Durga sir Java Notes
Page 144
https://gits-sln.blogspot.com Durga sir Java Notes
Page 145
https://gits-sln.blogspot.com Durga sir Java Notes
Page 146
https://gits-sln.blogspot.com Durga sir Java Notes
Page 147
https://gits-sln.blogspot.com Durga sir Java Notes
Generic
The main objective of generic is to provide type safety and resolve type casting
problems.
hence string array can contain only string type of object due to this we can give the
guarantee for the type of element present inside array hence array are safe to use with
respect to type that is array are type safe.
But collection are not safe that is we cannot give the guarantee for the type of elements
present inside collection.
Example
Page 148
https://gits-sln.blogspot.com Durga sir Java Notes
If our programme requirement is to hold only string type of objects and if we chose
array list , by mistake if we are trying to add any other type of object we wont get any
compile time error but the programmer may fail at run time.
ArrayList l=new ArrayList();
l.add(“durga”);
l.add(“Ravi”);
l.add(new Integer(10));
now I am trying to retrieve
String name1=(String)l.get(0);
String name2=(String)l.get(1);
String name1=(String)l.get(2); RE: classCastException
Hence we cannot give the guarantee for the type of element present inside collection due
to this collection are not save to use with respect to type that is collection are not type
safe.
Case-2 TypeCasting
In the case of array at the time of retrival it is not required to perform typecasting
because there is a guarantee for the type of element present inside array.
String s=new String[1000];
S[0]=”Durga”;
.
.
.
String name1=s[0];// type casting not required
But in the case of collection at the time of retrival compulsory we should perform
typecasting because there is not guarantee for the type of element present inside
collection.
ArrayList l=new ArrayList();
l.add(“Druga”);
Page 149
https://gits-sln.blogspot.com Durga sir Java Notes
Page 150
https://gits-sln.blogspot.com Durga sir Java Notes
Conclusion-2
For the type parameter we can provide any class or interface name but not primitive if
we are trying to provide primitive then we will get compile time error.
Generic Class
Untill 1.4 version a non generic version of array list class is declare as follows
class ArrayList
{
add(Object o);
Object get(int index);
Page 151
https://gits-sln.blogspot.com Durga sir Java Notes
}
The argument two add method is object and hence we can add any type of object to the
array list due to this we are missing type safety.
The return type of get method is object at the time of retrieval we have to perform
typecasting.
But in 1..5 version a generic version of array list class is declare as follows
class ArrayList<T>//where T is type parameter
{
Add(T t);
T get(int index);
}
Based on our run time requirement T will be replaced with our provided type.
For Example
To hold only string type of object a generic version of array list of object can be created
as follows
ArrayList<String> l=new ArrayList<String>;
For this requirement compiler consider version of array list class is as follows
class ArrayList<String>
{
add(String s);
String get(int index);
}
The argument two add method is string type hence we can add only string type object
by mistake if are trying to add any other type we will get compile time error
l.add(“Durga”);
l.add(new Integer(10));// CE:cannot find error
Hence through generic we are getting type safety.
The return type of get method is string and hence at the time of retrieval we are not
required to perform typecasting.
String name1=l.get(0); //type casting is not required
In generic we are associating a type parameter to the class such type of parameter rise
classes are nothing but generic classes or templet classes.
Based on our requirement we can define our own generic classes also
Class Account<T>
{
Page 152
https://gits-sln.blogspot.com Durga sir Java Notes
}
Account<Gold> a1=new Account<Gold>();
Account<Platinum> a2=new Account<Platinum>();
How to create own generic class by using example-
Bounded types
We can bound the type parameter for a particular range by using extends keyword such
types are called bounded types.
class Test<T>
{
}
As the type parameters we can pass any type and there are no restrictions and hence it
is unbounded type.
Test<Integer> t1=new Test<Integer>();
Test<String> t1=new Test<String>();
Syntax for bounded type
class Test<T extends X>
{
Page 153
https://gits-sln.blogspot.com Durga sir Java Notes
If X is a class then as the type parameter we can pass either X type or its child classes.
If X is an interface as the type parameter we can pass either X type or its
implementation classes.
Example-
class Test<T extends Number>
{
}
Test<Integer> t1=new Test<Integer>();
Test<String> t1=new Test<String>();//CE: type parameter string is not within its
bound
Example-
class Test<T extends Runnable>
{
}
Test<Runnable> t1=new Test<Runnable>();
Test<Thread> t2=new Test<Thread>();
Test<Integer> t1=new Test<Integer>();//CE:type parameter Integer is not within its bound
We can define bounded types even in combination also
class Test<T extends Number & Runnable>
{
}
As type of parameters we can take anything which should be child class Number and
should implements Runnable interface.
Note-
class Test<T extends Runnable & Comparable>
class Test<T extends Number & Runnable & Comparable>
class Test<T extends Runnable & Number>// CE:
because we have to take class first followed by interface next(Number is a class and
Runnable is an interface) so correct notation will be
class Test<T extends Number & Runnable>
class Test<T extends Number & Thread> // CE:
Because we cannot extends more than one class simultaneously
Conclusion
1-we can define bounded types only by using extends keyword and we cannot use
implements and super keyword but we can replace implement keyword purpose with
extends keyword.
Page 154
https://gits-sln.blogspot.com Durga sir Java Notes
2-as the type parameters T we can take any valid java identifiers but it is convention to
use T.
3-based on our requirement we can declare any no of type parameters and all these type
parameters should be separated with “,”.
Page 155
https://gits-sln.blogspot.com Durga sir Java Notes
When we are using generic method by using ? we can call this method by using any type
of argument that means no need to create different type of m1 method.
m1(AL<String> l)
{
Page 156
https://gits-sln.blogspot.com Durga sir Java Notes
m1(<AL<?> l)
{
}
a) We can call this method by passing array list of any type.
b) But within the method we cannot add anything except null(because it is valid value
for any type)
Page 157
https://gits-sln.blogspot.com Durga sir Java Notes
{
}
X can be either class or interface
If X is a class then we can call this method by passing array list of either X type or its
child classes.
If X is an interface then we can call this method by passing array list of either X type or
its implementation classes.
But within the method we cannot add anything to the list except null because we donnot
the type of X exactly.
This type of method also best suitable for read-only operation.
m(AL<? super X> l)
{
}
X can be either class or interface
If X is a class then we can call this method by passing array list of either X type or its
super classes.
If X is an interface then we can call this method by passing array list of either X type or
super class of implementation class of X.
But with in the method we can add X type of object and null to the list.
Page 158
https://gits-sln.blogspot.com Durga sir Java Notes
Generic Method
We can declare type parameter either yet class level or yet method level
On class level- we can declare type parameter just after class name.
On method level- we can declare type parameters just before method return type.
We can defined bounded yet method level also
Page 159
https://gits-sln.blogspot.com Durga sir Java Notes
The main purpose of generic is to provide type safety and to resolve type casting
problems.
Type safety and the type casting both are applicable at compile time hence generic
concept also applicable only at compile time but run time.
At the time of compilation as last step generic syntax will be removed and hence for the
JVM generic syntax won’t be available.
Hence the following declaration are equal
Page 160
https://gits-sln.blogspot.com Durga sir Java Notes
Introduction
Why java.lang package is favorites package for all programmer?
Page 161
https://gits-sln.blogspot.com Durga sir Java Notes
1) For writing any java program the most commonly required classes and interface
are grouped into a separate package which is nothing but java.lang package.
2) Without java.lang package we cannot write any java program. So java.lang
package is default available in the program.
In a simple java program how many time depending to use java.lang package
Object Class
Page 162
https://gits-sln.blogspot.com Durga sir Java Notes
Object class contain all most common method which are applicable for all java classes.
Page 163
https://gits-sln.blogspot.com Durga sir Java Notes
toString()
Page 164
https://gits-sln.blogspot.com Durga sir Java Notes
Page 165
https://gits-sln.blogspot.com Durga sir Java Notes
hashCode() method
Page 166
https://gits-sln.blogspot.com Durga sir Java Notes
public class Ob {
toString() vs hashCode()
if we are giving the chance to object class toString() method it will internally calls
hashCode() method.
If we are overriding toString() method then our toString() method may not call
hashcode() method.
Page 167
https://gits-sln.blogspot.com Durga sir Java Notes
equals() method
it is used to check the equality of two object. Example- obj1.equals(obj2)
if our class does’t contain equals() method then object class equals() method will be
executed.
Page 168
https://gits-sln.blogspot.com Durga sir Java Notes
In the above example object class equal() method got executed which is met for
reference comparison (address comparison) that is if two reference point into the same
object then only that equal method return true.
Based on our requirement we can override equal() method for content comparison.
While overriding equal method for content comprision we have to take care about the
following-
1-what is the meaning of equality that is whether we have to check only name or only
roll number or both
2- if we are passing different type of object our equal method should not rise
classcastexception we have tohandel classcast exception to return false.
3- if we are passing null argument then our equal method should not rise null pointer
exception that is we have to handel null pointer exception to return false.
The following is the proper way of overriding is equal method for student class content
comparison.
public boolean equals(Object obj) //s1.equals(s2) s1 means this and s2 means obj
{
try
{
String name1=this.name;
int rollnum1=this.rollnum;
Student s=(Student)obj;//RE:CCE
String name2=s.name;//RE:NPE
Page 169
https://gits-sln.blogspot.com Durga sir Java Notes
}
catch(ClassCastException e) { return false;}
catch(NullPointerException e) { return false;}
}
Page 170
https://gits-sln.blogspot.com Durga sir Java Notes
To make above equals method more abscent we have to write the following code at the
beginning inside equals method
According to this if both reference pointing to the same object then without performing
any comparison equals method return true directly.
Page 171
https://gits-sln.blogspot.com Durga sir Java Notes
In string a equals method present and used to compare content even though object are
different if content is same then equals method return true.
But in string buffer an equals method not present so equals method of object class call
and is used to compare reference of object.
getClass() method
By using this class class object we can access class level property like fully qualified
name of class, method information, constructor information etc.
import java.lang.reflect.Method;
Connection con=DriverManager.getConnection(...);
sop(con.getClass().getName());
Note-
Page 172
https://gits-sln.blogspot.com Durga sir Java Notes
1) After loading every .class file jvm will create an object of the type java.lang.class
in the heap area.Programmer can use this class object to get class level
information.
2) We can use getClass() very frequently in reflection api.
finalized() method
Just before destroying an object garbage collector call finalized method to perform
cleanup activity.
Once finalized method complete automatically garbage collector destroy that object.
String class
Case-1
Immutable- means not any type changeable behavior
One we create a String object we cannot perform any changes in the existing object if
we are trying to perform any change with those changes a new object will be created
this non-changeable behavior is nothing but immutability of string.
String s=new String("durga");
s.concat("soft");
System.out.println(s);//durga
Once we create StringBuffer object we can perform any change in the existing object
this changabe behavior is nothing but mutability of StringBuffer object.
StringBuffer sb=new StringBuffer("durga");
sb.append("soft");
System.out.println(sb);//durgasoft
Case-2
String s1=new String("durga");
String s2=new String("durga");
System.out.println(s1==s2);//falseused for reference comparison
System.out.println(s1.equals(s2));//true it is an string class equals() method
Page 173
https://gits-sln.blogspot.com Durga sir Java Notes
//reference comparison
Case-3
String s=new String("durga");
Here two object is created one is in heap area and other in the String constant pool
(scp) area.
s point to heap area object only.
Scp area object is used for future purpose only.
String s="durga";
Here only one object is created in scp area.
s is point to that object.
Note-
1. Object creation in scp is optional. First jvm will check if any object is already
present present in scp with required content if object already present then existing
object will be reused. If object not already available then only a new object will be
created. But this rule is only applicable for scp only not for heap.
2. Garbage collector is not allowed to access the scp area hence even though object
doesn’t contain reference variable it is not eligible for gc if it is present in scp area.
3. All scp object will be destroyed automatically at the time of jvm shutdown.
Example-
Page 174
https://gits-sln.blogspot.com Durga sir Java Notes
String s2=s1.concat("solution");
s1=s1.concat("soft");
System.out.println(s1);
System.out.println(s2);
Note-
1) For every string constant one object will be placed in scp area.
2) Because of some run time operation if an object is required to create that object
will be placed only in the heap area but not in scp area.
Page 175
https://gits-sln.blogspot.com Durga sir Java Notes
Sop(s.substring(2,6));//cdef
7. public int length()
return the length of the string(number of character of string including space)
String s=”Durga soft”;
Sop(s);//5
Note:-
s.length applicable for array whereas s.length() is applicable for string.
8. public String replace(char oldchar, char newchar)
replace of a particular old character in string to new character
String s=”ababa”;
Sop(s.replace(a,b));//bbbbb
Special Note-
Because of run time operation if there is change in the content then if those changes a
new object will be created in the heap.
If there is no change in the content then existing object will be reused and new object
won’t be created.
Whether object is present in heap or scp the rule is same.
Page 177
https://gits-sln.blogspot.com Durga sir Java Notes
Page 178
https://gits-sln.blogspot.com Durga sir Java Notes
If there is no changes in the content then existing object will be reused this behavior is
nothing but immutability.
Once we create test object we cannot perform any change in the existing object if we are
trying to perform any change and if there is a change in the content then if those
changes a new object will be created.
If there is no change in the content then existing object will be reused.
final vs immutability
final applicable for variables but not for object
Whereas immutability applicable for object but not for variable
by declaring a reference variable as final we won’t get any immutability nature even
though reference variable is final we can perform any type of change of the
corresponding object but we cannot perform reassignment for that variable.
Page 179
https://gits-sln.blogspot.com Durga sir Java Notes
StringBuffer
If the content is fixed and won’t change frequently then it is recommended to go for
string.
If the content is not fixed and keep on changing then it is not recommended to used
string because for every change a new object will be created which effect performance of
the system to handle this requirement we should go for StringBuffer. The main
advantage of StringBuffer over String is all required changes will be performed in the
existing object only.
StringBuffer Constructor
Page 180
https://gits-sln.blogspot.com Durga sir Java Notes
Page 181
https://gits-sln.blogspot.com Durga sir Java Notes
StringBuilder
Every method present in StringBuffer is synchronized and hence only one thread is
allowed to operate on StringBuffer object at a time which make create performance
problem to handel this requirement sun people introduced StirngBuilder concept in
1.5 version.
StringBuilder is excetly same as StringBuffer except following difference
StringBuffer StringBuilder
Evey method synchronized Non-synchronized
Object allowed to only one thread at a Object allowed to multiple thread at a
time which menas object is threadsafe time which menas object is not
threadsafe
Increasing waiting time of thread and decreases waiting time of thread and
decrease performance increase performance
Came in 1.0 version Came in 1.5 version
Page 182
https://gits-sln.blogspot.com Durga sir Java Notes
Method chaining
For most of the method in String, StringBuffer, StringBuilder are return type are same
type hence after applying a method and the result we can call another method which
forms method chaining.
sb.m1().m2().m3()…….
sb.append("durga").append("software").append("solutions").insert(5,"srikant").delete(13,21).app
end("AR Nagar");
System.out.println(sb);// durgasrikantsolutionsAR Nagar
Wrapper classes
The main objective of wrapper classes are
To wrap primitive into object form so that we can handle primitive also just like object.
To define several utility method which are required for the primitives.
Creation of wrapper object-
Almost all wrapper classes contain two constructor one can take corresponding as
argument and other can take String as argument.
Example-1
Integer i=new Integer(10);
Integer i=new Integer(“10”);
Example-2
Double d=new Double(10.5);
Double d=new Double(“10.5”);
If String argument not representing a number we will get run time exception saying
numberformatexception.
Integer i=new Integer(“ten”);//RE:numberformatexception
Page 183
https://gits-sln.blogspot.com Durga sir Java Notes
Form-2
Page 184
https://gits-sln.blogspot.com Durga sir Java Notes
Every Integral Wrapper class Byte, Short, Integer, Long) contains the following valueOf()
method to create a Wrapper object for the given String with specified radix. The range of
the radix is 2 to 36.
public static Wrapper valueOf(String s, int radix)
Integer I = Integer.valueOf("1111", 2);
System.out.println(I);
Integer I1 = Integer.valueOf("1111", 4);
System.out.println(I1);
Output:
15
85
Form-3
Every Wrapper class including Character class contains the following method to create a
Wrapper object for the given primitive type.
Syntax:
public static Wrapper valueOf(primitive p);
Integer I = Integer.valueOf(10);
Double D = Double.valueOf(10.5);
Character C = Character.valueOf('a');
System.out.println(I);
System.out.println(D);
System.out.println(C);
Output:
10
10.5
a
2.xxxValue() method:
We can use xxxValue() methods to get the primitive for the given Wrapper Object. Every
number type Wrapper class( Byte, Short, Integer, Long, Float, Double) contains the
following 6 methods to get primitive for the given Wrapper object:
Page 185
https://gits-sln.blogspot.com Durga sir Java Notes
Output:
-126
130
130
130
130.0
130.0
Output:
10
10.5
true
parseXxx(String s, int radix) : Every Integral type Wrapper class (Byte, Short,
Integer, Long) contains the following parseXxx() method to convert specified radix
String to primitive.
Syntax:
Page 186
https://gits-sln.blogspot.com Durga sir Java Notes
Output:
8
85
4. toString() method:We can use toString() method to convert Wrapper object or
primitive to String. There are few forms of toString() method:
public String toString() : Every wrapper class contains the following toString()
method to convert Wrapper Object to String type.
Syntax:
Output:
10
toString(primitive p) : Every Wrapper class including Character class contains
the following static toString() method to convert primitive to String.
Syntax:
public static String toString(primitive p);
String s = Integer.toString(10);
System.out.println(s);
String s1 = Character.toString('a');
System.out.println(s1);
Output:
10
a
toString(primitive p, int radix) : Integer and Long classes contains the following
toString() method to convert primitve to specified radix String.
Syntax:
Output:
Page 187
https://gits-sln.blogspot.com Durga sir Java Notes
1111
222120121300
Page 188
https://gits-sln.blogspot.com Durga sir Java Notes
Conclusion-
1. The wrapper classes which are not child class of number are Boolean , character.
2. The wrapper classes which are not direct child classes are byte, shot, interger,
float, double.
3. String , StringBuffer, StringBuilder and all wrapper classes are final classes.
4. In addition to string all wrapper classes object also immutable.
5. Some people are sometime void classes is also consider as wrapper class.
Void class
public final class Void
extends Object
Java.lang.Void class is a placeholder which holds a reference to a class object if it represents void keyword. It is a
uninstantiable placeholder. Well, uninstantiable means that this class have a private constructor and no other
constructor that we can access from outside.
It does’t contain any method and it’s contain only one variable void.type
In gereral we can use void class in reflection to check whether the menthod return type
is void or not.
if(getMethod(“m1()”).getReturnType()==Void.Type)
{
Autoboxing
Automatic conversion of primitive to wrapper object by compiler is known as autoboxing.
Integer i=10;
Compiler convert int to Integer automatically by autoboxing.
After compilation compiler will automatically placed this line into this line
Integer i=Integer.valueOf(10);
Page 189
https://gits-sln.blogspot.com Durga sir Java Notes
Autounboxing
Automatic conversion of wrapper object to primitive by compiler is called autounboxing.
Integer I=new Integer(10);
int i=I;
compiler covert Integer to int automatically. After compilation the above line will become
int i=I.intValue();
that means internally autounboxing concept in implemented by using xxxValue()
method.
Page 190
https://gits-sln.blogspot.com Durga sir Java Notes
Note- just because of autoboxing and autounboxing we can use primitive and wrapper
object inter-changeable.
On null reference if we are trying to perform autounboxing then we will get runtime
exception saying null pointer exception.
Page 191
https://gits-sln.blogspot.com Durga sir Java Notes
Note – All wrapper class object are immutable that is once we create a wrapper class
object we cannot perform any changes in that object if we are trying to perform any
changes then those changes a new object will be created.
Conclusion-
Internally to provide support for autoboxing a buffer of wrapper object will be crated at
the time of wrapper class loading.
By autoboxing if an object is required to create first jvm will checq whether this object
already present in the buffer or not if it is already present in the buffer then existing
buffer object will be used if it is not already available in the buffer then jvm will create
new object.
Page 192
https://gits-sln.blogspot.com Durga sir Java Notes
Excepted this range in all remaining cases a new object will be created.
Page 193
https://gits-sln.blogspot.com Durga sir Java Notes
Autoboxing vs widening
public class Ob {
public static void m1(Integer I)
{
System.out.println("Autoboxing");
}
public static void m1(long l)//overloaded method
{
System.out.println("widening");
}
Output- widening
Widening dominates varg-arg method.
Case-3
Page 194
https://gits-sln.blogspot.com Durga sir Java Notes
{
System.out.println("autoboxing");
}
Output-autoboxing
Autoboxing dominates var-arg method.
In general var-arg method get least priority.
Note- If no any other method is not found or matched then var-arg method execute. It
is exactly same as default case of switch method.
While resolving overloaded method compiler will always give the precedence in the
following order
1-widening
2-autoboxing
3-var-arg method
Case-4
Page 195
https://gits-sln.blogspot.com Durga sir Java Notes
Object o=10;
Number n=10;
Which of the following assignment are legal
int i=10; //valid
Integer I=10; //validautoboxing
int i=10L; //invalid
Long l=10L: //validautoboxing
Long l=10; //invalid
long l=10; //valid-widening
Object o=10; //validautoboxing followed by widening
double d=10; //valid widening
Double D=10; //invalid
Number N=10; //validautoboxing followed by
widening
2) If two object are not equal by == operator then we cannot conclude anything about
.equals() method it may return true or false that is
If r1==r2 is false then r1.equals(r2) may return true or false we cannot accept exactly.
Page 196
https://gits-sln.blogspot.com Durga sir Java Notes
3) If two object are equal by .equals() method then we cannot conclude anything about
== operator it may return true or false.that is
If r1.equals(r2) is true then we cannot conclude anything about r1==r2 it may return
true or false
4) If two object are not equal by .equals() method then these object are always not
equal by == operator that is
If r1.equals(r2) if false then r1==r2 always false
Page 197
https://gits-sln.blogspot.com Durga sir Java Notes
Page 198
https://gits-sln.blogspot.com Durga sir Java Notes
In String class .equals() method is overridden for content comparison and hence
hashCode() method is also overridden to generate hashCode based on content.
In StringBuffer class .equals() method is not overridden for content comparison and
hence hashCode() method is also not overridden.
Consider the following person class find which of the following hashCode method suitable
for
Page 199
https://gits-sln.blogspot.com Durga sir Java Notes
Clone() method
The process of creating exact duplicate object is called cloning.
The main purpose of cloning is to maintain backup copy and to preserve states of an
object.
We can perform cloning by using clone() method of object class.
protected native clone() throws ClonenotSupportedException
Page 200
https://gits-sln.blogspot.com Durga sir Java Notes
int i=10;
int j=20;
Output-
10 20
111 222
We can perform cloning only for clone able object. An object is said to clone able if and
only if the corresponding class implements clone able interface.
The clone able interface present in java.lang package and it does’t contain any method it
is marker interface.
If we are trying to perform cloning non clone-able object then we will get runtime
Exception saying ClonenotSupportedExcetion.
Page 201
https://gits-sln.blogspot.com Durga sir Java Notes
Shallow cloning
I. The process of creating bitwise copy of an object is called shallow cloning.
II. If the main object contain primitive variables then exactly duplicate copy will be
created in the cloned object.
III. If the main object contain any reference variable then corresponding object don’t
be created just duplicate reference will be created pointing to old contained object.
IV. Object class clone method meant for shallow cloning.
Example-
class Cat
{
int j;
Cat(int j)
{
this.j=j;
}
}
class Dog implements Cloneable
{
Cat c;
int i;
Dog(Cat c,int i)
{
this.c=c;
this.i=i;
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
public class ShallowClone {
Page 202
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(d1.i+" "+d1.c.j);
}
In shallow cloning by using cloned object reference if we perform any change to the
content object then those changes will be reflected to the main object.
To overcome this problem we should go for deep cloning.
Deep cloning
I. The process of creating exactly duplicate independent copy including content
object is called deep cloning.
II. In deep cloning if the main object contain any primitive variable then in the cloned
object duplicate copy will be created.
III. If the main object contain any reference variable then the corresponding contain
object also will be created in the cloned copy.
IV. By default object class clone method meant for shallow cloning but we can
implement deep cloning explicitly by overriding clone method in our class.
Example-
class Cat
{
int j;
Cat(int j)
{
this.j=j;
}
}
class Dog implements Cloneable
{
Cat c;
int i;
Dog(Cat c,int i)
{
this.c=c;
this.i=i;
Page 203
https://gits-sln.blogspot.com Durga sir Java Notes
}
public Object clone() throws CloneNotSupportedException
{
Cat c1=new Cat(c.j);
Dog d2=new Dog(c1,i);
return d2;
}
}
public class DeepClone {
System.out.println(d1.i+" "+d1.c.j);
System.out.println(d2.i+" "+d2.c.j);
}
By using cloned object reference if we perform any change to the content object then
those changes won’t be re?flected to the main object.
Which cloning is best?
If object contain only primitive variable than shallow cloning is the best choice.
If object contain reference variable then deep cloning is the best choice.
Page 204
https://gits-sln.blogspot.com Durga sir Java Notes
Page 205
https://gits-sln.blogspot.com Durga sir Java Notes
If the corresponding scp object is not available then intern() method itself will create
the corresponding scp object.
Page 206
https://gits-sln.blogspot.com Durga sir Java Notes
Page 207
https://gits-sln.blogspot.com Durga sir Java Notes
Page 208
https://gits-sln.blogspot.com Durga sir Java Notes
Ans.8- String is the most common use object and hence sun people provided special
memory management for string object.
But StringBuffer is not commonly used object and hence special memoey management is
not required for StringBuffer.
Ans.9- because of SCP.
In the case of String because of SCP a single object can be referenced by multiple
references.
By using one reference if we are allowed the change the content in the existing object
then remaining reference will be affected to overcome this problem sun people
implemented String object as mutable. According to this once we create string object we
cannot perform any change of existing object if we are trying to perform any changes
with those changes a new object will be created.
Page 209
https://gits-sln.blogspot.com Durga sir Java Notes
But in string buffer there is no concept like SCP. Hence for every requirement a separate
object will be created. By using one reference if we trying to change the content then
there is no effect of remaining reference hence immobility concept not required for string
buffer.
Ans.10-
In addition to string object all wrapper class object is also immutable.
Ans.11-
Yes
Inner class
Some time we can declare a class inside another class such type of classes is called inner
classes.
Inner classes concept in introduced in 1.1 version to fixed GUI bug as the part of event
handling but because of powerful feature and benefit feature slowly programmer started
regular coding also.
Without existing one type of object if there is no chance of existing another type of
object then we should go for inner classes.
Example.1-
University consist of several department without existing university there is no chance of
existing department hence we how to declare class inside university class.
class University
{
class Department
{
}
}
Example.2-
class Car
{
class Engine
Page 210
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
Example.3- Map is a group of key value pairs and each key value pairs is called an Entry.
Without existing Map object there is no chance of Entry object. Hence interface entry is
defined inside Map interface.
Key Value
101 Ravi
102 Sohan
interface Map
{
interface Entry
{
}
}
Note- without existing an outer class object there is no chance of existing inner class
object.
The relation between outer class and inner class is not IS-A relation and it is HAS-A
(composition or aggregation) relationship.
Based on position or declaration and behavior all inner classes are divided into four
types-
1. Normal or regular inner classes
2. Method local inner classes
3. Anonymous inner classes
4. Static nested classes
Page 211
https://gits-sln.blogspot.com Durga sir Java Notes
Inside inner class we cannot declare any static member hence we cannot declare main
method and we cannot run inner class directly from command prompt. So inner classes
cannot have any static declaration.
Page 212
https://gits-sln.blogspot.com Durga sir Java Notes
Page 213
https://gits-sln.blogspot.com Durga sir Java Notes
class Inner
{
public void m1()
{
System.out.println("inner class method");
}
}
}
public class Test
{
public static void main(String[] args) {
// TODO Auto-generated method stub
Outer o=new Outer();
Outer.Inner i=o.new Inner();
}
From normal or regular inner class we can access both static or non-static member and
outer class directly.
public class Outer {
int x=10;
static int y=20;
class Inner
{
public void m1()
{
System.out.println(x);
System.out.println(y);
}
}
Page 214
https://gits-sln.blogspot.com Durga sir Java Notes
Within the inner class this always refer current inner class object if we want to refere
current outer class object we have to use outer_class_name.this
public class Outer {
int x=10;
class Inner
{
int x=100;
public void m1()
{
int x=1000;
System.out.println(x); //1000
System.out.println(Inner.this.x); //100
System.out.println(this.x); //100
System.out.println(Outer.this.x); //10
}
}
}
public class Outer
{
public static void main(String[] args) {
A a=new A();
A.B b=a.new B();
Page 215
https://gits-sln.blogspot.com Durga sir Java Notes
Page 216
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(y);
}
}
Inner i=new Inner();
i.m2();
}
public static void main(String[] args)
{
Outer o=new Outer();
o.m1();
}
}
From method local inner class we cannot access local variable of the method in which we
declare inner class.
If the local variable as final then we can access
public class Outer
Page 217
https://gits-sln.blogspot.com Durga sir Java Notes
{
public void m1()
{
int x=10;//we can use final or without final same result execute
class Inner
{
public void m2()
{
System.out.println(x);
}
}
Inner i=new Inner();
i.m2();
}
public static void main(String[] args)
{
Outer o=new Outer();
o.m1();
}
}
Example-
Consider the output of the following
public class Outer
{
int i=10;
static int j=20;
public void m1()
{
int k=30;
int m=40;
class Inner
{
public void m2()
{
System.out.println(i+" "+j+" "+k+" "+m);
}
}
Inner i=new Inner();
i.m2();
}
public static void main(String[] args)
{
Outer o=new Outer();
o.m1();
}
}
10 20 30 40
If we declared m1() as static then I cannot access in m2()
public class Outer
{
int i=10;
static int j=20;
public static void m1()
{
int k=30;
int m=40;
Page 218
https://gits-sln.blogspot.com Durga sir Java Notes
class Inner
{
public void m2()
{
System.out.println(i+" "+j+" "+k+" "+m);
}
}
Inner i=new Inner();
i.m2();
}
public static void main(String[] args)
{
Outer o=new Outer();
o.m1();
}
}
If we declared m2() as static then in m2() no any variable can access directly because
wwe will get compile time error because static member inside inner classes
class PopCon
{
public void taste()
{
System.out.println("salty");
}
}
public class Test
{
public static void main(String[] args)
{
Page 219
https://gits-sln.blogspot.com Durga sir Java Notes
{
System.out.println("sweet");
}
};
p2.taste(); //sweet
System.out.println(p.getClass().getName());
System.out.println(p1.getClass().getName());
System.out.println(p2.getClass().getName());
}
}
Output-
spicy
salty
sweet
com.java.test.Outer$1
com.java.test.PopCon
com.java.test.Outer$2
The generated .class files are
1. PopCon.class
2. Test.class
3. Test$1.class
4. Test$2.class
Analysis
};
I. We are declaring a class that extends PopCon without name (anonymous inner
classes)
II. For that child class we are creating an object with parent reference.
PopCon p=new PopCon()
{
public void taste()
{
System.out.println("spicy");
}
};
I. We are declaring a class that extends PopCon without name (anonymous inner
classes)
Page 220
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
Page 221
https://gits-sln.blogspot.com Durga sir Java Notes
Page 223
https://gits-sln.blogspot.com Durga sir Java Notes
Page 224
https://gits-sln.blogspot.com Durga sir Java Notes
{
static class Nested
{
public static void main(String []args)
{
System.out.println("static nested class main method");
}
}
javac Test.java
java Test
Output: outer class main method
java Test$Nested
Output: static nested class main method
From normal or regular inner classes we can access both static or non-static member of
outer class directly but from static nested classes we can access static member of outer
class directly and we cannot access non- static members.
public class Outer
{
int x=10;
static int y=20;
static class Nested
{
public void m()
{
//System.out.println(x);//CE:Cannot make a static reference to the non-static field x
System.out.println(y);
}
}
}
}
Difference between normal or regular inner classes and static nested classes
Page 225
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
Page 226
https://gits-sln.blogspot.com Durga sir Java Notes
Every interface present inside interface is always public and static whether we are
declaring or not hence we can implement inner interface directly without implementation
outer interface.
Similarly whenever we are implementing outer interface we are not required to
implement inner interface that is we can implement outer and inner interface
independently.
interface Out
{
public void m1();
interface Inn
{
public void m2();
}
}
Page 227
https://gits-sln.blogspot.com Durga sir Java Notes
In the above example email details is required only for email service and we are not
using anywhere else hence email details class is recommended to declare email service
interface.
We can also implement a class inside interface to provide default implementation that
interface.
Page 228
https://gits-sln.blogspot.com Durga sir Java Notes
In the above example default vehicle is the default implementation of vehicle interface
whereas bus is customize implementation of vehicle interface.
Note-
The class which is declare inside interface is always public static whether we are
declaring or not hence we can create class object directly without having outer interface
type object.
Conclusion-
1. Among classes and interfaces we can declare anything inside anything is possible.
2. The interface which is declare inside interface is it always public and static whether we
are declaring or not.
3. The class which is declare inside interface is always public and static whether we are
declaring or not.
4. The interface which is declare inside a class is always static but need not be public.
Page 229
https://gits-sln.blogspot.com Durga sir Java Notes
Collection
An array is an index collection of fixed no of homogeneous data elements.
The main advantage of array is we can represent multiple values by using single
variable. So that readability of the code will be improved.
Limitation of array-
1) Array are fixed in size that is once we create an array there is no chance of
increasing or decreasing of size based on r requirement due to this, to use array
concept compulsory we should know the size in advance which may not possible
always.
2) Array can hold only homogeneous data type elements.
Student[] s=new Student[1000];
s[0]=new Student(); //valid
s[1]=new Customer(); //CE: incompatible type error
But we can solve this problem by using object type array
Object[] a=new Object[1000];
a[0]=new Student();
a[1]=new Customer();
3) Array concept is not implemented based on some standard data structure and hence
readymade method support is not available for every requirement we have to
write a code explicitly which increases complexity of programming.
To overcome above problem we should go for collection concept
1) Collection are grow able in nature. Hence we can increase and decrease the size on
the based our requirement.
2) Hold both homogeneous and heterogeneous elements.
3) Every collection class is implemented based on some standard data structure hence
for every requirement readymade method support is available. being a
programmer we are responsible to use those method and we are not responsible to
implement those method.
Note-
Performance wise array is best choice but memory wise collection is best choice.
Page 230
https://gits-sln.blogspot.com Durga sir Java Notes
recommended.
Hold only homogeneous data. Hold both homogeneous and
heterogeneous data.
Readymade method support is not Readymade method support is available.
available.
Used to hold both primitive and object. Used to hold only objects but not
primitive.
Collection
If we want to represent a group of individual object as a single entity then we should go
for collection.
Collection framework
It contain several classes and interface which can be used to represent a group of
individual object as a single entity.
Java C++
Collection Container
Collection framework STL(standard template library)
Page 231
https://gits-sln.blogspot.com Durga sir Java Notes
In 1.2 version vector and stack classes are modified to implement list interface.
3) Set
a) It is the child interface of collection.
b) If we want to represent a group of individual object as a single entity where
duplicate are not allowed and insertion order not required then we should go for
set interface.
4) SortedSet(interface)
a) It is the child interface of set.
b) If we want to represent a group of individual object as a single entity where
duplicate are not allowed and all object should be inserted according to some
sorting order then we should go for sortedset.
5) NavigableSet(interface)
It is the child interface of sorted set it contain several method for navigation purpose.
Page 232
https://gits-sln.blogspot.com Durga sir Java Notes
List Set
Duplicate are allowed Not allowed
Insertion order preserved Not preserved
6) Queue(interface)
a) It is the child interface of collection.
b) If we want to represent a group of individual object prior to processing then we
should go for queue.
c) Usually queue follows FIFO order but based on our requirement we can impement
our own priority order also.
Example
Before sending a mail all mail id we have to store in some data structure.
In which order we added mail id in the same order only mail should be delivered for this
requirement queue is best choice.
Page 233
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
All the above interface (collection, list, sortedset, navigableset and queue) meant for
representing a group of individual object.
If we want to represent a group of object as key value pairs then we should go for map.
7) Map
a) Map is not child interface of collection.
b) If we want to represent a group of object as key value pairs then we should go for
map.
Example-
Page 234
https://gits-sln.blogspot.com Durga sir Java Notes
8) SortedMap
a) It is the child interface of map.
b) If we want to represent a group of key value pairs according to some sorting order
of keys then we should go for sorted map.
c) In sorted map the sorting should be based on key but not based on value.
9) NavigableMap
a) It is the child interface of sortedmap.
b) It defined several method for navigation purpose.
Page 235
https://gits-sln.blogspot.com Durga sir Java Notes
Page 236
https://gits-sln.blogspot.com Durga sir Java Notes
Collection
If we want to represent a group of individual object as a single entity then we
should go for collection.
Collection interface define the most common method which are applicable for any
collection object.
The following list of method present in collection interface-
Page 237
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
There is no concrete class which implement collection interface directly.
List
List is child interface of collection.
If we want to represent a group of individual object as a single entity where
duplicate are allowed and insertion order must be preserved then we should go for
list.
We can preserve insertion order via index and we can differentiates duplicate
object by using index hence index will play very important role in list.
List interface defined the following specific method
Positional Access:
List allows add, remove, get and set operations based on numerical positions of
elements in List. List provides following methods for these operations:
void add(int index, Object O): This method adds given element at specified
index.
boolean addAll(int index, Collection c): This method adds all elements from
specified collection to list. First element gets inserted at given index. If there is
already an element at that position, that element and other subsequent
elements(if any) are shifted to the right by increasing their index.
Object remove(int index): This method removes an element from the specified
index. It shifts subsequent elements(if any) to left and decreases their indexes by
1.
Object get(int index): This method returns element at the specified index.
Object set(int index, Object new): This method replaces element at given
index with new element. This function returns the element which was just replaced
by new element.
Search:
List provides methods to search element and returns its numeric position. Following two
methods are supported by List for this operation:
Page 238
https://gits-sln.blogspot.com Durga sir Java Notes
int indexOf(Object o): This method returns first occurrence of given element or -
1 if element is not present in list.
int lastIndexOf(Object o): This method returns the last occurrence of given
element or -1 if element is not present in list.
Iteration:
Range-view:
List Interface provides a method to get the List view of the portion of given List between
two indices. Following is the method supported by List for range view operation.
1. ArrayList
The underline datastructure is resizable array or grow able array.
Duplicate object are allowed.
Inserction order is preserved.
Heterogeneous object are allowed(except treeset and treemap everywhere
heterogeneous object are allowed).
Null insertion is possible.
Constructor in ArrayList
i. ArrayList l=new ArrayList();
Create an empty array list object with default initial capacity 10.
Once ArrayList reaches it max capacity then a new array list object will be created
New capacity= (current capacity*3/2)+1
ii. ArrayList l=new ArrayList(int initialcapacity);
Create an empty array list object with the specified initial capacity.
iii. ArrayList l=new ArrayList(Collection c);
Create an equivalent arraylist object for the given collection.
Example-
import java.util.*;
Page 239
https://gits-sln.blogspot.com Durga sir Java Notes
l.add(10);
l.add("A");
l.add(null);
System.out.println(l);
l.remove(2);
System.out.println(l);
l.add(2,"M");
l.add("N");
System.out.println(l);
}
}
Output-
0
[A, 10, A, null]
[A, 10, null]
[A, 10, M, null, N]
Usually we can use collection to hold and the transfer object from one location to
another location (container) to provide support for this requirement every
collection class by default implement resizable and the clone able interface.
Array list and vector classes implement random access interface so that any
random element we can access with the same speed.
Random access interface present in java.util package and it does’t contain any
method it is a marker interface where required ability will be provided
automatically by the JVM.
Array list is the best choice if our frequent operation is retrieval operation (because
array list implement random access interface).
Array list is the worst choice if our frequent operation is insertion or deletion in the
middle.
Difference between ArrayList and Vector
ArrayList Vector
Evey method present in the arraylist is Synchronized.
non-synchronized.
At a time multiple thread are allowed to At a time only one thread are allowed to
operate on arraylist object and hence it operate on vector object and hence it is
is not thread-safe. thread-safe.
Relatively performance is high because Relatively performance is low because
thread are not required to wait to thread are required to wait to operate on
operate on array list object. vector object.
Introduced in 1.2 version and it is non Introduced in 1.0 version and it is
legacy. legacy.
Page 240
https://gits-sln.blogspot.com Durga sir Java Notes
Example-
import java.util.*;
public class ArrayListDemo {
Page 241
https://gits-sln.blogspot.com Durga sir Java Notes
Output-
0
[Prabhakar, 10, null, Prabhakar]
[Software, 10, null, Prabhakar]
[Pathak, Software, 10, null, Prabhakar]
[Pathak, Software, 10, null]
[javaclass, Pathak, Software, 10, null]
3. Vector
a) The underline data structure is resizable array or growable array.
b) Insertion order is preserved.
c) Duplicate are allowed.
d) Heterogeneous object are allowed.
e) Null insertion is possible.
Page 242
https://gits-sln.blogspot.com Durga sir Java Notes
Method of Vector
To add object
1. void add(int index, Object element)
Inserts the specified element at the specified position in this Vector.
2. boolean add(Object o)
Appends the specified element to the end of this Vector.
3. void addElement(Object obj)
Adds the specified component to the end of this vector, increasing its size by one.
To remove element or object
1. boolean remove(Object o)
Removes the first occurrence of the specified element in this vector, If the vector
does not contain the element, it is unchanged.
2. boolean removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this vector.
3. Object remove(int index)
Removes the element at the specified position in this vector.
4. void removeElementAt(int index)
removeElementAt(int index).
5. void clear()
Removes all of the elements from this vector.
6. void removeAllElements()
Removes all components from this vector and sets its size to zero.
To retrieve element
1. Object get(int index)
Returns the element at the specified position in this vector.
2. Object elementAt(int index)
Returns the component at the specified index.
3. Object firstElement()
Returns the first component (the item at index 0) of this vector.
4. Object lastElement()
Returns the last component of the vector.
Page 243
https://gits-sln.blogspot.com Durga sir Java Notes
Example-
import java.util.*;
}
Output-
10
10
20
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A]
import java.util.*;
Output-
Page 244
https://gits-sln.blogspot.com Durga sir Java Notes
10
10
15
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A]
4. Stack
It is the child class of vector
It is a specially designed class for last in first out order (LIFO).
Constructor of stack
Stack s=new Stack();
Method of Stack
1. Object push(Object element) : Pushes an element on the top of the stack.
2. Object pop() : Removes and returns the top element of the stack. An
‘EmptyStackException’ exception is thrown if we call pop() when the invoking stack
is empty.
3. Object peek() : Returns the element on the top of the stack, but does not
remove it.
4. boolean empty() : It returns true if nothing is on the top of the stack. Else,
returns false.
5. int search(Object element) : It determines whether an object exists in the
stack. If the element is found, it returns the position of the element from the top of
the stack. Else, it returns -1.
Example-
import java.util.*;
}
Output-
[A, B, C]
3
-1
Page 245
https://gits-sln.blogspot.com Durga sir Java Notes
C
C
[A, B]
False
Cursor
If we want get object one by one from the collection then we should go for cursor.
There are three types of cursor available in java
1) Enumeration
2) Iterator
3) ListIterator
1. Enumeration
We can use enumeration to get object one by one from legacy collection object
We can create enumeration object by using element method of vector class
public Enumeration elements();
eg-
Enumeration e=v.elements();//here v is a vector object
Method of Enumeration
a) boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract,
and false when all the elements have been enumerated.
b) Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
Example-
import java.util.*;
Page 246
https://gits-sln.blogspot.com Durga sir Java Notes
Limitation of Enumeration
a) We can apply enumeration concept only for legacy classes and it is not a universal
cursor.
b) By using enumeration we can get only read access and we can’t perform remove
operation.
To overcome above limitation we should go for Iterator.
2. Iterator
We can apply iterator concept for any collection object and hence it is universal
cursor.
By using iterator we can perform both read and remove operation.
We can create iterator object by using iterator method of collection interface.
Public Iterator iterator();
Eg:
Iterator itr=c.iterator();//where c is any collection object
Method of Iterator
Page 247
https://gits-sln.blogspot.com Durga sir Java Notes
1) boolean hasNext( )
Returns true if there are more elements. Otherwise, returns false.
2) Object next( )
Returns the next element. Throws NoSuchElementException if there is not a next
element.
3) void remove( )
Removes the current element. Throws IllegalStateException if an attempt is made
to call remove( ) that is not preceded by a call to next( ).
Example-
// Java program to demonstrate Iterator
import java.util.*;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
for (int i = 0; i < 10; i++)
al.add(i);
System.out.println(al);
// at beginning itr(cursor) will point to
// index just before the first element in al
Iterator itr = al.iterator();
// checking the next element availabilty
while (itr.hasNext())
{
// moving cursor to next element
int i = (Integer)itr.next();
// getting even elements one by one
System.out.print(i + " ");
// Removing odd elements
if (i % 2 != 0)
itr.remove();
}
System.out.println();
System.out.println(al);
}
}
Output-
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9
[0, 2, 4, 6, 8]
Limitations of Iterator :
Only forward direction iterating is possible.
Replacement and addition of new element is not supported by Iterator.
3. ListIterator
It provides bi-directional iteration.
We can perform replacement and the addition of new object in addition to read and
remove operation
We can create listiterator by using listiterator method of list interface
Public ListIterator listIterator();
Page 248
https://gits-sln.blogspot.com Durga sir Java Notes
Eg:
// Here "l" is any List object, ltr is of type
// ListIterator interface and refers to "l"
ListIterator ltr = l.listIterator();
Method of ListIterator
ListIterator interface extends Iterator interface. So all three methods of Iterator interface
are available for ListIterator.
ListIterator define following nine method
// **for Forward direction**
// Returns true if the iteration has more elements
public boolean hasNext();
// **Other Methods**
// same as remove() method of Iterator
public void remove();
Example-
public class ListIteratorDemo
{
public static void main(String[] args)
Page 249
https://gits-sln.blogspot.com Durga sir Java Notes
{
LinkedList l = new LinkedList();
l.add("balkrishna");
l.add("venki");
l.add("chiru");
l.add("nag");
System.out.println(l);
ListIterator ltr = l.listIterator();
while (ltr.hasNext())
{
String s = (String)ltr.next();
if(s.equals("venki"))
{
ltr.remove();
}
else if(s.equals("nag"))
{
ltr.add("chaitu");
}
else if(s.equals("chiru"))
{
ltr.set("charan");
}
}
System.out.println(l);
}
}
Output-
[balkrishna, venki, chiru, nag]
[balkrishna, charan, nag, chaitu]
Note-The most powerful cursor is ListIterator but its limitation is it is applicable only for
list objects.
Difference between Enumeration, Iterator, and ListIterator in Java
Properties Enumeration Iterator ListIterator
Only List
Applicable Only Legacy Any Collection implemented
implemented
for classes classes
classes
Only forward Both forward
Movement Only forward direction
direction and backward
Read, remove,
Accessibilit
Only read access Read and remove access replace, and
y
add access
elements() listIterator()
How to get iterator() method Collection
method of Vector method List
it? interface
class interface
hasNext(),
hasNext(), next(), remove(), next(),
hasMoreElements(
and nextIndex(),
Methods ) and
forEachRemaining(Consumer< hasPrevious(),
nextElements()
? super E> action) previous(),
previousIndex()
Page 250
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(e.getClass().getName());
System.out.println(itr.getClass().getName());
System.out.println(litr.getClass().getName());
}
Output-
Page 251
https://gits-sln.blogspot.com Durga sir Java Notes
Set
Set interface doesn’t contain any new method and we have to use only collection
interface methods.
HashSet
The underline data structure is hash table
Duplicate object are not allowed.
Insertion order is not preserved and it is based on hash code of object.
Null insertion is possible only once.
Heterogeneous object are allowed.
Implement serializable and clone able but not random access interface.
Hashset is the best choice if our frequent operation is search operation.
Note-
In hash set duplicate are not allowed if we are trying to insert duplicate then we won’t
get any compile time or run time error and add() method simply return false.
HashSet h=new HashSet();
Sop(h.add(“A”);//true
Sop(h.add(“A”);//false
Constructors in HashSet:
1. HashSet h = new HashSet();
Default initial capacity is 16 and default load factor is 0.75.
2. HashSet h = new HashSet(int initialCapacity);
default loadFactor of 0.75
3. HashSet h = new HashSet(int initialCapacity, float loadFactor);
4. HashSet h = new HashSet(Collection C);
Page 252
https://gits-sln.blogspot.com Durga sir Java Notes
Output-
false
[null, D, B, C, 10, Z]
LinkedHashSet
HashSet LinkedHashSet
the underline datastructure is hashtable The underline datastructure is a
combination of linkedlist and the
hashtable.
Insertion order not preserved Insertion order preserved
Introduced in 1.2 version Introduced in 1.4 version
In the above program if we replace hashset with linkedhashset then we get an output in
this way
false
[B, C, D, Z, null, 10]
Page 253
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
In general we can use linkedhashset to develop cache based application where duplicate
are not allowed and insertion order preserved.
SortedSet
Sorted set is the child interface of set.
If we want to represent a group of individual object according to some sorting
order without duplicate then we should go for sorted set.
Page 254
https://gits-sln.blogspot.com Durga sir Java Notes
TreeSet
The underline datastructure is balanced tree.
Duplicate object are not allowed.
Insertion order not preserved.
Heterogeneous object are not allowed otherwise we will get runtime exception
saying classcastexception.
Null insertion possible only once.
Implement serializable and cloneable but not random access.
All object will be inserted based on some sorting order it may be default natural
sorting order or customized sorting order.
Constructors of TreeSet class:
1. TreeSet t = new TreeSet();
This will create empty TreeSet object in which elements will get stored in default
natural sorting order.
2. TreeSet t = new TreeSet(Comparator comp);
This constructor is used when external specification of sorting order of elements is
needed.
3. TreeSet t = new TreeSet(Collection col);
This constructor is used when any conversion is needed from any Collection object
to TreeSet object.
4. TreeSet t = new TreeSet(SortedSet s);
This constructor is used to convert SortedSet object to TreeSet Object.
Example-
import java.util.*;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet h=new TreeSet();
h.add("A");
h.add("a");
h.add("B");
h.add("Z");
h.add("L");
System.out.println(h);
}
}
Output-
[A, B, L, Z, a]
Null acceptance-
For non-empty treeset if we are trying to insert null then we will get
nullpointerexception.
For empty treeset as a first element null is allowed but after inserting null if we are
trying to insert another then we will get runtime exception nullpointerexception.
Note-
Until 1.6 version null is allowed as the first element to the empty treeset but form 1.7
version onward null is not allowed even as the first element. Null such type of story not
applicable for treeset not applicable for treeset from 1.7 version onward.
Page 255
https://gits-sln.blogspot.com Durga sir Java Notes
Example-
import java.util.*;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet h=new TreeSet();
h.add(new StringBuffer("A"));
h.add(new StringBuffer("a"));
h.add(new StringBuffer("B"));
h.add(new StringBuffer("Z"));
h.add(new StringBuffer("L"));
System.out.println(h);
}
}
If we are depending on default natural sorting order compuslosy the object should be
homogeneous and comparable otherwise we will get runtime exception saying
ClassCastException.
System.out.println("A".compareTo("Z"));//-25
System.out.println("A".compareTo("A"));//0
System.out.println("a".compareTo("A"));//32
System.out.println("A".compareTo(null));//NPE
}
}
If we are depending on default natural sorting order then while adding object into the
treeset JVM will call compareTo() method
Page 256
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
If default natural sorting order not available or if we are not satisfied with default natural
sorting order then we can go for customize sorting by using comparator.
Comparable meant for default natural sorting order whereas comparator meant for
customize sorting order.
Comparator
Comparator present in java.util package and it define two method compare() and equal()
public int compare(Object obj1, Object obj2);
return –ve if obj1 has to come before obj2
return +ve if obj1 has to come after obj2
return 0 if obj1 and obj2 are equal
public boolean equals(Object obj)
Page 257
https://gits-sln.blogspot.com Durga sir Java Notes
At the line 1 if we are not passing the comparator object then internally JVM will call
compareTo() method which is meant for default natural sorting order in this case the
output is
Page 258
https://gits-sln.blogspot.com Durga sir Java Notes
0,5,10,15,20
But if we are passing comparator object then JVM will call compare method which is
meant for customizer sorting in this case the output is
20,15,10,5,0
Various possible implementation of compare() method
Write a program to insert string object in a treeset where all element should be
inserted according to reverse of alphabetical order.
Page 259
https://gits-sln.blogspot.com Durga sir Java Notes
If we are depending on default natural sorting order then compulsory object should be
homogeneous and comparable otherwise we will get runtime exception
clascastexception.
If we are defining our own sorting by comparator then object need not be comparable
and homogeneous that is we can add heterogeneous non-comparable also.
Write program to inset string and stringbuffer object into treeset where sorting
order is increasing length order. If two object having same length then consider
their alphabetical order.
Page 260
https://gits-sln.blogspot.com Durga sir Java Notes
Comparable vs comparator
1. For predefined comparable classes default natural sorting order already available if
we are not satisfied with that default natural sorting order then we can define our
own sorting by using comparator.
2. For predefined non-comparable (like a StringBuffer) default natural sorting order
not already available we can define our own sorting by using comparator.
3. For our own classes like employee the person who is writing the class is
responsible to define default natural sorting order by implementing comparable
interface.
4. The person who is using our class if he is not satisfied with default natural sorting
order then he can define own sorting by using comparator.
Page 261
https://gits-sln.blogspot.com Durga sir Java Notes
import java.util.*;
class Employee implements Comparable
{
String name;
int eid;
Employee(String name, int eid)
{
this.name=name;
this.eid=eid;
}
public String toString()
{
return name+" "+eid;
}
public int compareTo(Object obj)
{
int eid1=this.eid;
Employee e=(Employee)obj;
int eid2=e.eid;
if(eid1<eid2)
{
return -1;
}
else if(eid1>eid2)
{
return +1;
}
else return 0;
}
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee e1=new Employee("nag",100);
Employee e2=new Employee("balaiah",200);
Employee e3=new Employee("chiru",50);
Employee e4=new Employee("venki",150);
Employee e5=new Employee("nag",100);
TreeSet t=new TreeSet();
t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
Page 262
https://gits-sln.blogspot.com Durga sir Java Notes
t.add(e5);
System.out.println(t);//sortig based on eid
TreeSet t1=new TreeSet(new MyComparator());
t1.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t1);//sorting based on alphabatic order
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
Employee e1=(Employee)obj1;
Employee e2=(Employee)obj2;
String s1=e1.name;
String s2=e2.name;
return s1.compareTo(s2);
}
Output-
Comparable Comparator
It is meant for default natural sorting It is meant for customize sorting order
order.
Present in java.lang package Presenet in java.util package.
It define only one method compareTo() It define two methods compare() and
equals()
String and all wrapper classes implements The only implemented classes of
comparable interface comparator are Collator,
RuleBasedCollator.
Page 263
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
For empty tree set as the first element null is allowed but this rule is applicable until 1.6
version only form 1.7 version onward null is not allowed even as the first element.
Map(I)
Page 264
https://gits-sln.blogspot.com Durga sir Java Notes
10 Puts an entry in the invoking map, overwriting any previous value associated with the key. The key
and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the
previous value linked to the key is returned.
void putAll(Map m)
11
Puts all the entries from m into this map.
Object remove(Object k)
12
Removes the entry whose key equals k.
int size( )
13
Returns the number of key/value pairs in the map.
Collection values( )
14
Page 265
https://gits-sln.blogspot.com Durga sir Java Notes
Returns a collection containing the values in the map. This method provides a collection-view of the
values in the map.
Entry(Interface)
A map is a group of key value pairs and the each key value pair is classed an entry
hence map is consider as a collection of entry object.
Without existing map object there is no chance of existing entry object hence entry
interface is define inside map interface.
Interface Map
{
Interface Entry
{
Object getKey();
Page 266
https://gits-sln.blogspot.com Durga sir Java Notes
Object getValue();
Object setValue(new object);
}
}
HashMap
The underline datastructure is hashtable.
Insertion order is not preserved and it is based on hashcode of keys.
Duplicate keys are not allowed but values can be duplicated.
Heterogeneous object are allowed for both key and value.
Null is allowed for key (only once)
Null is allowed for value (any number of times)
Hashmap implements serializable and clone able interface but not random access.
Hashmap is the best choice if our frequent operation is search operation.
HashMap provides 4 constructors and access modifier of each is public:
1. HashMap(): It is the default constructor which creates an instance of HashMap
with initial capacity 16 and load factor 0.75.
HashMap m=new HashMap();
Example-
import java.util.*;
Page 267
https://gits-sln.blogspot.com Durga sir Java Notes
HashMap Hashtable
1) HashMap is non synchronized. It is not-thread safe Hashtable is synchronized.
and can't be shared between many threads without It is thread-safe and can be
proper synchronization code. shared with many threads.
2) HashMap allows one null key and multiple null Hashtable doesn't allow
values. any null key or value.
Hashtable is a legacy
3) HashMap is a new class introduced in JDK 1.2.
class.
4) HashMap is fast. Hashtable is slow.
5) We can make the HashMap as synchronized by calling Hashtable is internally
this code synchronized and can't be
Map m = Collections.synchronizedMap(hashMap); unsynchronized.
Hashtable is traversed by
6) HashMap is traversed by Iterator.
Enumerator and Iterator.
Enumerator in Hashtable is
7) Iterator in HashMap is fail-fast.
not fail-fast.
Hashtable inherits
8) HashMap inherits AbstractMap class.
Dictionary class.
Page 268
https://gits-sln.blogspot.com Durga sir Java Notes
LinkedHashMap
It is the child class of HashMap.
It is exactly same as the HashMap except the following difference
HashMap LinkedHashMap
The underlying data structure is The underlying data structure is
HashTable HashTable+LinkedList means hybrid data
structure.
Insertion order is not preserved it is Insertion order is preserved.
based of Hash code of keys.
In the above HashMap program if we replaced HashMap with LinkedHashMap then output
is
{chiranjeevi=700, balaiah=800, venkatesh=200, nagarjuna=500}
IdentityHashMap
It is exactly same as HashMap inclucing method and constructor except the following
difference
In the case of normal HashMap JVM will use .equals() method to identify duplicate keys,
which is meant for content comparison.
But in the case of identity HashMap JVM will use == operation to identify duplicate keys
which is meant for reference comparison (address comparison).
Page 269
https://gits-sln.blogspot.com Durga sir Java Notes
WeakedHashMap
It is exactly same as HashMap except the following difference
In the case of HashMap even though object does’t have any reference it is not eligible
for GC if it is associated with HashMap that is HashMap dominate GC.
But in the case of WeakHashMap if object does’t contain any reference it is eligible for
GC even though object associated with WeakHashMap that is GC dominates
WeakHashMap.
// Java program to illustrate
// Hashmap
import java.util.*;
class HashMapDemo
{
public static void main(String args[])throws Exception
{
HashMap m = new HashMap();
Demo d = new Demo();
// puts an entry into HashMap
m.put(d," Hi ");
System.out.println(m);
d = null;
Page 270
https://gits-sln.blogspot.com Durga sir Java Notes
Output-
{demo=Hi}
{demo=Hi}
In the above example “demo” object not eligible for GC because it is associated with
HashMap.
In the above program if we replace HashMap with a WeakHashMap then “demo” object
eligible for GC
// Java program to illustrate
// WeakHashmap
import java.util.*;
class WeakHashMapDemo
{
public static void main(String args[])throws Exception
{
WeakHashMap m = new WeakHashMap();
Demo d = new Demo();
// puts an entry into WeakHashMap
m.put(d," Hi ");
System.out.println(m);
d = null;
// garbage collector is called
System.gc();
// thread sleeps for 4 sec
Thread.sleep(4000); .
System.out.println(m);
}
}
class Demo
{
public String toString()
{
return "demo";
Page 271
https://gits-sln.blogspot.com Durga sir Java Notes
// finalize method
public void finalize()
{
System.out.println("finalize method is called");
}
}
Output-
{demo = Hi}
finalize method is called
{ }
SortedMap
It is the child interface of Map.
It we want to represent a group of object as a group of key value paste according
to some sorting order of keys then we should go for SrotedMap.
Sorting is based on key but not based on value.
SortedMap define the following specific method which is same as SortedSet
1. comparator() : Returns the comparator used to order the elements in this set, or
null if this set uses the natural ordering of its elements.
2. first() : Returns the first (lowest) element currently in this set.
3. headSet(E toElement) : Returns a view of the portion of this set whose elements
are strictly less than(<) toElement.
4. last() : Returns the last (highest) element currently in this set.
5. subSet(E fromElement, E toElement) : Returns a view of the portion of this set
whose elements range from fromElement, inclusive(>=), to toElement,
exclusive(<).
6. tailSet(E fromElement) : Returns a view of the portion of this set whose
elements are greater than or equal(>=) to fromElement.
TreeMap
The underline datastructure is redblack tree.
Page 272
https://gits-sln.blogspot.com Durga sir Java Notes
Insertion order is not preserved and it is based on some sorting order of keys.
Duplicate keys are not allowed but value can be duplicated.
If we are depending on default natural sorting order then keys should be
homogeneous and comparable otherwise we will get runtime exception saying
classcastexception.
If we are defining our own sorting by comparater then keys need not be
homogeneous and comparable we can take heterogeneous non comparable object
also.
Whether we are depending on default natural sorting order or customized sorting
order there are no restriction for values we can take heterogeneous non
comparable object also.
Null acceptance
For non empty TreeMap if we are trying to insert entry with null key then we will
get runtime excetion saying null pointer exception.
For empty TreeMap as the first entry with null key is allowed but after inserting
that entry if we are trying to insert any other entry we will get
nullpointerexception.
Note-
The above nullexception rule applicable until 1.6 version only from 1.7 version onwards
null is not allowed for key.
But for values we can use null any number of times there is no restriction whether it is
1.6 version or 1.7 version.
Constructors in TreeMap
Constructor Description
Page 273
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(m);
Output-
import java.util.*;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap t=new TreeMap();
t.put("xxx",10);
t.put("aaa",20);
t.put("zzz",30);
t.put("lll",40);
System.out.println(t);
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
return s2.compareTo(s1);
}
Output-
Hashtable
The underline data structure hashtable is java class hashtable.
Insertion order is not preserved and it is based on hashcode of keys.
Duplicate keys are not allowed and value can be duplicated.
Page 274
https://gits-sln.blogspot.com Durga sir Java Notes
This is the default constructor of the hash table it instantiates the Hashtable
1
class.
3 This creates a hash table that has an initial size specified by size and a fill
ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it
determines how full the hash table can be before it is resized upward.
Hashtable(Map m)
4
This constructs a Hashtable with the given mappings.
import java.util.*;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Hashtable t=new Hashtable();
t.put(new Temp(5),"A");
t.put(new Temp(2),"B");
t.put(new Temp(6),"C");
t.put(new Temp(15),"D");
t.put(new Temp(23),"E");
t.put(new Temp(16),"F");
System.out.println(t);
}
}
class Temp
{
Page 275
https://gits-sln.blogspot.com Durga sir Java Notes
int i;
Temp(int i)
{
this.i=i;
}
public int hashCode()
{
return i;
}
public String toSting()
{
return i+"";
}
}
Output-
Page 276
https://gits-sln.blogspot.com Durga sir Java Notes
Properties
In our program if anything which changes frequently (like username ,password, mailed,
moble_no etc.) are not recommended to hardcode in java program because if there is
any change to reflect that change recompilation , rebuild, and redeploy the application
are required even some time server restart also which create a big business impact to
the client.
Page 277
https://gits-sln.blogspot.com Durga sir Java Notes
We can overcome this problem by using properties file such type of variable things we
have to configure in the properties file from that properties file we have to read into the
java program and we can use those properties.
The main advantage of this approach is if there is a change in properties file to reflect
that change just redeployment is enough which won’t create any business impact to the
client.
We can use java properties object to hold properties which are coming from properties
file
In normal map (like hashmap, hashtable, treemap )key and value can be any type but in
the case of properties key and value should be string type
Returns the value associated with the key. A null object is returned if the key is neither
in the list nor in the default property list.
Associates value with the key. Returns the previous value associated with the key, or
returns null if no such association exists.
Enumeration propertyNames( )
Returns an enumeration of the keys. This includes those keys found in the default
property list, too.
void load(InputStream streamIn): This method reads a property list (key and
element pairs) from the input byte stream.to load the properties from properties file into
java properties object.
void store(OutputStream streamOut, String Description): After writing the string
specified by description, the property list is written to the output stream linked to
streamOut. To update properties form properties object into properties file.
Page 278
https://gits-sln.blogspot.com Durga sir Java Notes
Example-1
import java.io.*;
import java.util.*;
public class PropertiesDemo {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Properties p=new Properties();
FileInputStream fis=new
FileInputStream("D:/Prabhakar/Test/src/com/java/pptest/abc.properties");
p.load(fis);
System.out.println(p);
String s=p.getProperty("venki");
System.out.println(s);
p.setProperty("nag", "8888");
FileOutputStream fos=new
FileOutputStream("D:/Prabhakar/Test/src/com/java/pptest/abc.properties");
p.store(fos, "Updated by Prabhakar");
}
}
abc.properties
user=scott
venki=9999
pwd=tiger
Output-
{user=scott, venki=9999, pwd=tiger}
9999
After run when we check abc.properties file then we get this file in this format
#Updated by Prabhakar
#Fri Mar 27 10:57:03 IST 2020
nag=8888
user=scott
venki=9999
pwd=tiger
Example-2
Page 279
https://gits-sln.blogspot.com Durga sir Java Notes
Page 280
https://gits-sln.blogspot.com Durga sir Java Notes
Usually queue follows FIFO order but based on our requirement we can implement our
own priority order also (priority queue).
From 1.5 version on words linked list class also implements queue interface.
Linked list based implementation of queue always follows FIFO order.
PriorityQueue
If we want to represent a group of individual object prior to processing according
to some priority then we should go for priority queue.
The priority can be either default natural sorting order or customizer sorting order
defined by comparator.
Insertion order is not preserved and it is based on some priority.
Duplicate object are not allowed.
If we are depending on default natural sorting order cumposary the order should
be homogeneous and comparable otherwise we will get runtime exception saying
classcastexception.
If we are defining our own sorting by comparator then object need not be
homogeneous and comparable.
Null is not allowed even as the first element also.
Page 281
https://gits-sln.blogspot.com Durga sir Java Notes
import java.util.*;
}
Output-
null
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0
0
[1, 3, 2, 7, 4, 5, 6, 10, 8, 9]
In a some platform won’t provide proper support for thread priority and priority queue.
import java.util.*;
public class PriorityQueueDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
PriorityQueue pq=new PriorityQueue(15,new MyComparator1());
pq.offer("A");
pq.offer("Z");
pq.offer("L");
pq.offer("B");
System.out.println(pq);
}
}
class MyComparator1 implements Comparator
{
public int compare(Object obj1, Object obj2)
{
String s1=(String)obj1;
String s2=obj2.toString();
return s2.compareTo(s1);
}
}
Output-
[Z, B, L, A]
Page 282
https://gits-sln.blogspot.com Durga sir Java Notes
1. NavigableSet(I)
2. NavigableMap(I)
NavigableSet(I)
It is the child interface of sorted set and it define several method for navigation purposes
1. Lower(E e) : Returns the greatest element in this set which <e or NULL if there is
no such element.
2. Floor(E e ) : Returns the greatest element in this set which is less than or equal to
given element or NULL if there is no such element.
3. Ceiling(E e) : Returns the lowest element in this set which is >=e or NULL if there
is no such element.
4. Higher(E e) : Returns the lowest element in this set which is >e or NULL if there is
no such element.
5. pollFirst() : Retrieve and remove the first least element. Or return null if there is
no such element.
6. pollLast() : Retrieve and remove the last highest element. Or return null if there is
no such element.
7. descendingSet(): returns a reverse order view of the elements contained in the set.
8. descendingIterator(): returns an iterator that allows traversing over elements in the set in
descending order.
import java.util.*;
/**
* @param args
*/
Page 283
https://gits-sln.blogspot.com Durga sir Java Notes
}
Output-
[1000, 2000, 3000, 4000, 5000]
2000
3000
3000
2000
1000
5000
[4000, 3000, 2000]
[2000, 3000, 4000]
java.util.TreeMap$NavigableSubMap$DescendingSubMapKeyIterator@12b6651
NavigableMap(I)
It is a child interface of SortedMap
It defines several methods for navigations purposes.
A NavigableMap can be easily accessed and traversed in either ascending or
descending key order.
The performance and behavior of ascending operations are likely to be faster and
efficient than that of the descending order.
Page 284
https://gits-sln.blogspot.com Durga sir Java Notes
Methods of NavigableMap:
1. lowerKey(Object key) : Returns the greatest key strictly less than the given key,
or if there is no such key.
2. floorKey(Object key) : Returns the greatest key less than or equal to the given
key, or if there is no such key.
3. ceilingKey(Object key) : Returns the least key greater than or equal to the
given key, or if there is no such key.
4. higherKey(Object key) : Returns the least key strictly greater than the given
key, or if there is no such key.
5. descendingMap() : Returns a reverse order view of the mappings contained in
this map.
6. pollFirstEntry()
7. pollLastEntry()
import java.util.*;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap<String, String> t = new TreeMap<String,String>();
t.put("b","banana");
t.put("c","cat");
t.put("a","apple");
t.put("d","dog");
t.put("g","gun");
System.out.println(t);//{a=apple, b=banana, c=cat, d=dog, g=gun}
System.out.println(t.ceilingKey("c"));//c
System.out.println(t.higherKey("e"));//g
System.out.println(t.floorKey("e"));//d
System.out.println(t.lowerKey("e"));//d
System.out.println(t.pollFirstEntry());//a=apple
System.out.println(t.pollLastEntry());//g=gun
System.out.println(t.descendingMap());// {d=dog, c=cat, b=banana}
System.out.println(t);//{b=banana, c=cat, d=dog}
Page 285
https://gits-sln.blogspot.com Durga sir Java Notes
Collections class
It is a utility class present in java.util package.
It is define several utility methods for collection object like sorting, searching,
reversing etc.
Output-
Befor soritng[Z, A, K, N]
After soritng[A, K, N, Z]
Page 286
https://gits-sln.blogspot.com Durga sir Java Notes
}
class MyComparator2 implements Comparator
{
public int compare(Object obj1, Object obj2)
{
String s1=(String)obj1;
String s2=obj2.toString();
return s2.compareTo(s1);
}
}
Conclusion
The above search method internally we will use binary search algorithm
Successful search return index
Unsuccessful search return insertion point
Insertion point is the location where we can play the target element in sorted list
Before calling binary search method compulsory list should be sorted otherwise we
will get unpredictable result.
If the list is sorted according to comparator then at the time of search operation
also we have to pass same comparator object also otherwise we will get
unpredictable result.
Example-1
import java.util.*;
Output-
[Z, A, M, K, a]
Page 287
https://gits-sln.blogspot.com Durga sir Java Notes
[A, K, M, Z, a]
3
-2
Example-2
import java.util.*;
Page 288
https://gits-sln.blogspot.com Durga sir Java Notes
Page 289
https://gits-sln.blogspot.com Durga sir Java Notes
l.add(10);
l.add(5);
System.out.println(l);
Collections.reverse(l);
System.out.println(l);
}
Output-
[15, 0, 20, 10, 5]
[5, 10, 20, 0, 15]
reverse() vs reverseOrder()
we can use reverse() method to reverse order of element of list.
Whereas we can use reverseOrder() method to get reverse comparator.
Comparator c1=Collections.reverseOrder(Comparator c)
Where c1 is descending order and c is ascending order
// Java program to demonstrate working of Collections.reveseOrder()
// to sort a list in descending order
import java.util.*;
Output-
List after the use of Collection.reverseOrder() and Collections.sort():
[50, 40, 30, 20, 10]
Page 290
https://gits-sln.blogspot.com Durga sir Java Notes
Array class
Array class is an utility class to define several utility method for array object.
1. Sorting element of array
a) public static void sort(primivite[] p)
to sort according to natural sorting order.
b) public static void sort(Object[] a)
to sort according to natural sorting order.
c) public static void sort(Object[] a, Comparator c)
to sort according to customized sorting order.
package com.java.ppteSst;
import java.util.*;
}
class MyComparator33 implements Comparator
{
public int compare(Object o1, Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
Page 291
https://gits-sln.blogspot.com Durga sir Java Notes
return s2.compareTo(s1);
}
}
Output-
Note-
We can sort primitive array only based on default natural sorting order whereas we
can sort object array either based on default natural sorting order or based on
customized sorting order.
Page 292
https://gits-sln.blogspot.com Durga sir Java Notes
for(String s1:s)
{
System.out.print(s1+"\t");
}
Arrays.sort(s);
System.out.println("\n object array after sorting");
for(String s1:s)
{
System.out.print(s1+"\t");
}
System.out.print("\nSearch(s, Z):");
System.out.println(Arrays.binarySearch(s, "Z"));
System.out.print("\nSearch(s, S):");
System.out.println(Arrays.binarySearch(s,"S"));
//----------------------------------------------
Arrays.sort(s,new MyComparator111());
System.out.println(binarySearch(s,"Z",new MyComparator111()));
System.out.println(binarySearch(s,"S",new MyComparator111()));
System.out.println(binarySearch(s,"N",new MyComparator111()));
Output-
before sorting
10 5 20 11 6
after sorting
5 6 10 11 20
Search(a, 6):1
Search(a, 14):-5
Search(s, S):-3
0
-2
-2
Page 293
https://gits-sln.blogspot.com Durga sir Java Notes
By using array reference if we perform any change automatically that change will be
reflected to the list similarly by using list reference if we perform any change that change
will be reflected automatically to the array.
By using list reference we can’t perform any operation which varies the size otherwise
we will get runtime exception saying unsupported operation exception.
Page 294
https://gits-sln.blogspot.com Durga sir Java Notes
By using list reference we are not allowed to replace with heterogeneous object
otherwise we will get runtime exception saying arraystoreexception
Example- l.set(1,new Integer(10)); RE:ArrayStoreException
import static java.util.Arrays.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
Output-
[A, Z, B]
[K, Z, B]
K L B
Multi-Threading
Multitasking
Executing several task simultaneously is the concept of multitasking.
There are two type of multitasking
a) Process based multitasking
b) Thread based multitasking
Page 295
https://gits-sln.blogspot.com Durga sir Java Notes
Defining a Thread
We can define a thread in the following two base
a) By extending thread class
b) By implementing Runnable interface
a) By extending thread class
Example-
Page 296
https://gits-sln.blogspot.com Durga sir Java Notes
Page 297
https://gits-sln.blogspot.com Durga sir Java Notes
Page 298
https://gits-sln.blogspot.com Durga sir Java Notes
Page 299
https://gits-sln.blogspot.com Durga sir Java Notes
{
1. Register this thread with thread scheduler.
2. Perform all other mandatory activity.
3. Invoke run() method.
}
Page 300
https://gits-sln.blogspot.com Durga sir Java Notes
Output-
start method
main method
these output is produced by main thread
372
Page 301
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
Case-9:
After starting a thread if we are trying to restart the same thread then we will get
runtime exception saying IllegalThreadException.
Example-
Thread t=new Thread();
t.start();
:
:
:
t.start();//RE: IllegalThreadException
Page 302
https://gits-sln.blogspot.com Durga sir Java Notes
Page 303
https://gits-sln.blogspot.com Durga sir Java Notes
Case-1: t1.start();
A new thread will be created which is responsible for the execution of thread class run()
method, which has empty implementation.
Case-2: t1.run();
No new thread will be created and thread class run() method will be executed just like a
normal method call.
Case-3: t2.start();
A new thread will be created which is responsible for the execution of MyRunnable class
run() method.
Case-4: t2.run();
A new thread won’t be created and MyRunnable run() method will be executed just like a
normal method call.
Case-5: r.start();
We will get compile time error saying MyRunnable class doesn’t have start capability.
CE: cannot find symbol
Symbol method start()
Location class MyRunnable
Case-5: r.run();
No new thread will be created and MyRunnable run() method will be executed like
normal method call.
Page 304
https://gits-sln.blogspot.com Durga sir Java Notes
Thread(String name)
4
This constructs allocates a new Thread object.
Thread(ThreadGroup g, Runnable r)
5
This allocates a new Thread object.
Thread(ThreadGroup g, Runnable r, String name)
This allocates a new Thread object so that it has target as its run object, has
6
the specified name as its name, and belongs to the thread group referred to
by group.
Thread(ThreadGroup g, Runnable r, String name, long stackSize)
This allocates a new Thread object so that it has target as its run object, has
7
the specified name as its name, belongs to the thread group referred to by
group, and has the specified stack size.
Thread(ThreadGroup g, String name)
8
This allocates a new Thread object.
Output-
main run
method method
run main
method method
Page 305
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());//main thread name
Thread.currentThread().setName("Prabhakar");//change main thread name
System.out.println(Thread.currentThread().getName());//change name of main thread
MyThread t=new MyThread();
System.out.println(t.getName());//child thread default name
t.setName("child");//change child thread default name
System.out.println(t.getName());//change name of child thread default name
System.out.println(10/0);
}
}
Output-
main
Prabhakar
Thread-0
child
Exception in thread "Prabhakar" java.lang.ArithmeticException: / by zero
Output-
main method executed by the thread:main
run method executed by the thread:Thread-0
Thread priority
Every thread in java has some priority it may be default priority generated by JVM or
customized priority provided by programmer.
The valid range of thread priority is 1 to 10 where 1 is min priority 10 is max priority.
Thread class define the following constant to represent some standard priority.
1. public static int MIN_PRIORITY: This is minimum priority that a thread can have.
Value for this is 1.
2. public static int NORM_PRIORITY: This is default priority of a thread if do not
explicitly define it. Value for this is 5.
3. public static int MAX_PRIORITY: This is maximum priority of a thread. Value for
this is 10.
Thread scheduler will use priority while allocating processor.
Page 306
https://gits-sln.blogspot.com Durga sir Java Notes
The thread which is having highest priority will get chance first.
If two thread having same priority then we can’t except exact execution order it
depends on thread scheduler.
Default priority
The default priority only for main thread is 5 but for all the remaining thread it will be
inheriting from the parent i.e. whatever the priority parent has the same priority will be
inheriting to the child.
Output-
5
7
Page 307
https://gits-sln.blogspot.com Durga sir Java Notes
MyThread t=new MyThread(); this line is executed by the main thread and parent
thread is the main thread.
class MyThread extends Thread
{ public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child thread");
}
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread t=new MyThread();
t.setPriority(10);
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
If we are comment t.setPriority(10); line then both main and child thread have the
same priority 5 . We can’t expect execution order and exeat output.
If we are not comment line then main thread has a priority 5 and child thread has the
priority 10 hence child thread will get chance first followed by main thread in this case
output is
Child thread
Child thread
:
: 10 times
Main thread
Main thread
:
: 10 times
Note- some platform won’t provide proper support for thread priority.
Page 308
https://gits-sln.blogspot.com Durga sir Java Notes
If there is no waiting thread or all waiting thread have low priority then same thread
can continue its execution.
If multiple thread are waiting with same priority then which waiting thread will get the
chance we cannot except it depends on thread scheduler.
The thread which is yielded, then it will get chance once again it depends on thread
scheduler and we cannot expect exactly.
Syntax:
public static native void yield()
Example-
class MyThread extends Thread
{ public void run()
{
for(int i=0;i<2;i++)
{
System.out.println("child thread");
Thread.yield();
}
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread t=new MyThread();
t.start();
for(int i=0;i<2;i++)
{
System.out.println("main thread");
}
}
}
In the above program if we are comment Thread.yield(); line then both thread will be
executed simultaneously and we cannot expect which thread will complete first.
If we are not comment this line then child thread always call yield() method because of
that main thread will get chance more no of time and the chance of completing main
thread first is high.
Note- some platform won’t provide proper support for yield() method.
Page 309
https://gits-sln.blogspot.com Durga sir Java Notes
2. join()
if a thread want to wait until completing some other thread then we should go for join()
method.
For example a thread t1 want to wait until completing t2 then t1 has to call t2.join().
If t1 execute t2.join() then immediately t1 will be enter into waiting state until t2
complete.
Once t2 complete then t1 can continue its execution.
Example- Wedding card distribution
Wedding card printing thread(t2) has to wait until when you fixing thread(t1)
completion hence t2 has to call t1.join()
Wedding card distribution thread(t3) has to wait until wedding card printing thread(t2)
completion hence t3 has to call t2.join().
Types of join() method-
1. public final void join()throws InterruptedExcetion
2. Public final void join(long ms)throws InterruptedException
3. Public final void join(long ms, int ns)throws InterruptedException
Note- Every join() method throws interruptedException which is checked exception
hence compulsory we should handle this exception either by using try catch or by throws
keywords otherwise we will get compile time error.
Page 310
https://gits-sln.blogspot.com Durga sir Java Notes
Page 311
https://gits-sln.blogspot.com Durga sir Java Notes
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
case-3: if we are not using any join() method then both child and main thread
executed simultaneously we cannot expect any exact output.
Case-4:
In the above example child thread calls join() method on main thread object hence child
thread has to wait until completing main thread in this case output is main thread
followed by child thread.
Case-5:
If main thread call join() method on child thread object and child thread call join()
method on main thread object then both thread will wait forever and the program will be
paused.(this is something like deadlock condition).
Page 312
https://gits-sln.blogspot.com Durga sir Java Notes
Case-6:
If a thread call join() method on the same thread itself then the program will be stucked
(this is something like deadlock). In this case thread has to be infinite amount of time.
public class ThreadDemo2 {
public static void main(String[] args) throws InterruptedException {
Thread.currentThread().join();
}
}
3. sleep()
If a thread doesn’t want to perform any operation for a particular amount of time then
we should go for sleep method.
Syntax:
// sleep for the specified number of milliseconds
public static void sleep(long millis) throws InterruptedException
Page 313
https://gits-sln.blogspot.com Durga sir Java Notes
Page 314
https://gits-sln.blogspot.com Durga sir Java Notes
If we comment t.interrupt(); the main thread won’t interrupt child thread in this case
child thread will execute for loop 10 times.
If we are not comment this line then main thread interrupt child thread in this case
output is
End of main thread
I am lazy Thread
I got Interrupt
Note-
Whenever we are calling interrupt method if the target thread not in sleeping state or
waiting state then there is no impact of interrupt call immediately interrupt call will be
waited until target thread entered into sleeping or waiting state.
It the target thread entered into sleeping or waiting state then immediately interrupt call
will call the target thread.
If the target thread never entered into sleeping or waiting state in its life time then there
is no impact of interrupt call this is the only case where interrupt call will be wasted.
package com.java.ppteSst;
class MyThread1 extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("I am lazy Thread"+i);
}
try{
Thread.sleep(1000);
}catch(InterruptedException e)
{System.out.println("I got Interrupt");}
}
}
public class ThreadDemo2 {
public static void main(String[] args) {
MyThread1 t=new MyThread1();
t.start();
t.interrupt();
System.out.println("End of main thread");
}
}
In the above example interrupt call waited until child thread complete for loop 10 time.
Page 315
https://gits-sln.blogspot.com Durga sir Java Notes
Synchronization
Synchronized is the modifiers applicable only for method and block but not for classes
and variables.
If multiple threads are trying to operate simultaneously on the same java object then
there may be a chance of data inconsistency problem.
To overcome this problem we should go for synchronized keyword.
If a method or block declared as synchronized then at a time only one thread is
allowed to execute that method or block on the given object so that data
inconsistency problem will be resolved.
The main advantage of synchronized keyword is we can resolve data inconsistency
problem but the main disadvantage of synchronized keyword is it increases waiting
time of threads and create performance problem hence if there is no specific
requirement then it is not recommended to use synchronized keyword.
Internally synchronization concept is implemented by using lock every object in java
has a unique lock
Whenever we are using synchronized keyword then only lock concept will come into
the picture.
If a thread want to execute synchronized method on the given object first it has to
get lock of that object .
Once thread got the lock then it is allowed to execute any synchronized method on
that object.
Once method execution complete automatically thread releases the lock.
So acquiring and releasing lock internally takes care by JVM and programmer not
responsible for this activity.
While a thread executing synchronized method on the given object the remaining
thread are not allowed to execute any synchronized method simultaneously on the
same object but remaining thread are allowed to execute non-synchronized method
simultaneously.
Example-
Page 316
https://gits-sln.blogspot.com Durga sir Java Notes
class X
{
sync m1();
sync m2();
m3();
}
Page 317
https://gits-sln.blogspot.com Durga sir Java Notes
package com.java.ppteSst;
class Display
{
public synchronized void wish(String name)
{
for(int i=0;i<5;i++)
{
System.out.print("Good Morning:");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
System.out.println(name);
}
}
}
class MyThreads extends Thread
{
Display d;
String name;
MyThreads(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.wish(name);
}
}
public class SynchDemo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Display d=new Display();
MyThreads t1=new MyThreads(d,"Dhoni");
MyThreads t2=new MyThreads(d,"Yuraj");
t1.start();
t2.start();
}
Page 318
https://gits-sln.blogspot.com Durga sir Java Notes
If we are not declare wish() method as synchronized then both thread will be executed
simultaneously and hence we will get irregular output like as
Good Morning:Good Morning:Yuraj
Good Morning:Dhoni
Good Morning:Dhoni
Yuraj
But if we are declare wish() method as synchronized then at a time only one thread is
allowed to execute on the given display object hence we will get regular output like as
Good Morning:Dhoni
Good Morning:Dhoni
Good Morning:Yuraj
Good Morning:Yuraj
Case study
If we are using two object
Display d1=new Display();
Display d2=new Display();
MyThreads t1=new MyThreads(d1,"Dhoni");
MyThreads t2=new MyThreads(d2,"Yuraj");
t1.start();
t2.start();
Even though wish() method is synchronized we will get innregular output because
threads are operating on different java objects.
Conclusion
If multiple threads are operation on same java object then synchronization is
required
Page 319
https://gits-sln.blogspot.com Durga sir Java Notes
Here m1(), m2() used class level lock but m3(), m4() and m5() used object level lock.
Example-
package com.java.ppteSst;
class Display
{
public synchronized void displayn()
{
for(int i=1;i<=10;i++)
{
System.out.print(i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
}
}
public synchronized void displayc()
{
for(int i=65;i<=75;i++)
{
System.out.print((char)i);
try {
Thread.sleep(2000);
Page 320
https://gits-sln.blogspot.com Durga sir Java Notes
} catch (InterruptedException e) {}
}
}
}
class MyThreads1 extends Thread
{
Display d;
MyThreads1(Display d)
{
this.d=d;
}
public void run()
{
d.displayn();
}
}
class MyThreads2 extends Thread
{
Display d;
MyThreads2(Display d)
{
this.d=d;
}
public void run()
{
d.displayc();
}
}
public class SynchDemo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Display d=new Display();
MyThreads1 t1=new MyThreads1(d);
MyThreads2 t2=new MyThreads2(d);
t1.start();
t2.start();
}
Output-
Check output by using synchronized keyword and by using without synchronized
keyword
Every object in Java has a unique lock. If a thread wants to execute a synchronized method on a given object,
first it has to get a lock of that object. Once thread got the lock then it is allowed to execute any synchronized
method on that object. Once method execution completes automatically thread releases the lock. Acquiring and
release lock internally is taken care of by the JVM. Object level lock is a mechanism when we want to
Page 321
https://gits-sln.blogspot.com Durga sir Java Notes
synchronize a non-static method or non-static code block such that only one thread will be able to execute the
code block on a given instance of the class. This can always be done to make instance-level data thread-safe.
Example
public class ObjectLevelLockTest implements Runnable {
@Override
public void run() {
objectLock();
}
public void objectLock() {
System.out.println(Thread.currentThread().getName());
synchronized(this) {
System.out.println("Synchronized block " + Thread.currentThread().getName());
System.out.println("Synchronized block " + Thread.currentThread().getName() + "
end");
}
}
public static void main(String[] args) {
ObjectLevelLockTest test1 = new ObjectLevelLockTest();
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test1);
ObjectLevelLockTest test2 = new ObjectLevelLockTest();
Thread t3 = new Thread(test2);
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
}
Output
t1
t2
t3
Synchronized block t1
Synchronized block t3
Synchronized block t1 end
Synchronized block t3 end
Synchronized block t2
Synchronized block t2 end
Class level lock
Every class in Java has a unique lock which is nothing but a class level lock. If a thread wants to execute a
static synchronized method, then thread requires a class level lock. Once a thread got the class level lock, then
it is allowed to execute any static synchronized method of that class. Once method execution completes
automatically thread releases the lock. The Class level lock prevents multiple threads to enter in a synchronized
block in any of all available instances on runtime.
Example
public class ClassLevelLockTest implements Runnable {
@Override
public void run() {
classLock();
}
public void classLock() {
System.out.println(Thread.currentThread().getName());
synchronized(ClassLevelLockTest.class) {
System.out.println("Synchronized block " + Thread.currentThread().getName());
Page 322
https://gits-sln.blogspot.com Durga sir Java Notes
Synchronized block
If very few line of code requires synchronization then it is never recommended to
declare entire method as synchronized.we have to enclose those few line of code by
using synchronized block.
The main advantage of synchronized block over synchronized method is it reduces it
waiting time of thread and improves performance of application.
We can declare synchronized block as follows
1. To get lock of current object
synchronized (this) {
//code block
If a thread got lock of current object then only it is allowed to execute this area
}
synchronized (b) {
//code block
If a thread got lock of particular object ‘b’ then only it is allowed to execute this area
}
3. To get class level lock
synchronized (Display.class) {
//code block
Page 323
https://gits-sln.blogspot.com Durga sir Java Notes
If a thread got class level lock of ‘Display’ class then only it is allowed to execute this area
}
Example-
package com.java.ppteSst;
class Display
{
public void wish(String name)
{
//1 lakh line of code
synchronized(this)
{
for(int i=0;i<5;i++)
{
System.out.print("Good Morning:");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
System.out.println(name);
}
}
//1 lakh line of code
}
}
class MyThreads extends Thread
{
Display d;
String name;
MyThreads(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.wish(name);
}
}
public class SynchDemo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Display d=new Display();
MyThreads t1=new MyThreads(d,"Dhoni");
MyThreads t2=new MyThreads(d,"Yuraj");
t1.start();
t2.start();
}
}
Output-
Given regular output
But in the above example if we are taken
Display d1=new Display();
Display d2=new Display();
MyThreads t1=new MyThreads(d1,"Dhoni");
MyThreads t2=new MyThreads(d2,"Yuraj");
Then we find irregular output
Page 324
https://gits-sln.blogspot.com Durga sir Java Notes
So we can solve this problem by using class level lock in this way
synchronized(Display.class)
{
:
:
}
Lock concept applicable for object types and the class types but not for primitives hence
we cannot pass primitive type of argument to synchronized block otherwise we will get
compile time error saying unexpected type
Question
Q1. What is synchronized keyword and where we can apply?
Q2.Explain advantage of synchronized keyword?
=>We can resolve data inconsistency problem.
Q3. Explain disadvantage of synchronized keyword?
=>It increases waiting time of thread and create performance problem.
Q4.what is Race condition?
=>If multiple threads are operating simultaneously on same java object then there may
be a chance of data inconsistency problem this is called Race condition. We can
overcome this problem by using synchronized keyword.
Q5.what is object lock where it is required?
Q6.what is class level lock where it is required?
Q7.what is difference between class level lock and object level lock?
Q8.Is can a thread acquired multiple threads or not?
=>Yes of course from different object
Q.9 what is synchronized statement?
The statement present in synchronized method or synchronized block is called
synchronized statement.
Inter Thread communication
Two thread can communicate with each other by using wait(), notify() and notifyAll()
method and thread which is expecting updation is responsible to call wait() method then
immediately the thread will enter into waiting state.
The thread which is responsible to perform updating, after performing updating it is
responsible to call notify() method then waiting thread will get that notification and then
continue its execution with those updated items.
Page 325
https://gits-sln.blogspot.com Durga sir Java Notes
wait(), notify() and notifyAll() method present in Object class but not in Thread class
because thread can call this method on any java object.
To call wait(), notify() and notifyAll() methods on any object , Thread should be
owner of that object that is the thread should has lock of that object that is the thread
should be inside synchronized area.
Hence we can call wait(), notify() and notifyAll() methods only from synchronized
area otherwise we will get runtime exception saying IllegalMonitorStateException.
If a thread call wait() method on any object if immediately releases lock of a
particular object and inter into waiting state.
If a thread call notify() method on any object it release the lock of that object but
may not immediately.
Except wait(), notify() and notifyAll() there is no other method where thread releases
lock.
Method Is thread releases lock?
yield() No
join() No
sleep() No
wait() Yes
notify() Yes
notifyAll() Yes
Page 326
https://gits-sln.blogspot.com Durga sir Java Notes
Example-
class ThreadBB extends Thread
{
int total=0;
public void run()
{
synchronized(this)
{
System.out.println("child thread start calculation");//step-2
for(int i=1;i<=100;i++)
{
total=total+i;
}
System.out.println("child thread trying to giving notification");//step-3
this.notify();
}
}
}
public class ThreadAA1
{
public static void main(String[] args) throws InterruptedException
{
ThreadBB b=new ThreadBB();
b.start();
//System.out.println(b);
synchronized(b)
{
System.out.println("main thread trying to call wait method");//step-1
b.wait();
System.out.println("main thread got notification call");//step-4
System.out.println(b.total);//step-5
}
}
}
Output-
Page 327
https://gits-sln.blogspot.com Durga sir Java Notes
}
Output- first check by using only b.sleep(10000); then add b.wait(10000); and check
Page 328
https://gits-sln.blogspot.com Durga sir Java Notes
Page 329
https://gits-sln.blogspot.com Durga sir Java Notes
DeadLock
If two thread are waiting for each other forever, such type of infinite waiting is called
DeadLock.
The synchronized keyword which is used in program is only one that create a deadlock
condition.so many time we should prevent the use of synchronized keyword in program.
Synchronized keyword is a only reason for deadlock situation hence while using
synchronized keyword we have to take special care.
There is no resolution technique for deadlock but several prevention techniques
available.
package com.java.ppteSst;
class A
{
public synchronized void d1(B b)
{
System.out.println("Thread-1 start execution of d1() method");
try
{
Thread.sleep(6000);
}
catch(InterruptedException e){}
System.out.println("thread-1 trying to call B's last()");
b.last();
}
public synchronized void last()
{
System.out.println("inside A this is last() method");
}
}
class B
{
public synchronized void d2(A a)
{
System.out.println("Thread-2 start execution of d2() method");
try
{
Thread.sleep(6000);
}
catch(InterruptedException e){}
System.out.println("thread-2 trying to call A's last()");
a.last();
}
public synchronized void last()
{
System.out.println("inside B this is last() method");
}
}
Page 330
https://gits-sln.blogspot.com Durga sir Java Notes
{
b.d2(a);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DeadlockDemo d=new DeadlockDemo();
//d.m1();
}
}
Output-
In the above program if we remove atleast one synchronoized keywored then the
program won’t enter into deadlock. Hence synchronized keyword is the only one reason
for deadlock situation. So due to this while using synchronized keyword we have to take
special care.
Deadlock vs starvation
Long waiting of a thread where waiting never ends is called deadlock.
Whereas long waiting of a thread where waiting ends at a certain point is called
starvation. For example low priority thread has to wait until completing all high priority
threads it may be long waiting but ends at certain, which is nothing but starvation.
Page 331
https://gits-sln.blogspot.com Durga sir Java Notes
Daemon Threads
The threads which are executing in the background are called daemon threads.
Example- garbage collector, signal disputers, attach listener etc.
The main objective of daemon threads is to provide support for non-daemon threads
(main thread). For example if main threads run with low memory then JVM run garbage
collector to destroy useless object so that no of bites of free memory will be improved
with this free memory main thread can continue its execution.
Usually daemon threads having low priority but based on our requirement daemon
threads can run with high priority also.
a) void setDaemon(boolean status): This method is used to mark the current thread
as daemon thread or user thread. For example if I have a user thread tU then
tU.setDaemon(true) would make it Daemon thread. On the other hand if I have a
Daemon thread tD then by calling tD.setDaemon(false) would make it user thread.
Syntax:
public final void setDaemon(boolean on)
parameters:
on : if true, marks this thread as a daemon thread.
exceptions:
IllegalThreadStateException: if only this thread is active.
SecurityException: if the current thread cannot modify this thread.
b) boolean isDaemon():
This method is used to check that current is daemon. It returns true if the thread is
Daemon else it returns false.
Syntax:
public final boolean isDaemon()
returns:
This method returns true if this thread is a daemon thread;
false otherwise
Note-The main thread is always non-daemon and it is not possible to change its daemon
nature.
Page 332
https://gits-sln.blogspot.com Durga sir Java Notes
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("lazy thread");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class DaemonDemo {
Whenever last non-daemon thread terminated automatically then all daemon thread will
be terminated in respective of their position.
package com.java.ppteSst;
class MyThreadA extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class DaemonDemo {
Page 333
https://gits-sln.blogspot.com Durga sir Java Notes
If we are commenting t.setDaemon(true); Line then both main and child thread are non-
daemon and hence both will be executed until their completion.
If we are not commenting t.setDaemon(true); Line then main thread is non-daemon and
child thread is daemon. Hence whenever main threads terminate automatically child
thread will be terminated.so in this case the output will be
Green thread
Java multithreading concept is implemented by using the following two model’s
1) Green Thread model
2) Native OS model
Green Thread model
The thread which is managed completely by JVM without taking underling OS support
is called green thread.
Very few OS like sun Solaris provide support for green thread model.
Any way green thread model is deprecated and not recommended to use.
Native OS model
The thread which is managed by the JVM with the help of underlying OS, is called
native OS model.
All windows based OS provide support for native OS model.
Page 334
https://gits-sln.blogspot.com Durga sir Java Notes
1. New
2. Ready/Runnable
3. Running
4. Non-Runnable (Blocked)/ waiting
5. Terminated/ dead state
Dead State:-If the business logic of the project is completed means run() over
thread goes dead state.
Page 335
https://gits-sln.blogspot.com Durga sir Java Notes
Page 336
https://gits-sln.blogspot.com Durga sir Java Notes
Exception handling
An unexpected unwanted event that disturbs normal flow of the program is called
exception.
Example- tire puncture exception, file not found exception, sleeping exception
If the application contains exception then the program terminated abnormally then
the rest of the application is not executed.
It is highly recommended to handle exception and the main objective of exception
handling is graceful termination of the program.
Exception handling means just we are providing alternate code to continue the
execution of remaining code & to get normal termination of the application.
Page 337
https://gits-sln.blogspot.com Durga sir Java Notes
Our programmer requirement is to read data from remote file locating at Landon at run
time if Landon file is not available our program should not be terminated abnormally we
have to provide some local file to continue rest of the program normally this way of
defining alternative is nothing but exception handling.
try
{
Read data form remote file locating from Landon
}
catch(FileNotFoundException e)
{
Use local file and continue rest of the program normally
}
Page 338
https://gits-sln.blogspot.com Durga sir Java Notes
1) Inside a method if any exception occurs the method in which it is rise is responsible to
create exception object by including the following information
a) Name of exception
b) Description of exception
c) Location at which exception occurs( stack trace)
2) After creating exception method handover the object to JVM
3) JVM will check whether the method contain any exception handling code or not if the
method doesn’t contain exception handling code then JVM terminate that method
abnormally and remove corresponding from the stack.
4) Then JVM identify caller method and checks whether caller method contain any
handling code or not.
5) If the caller method doesn’t contain any handling code then JVM terminate that caller
method also abnormally and remove the corresponding entry from the stack.
6) This process will be continuing until main method and if the main method also doesn’t
contain handling code then JVM terminate main method also and remove
corresponding entry from the stack.
7) Then JVM handover responsibility of exception handling to default exception handler,
which is the part of JVM.
8) Default exception handler print exception information in the following format and
terminates program abnormally.
Exception in thread “XXX” name of exception : description stack trace
Example-
public class Exception_test {
public static void main(String[] args) {
// TODO Auto-generated method stub
doStuff();
Page 339
https://gits-sln.blogspot.com Durga sir Java Notes
}
public static void doStuff()
{
domoreStuff();
}
public static void domoreStuff()
{
System.out.println(10/0);
}
}
Output-
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Exception_test.domoreStuff(Exception_test.java:14)
at Exception_test.doStuff(Exception_test.java:10)
at Exception_test.main(Exception_test.java:6)
Example-2:
public class Exception_test {
public static void main(String[] args) {
// TODO Auto-generated method stub
doStuff();
}
public static void doStuff()
{
domoreStuff();
System.out.println(10/0);
}
public static void domoreStuff()
{
System.out.println("Hello");
}
}
Output-
Hello
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Exception_test.doStuff(Exception_test.java:11)
at Exception_test.main(Exception_test.java:6)
Example-3:
public class Exception_test {
public static void main(String[] args) {
// TODO Auto-generated method stub
doStuff();
System.out.println(10/0);
}
public static void doStuff()
{
domoreStuff();
System.out.println("hi");
}
public static void domoreStuff()
{
System.out.println("Hello");
}
Output-
Hello
hi
Exception in thread "main" java.lang.ArithmeticException: / by zero
Page 340
https://gits-sln.blogspot.com Durga sir Java Notes
at Exception_test.main(Exception_test.java:7)
Note-
Page 341
https://gits-sln.blogspot.com Durga sir Java Notes
1) Most of the time exception are caused by our program and these are recoverable for
example if our programme requirement to read data from remote file locating at
Landon at runtime if remote file is not available then we will get runtime exception
saying FileNotFoundException.
2) If FileNotFoundException occur we can provide local file and continue rest of program
normally.
try
{
Read data form the remote file locating on Londom
}
catch(FileNotFoundException e)
{
Use local file and continue rest of the program noamally
}
Error
Page 342
https://gits-sln.blogspot.com Durga sir Java Notes
1) Most of the time error are not caused by our program and these are due to lack of
system resources
2) Errors are non-recoverable for example if OutOfMemoryError occurs being a
programmer we can’t do anything and the program will be terminated abnormally.
3) System admin or server admin is responsible to increase heap memory.
Types of Exceptions:-
As per the sun micro systems standards The Exceptions are divided into three types
1) Checked Exception
2) Unchecked Exception
3) Error
Page 343
https://gits-sln.blogspot.com Durga sir Java Notes
InterruptedException checked(fully)
Error unchecked
ThrowableException checked(partially)
ArithmeticException unchecked
nullPointerException unchecked
Exception checked(partially)
FilNotFoundException checked(fully)
Start-1
Exception in thread "main" java.lang.ArithmeticException: / by zero
Page 344
https://gits-sln.blogspot.com Durga sir Java Notes
Start-3
Page 345
https://gits-sln.blogspot.com Durga sir Java Notes
java.lang.ArithmeticException: / by zero
at Exception_test.main(Exception_test.java:7)
2. if we are using System.out.println(e); then we get
java.lang.ArithmeticException: / by zero
3. if we are using System.out.println(e.toString()); then we get
java.lang.ArithmeticException: / by zero
4. if we are using System.out.println(e.getMessage()); then we get
/ by zero
Page 346
https://gits-sln.blogspot.com Durga sir Java Notes
Output-
Output-
Program successful compile.
We can’t declare two catch block for the same exception otherwise we will get compile
time error.
public class Exception_test {
public static void main(String[] args) {
try{
System.out.println(10/0);
}
catch(ArithmeticException e)
{
}
Page 347
https://gits-sln.blogspot.com Durga sir Java Notes
catch(ArithmeticException e)
{
}
}
}
final
1) Final is a modifiers applicable for classes method and variable.
2) If a class declare as final then we can’t extends that class that is we can’t create child
class that class that is inheritance is not possible for final classes.
3) If a method is final than we can’t overwrite that method in the child class.
4) If a variable declare as final then we can’t perform reassignment for that variable.
finally
1) it is a block always associated with try catch to maintain cleanup code.
try
{ risky code;
}
catch (Exception obj)
{ code to be run if the exception raised (handling code);
}
finally
{ Clean-up code;(database connection closing , streams closing……etc)
}
finalize
1) It is a method invoke by garbage collector just before destroying an object to perform
cleanup activity.
2) Once finalize method complete immediately garbage collector destroys that object.
Note-
Finally block is responsible to perform cleanup activity related to try block that is
whatever resources we open at the part of try block will be closed inside finally block.
Whereas finalize method is responsible to perform cleanup activity related to object
whatever rescores associated with object will be deallocated before destroying an object
by using finalize method.
Page 348
https://gits-sln.blogspot.com Durga sir Java Notes
Page 349
https://gits-sln.blogspot.com Durga sir Java Notes
Page 350
https://gits-sln.blogspot.com Durga sir Java Notes
throw
Sometime we can create exception object explicitly we can handover JVM manually for
this we have to use throw keyword.
Hence the main object of throw keyword is to handover our created exception object to
the JVM manually.
Hence the result of above two programs is exactly same as
Exception in thread "main" java.lang.ArithmeticException: / by zero
In the first case main method is responsible to create exception object and handover to
the JVM.
In the second case programmer is creating exception object explicitly and handover to
the JVM manually.
Page 351
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
The best use of throw keyword is for user defines exception or customizes exception for
example if we want to withdraw amount more than our balance amount.
withdraw (double amount)
{
if (amount> balance)
{
Throw new InsufficientFundException();
}
}
But if
public class Exception_test {
static ArithmeticException e;
public static void main(String[] args) {
throw e;
}
}
Case-2: after throw statement we are not allowed any statement directly otherwise we
will get compile time error saying unreachable statement.
public class Exception_test {
public static void main(String[] args) {
System.out.println(10/0);
System.out.println("HELLO");
}
}
RE:Exception in thread "main" java.lang.ArithmeticException: / by zero
But if
public class Exception_test {
public static void main(String[] args) {
throw new ArithmeticException("/ by zero");
System.out.println("HELLO");
}
}
Case-3: we can use throw keywords only for throwable type if we are trying to use for
normal java object we will get compile time error saying incompatibles types
Page 352
https://gits-sln.blogspot.com Durga sir Java Notes
But if
public class Exception_test extends RuntimeException {
public static void main(String[] args) {
throw new Exception_test();
}
}
throws
In our program if there is a possibility of rising checked exception then compulsory we
should handle checked exception otherwise we will get compile time error saying
Unreported exception XXX; must be caught or declare to be thrown.
Example-1
import java.io.*;
public class Exception_test {
public static void main(String[] args) {
PrintWriter pw=new PrintWriter("abc.txt");
pw.println("Hello");
}
}
Example-2
We can handle this compile time error by using the following two way
First way: by using try catch
public class Exception_test {
public static void main(String[] args) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Page 353
https://gits-sln.blogspot.com Durga sir Java Notes
}
}
}
Second way: by using throws
We can use throws to delegate responsibility of exception handling to the caller (it may
be another method or JVM) than caller method is responsible to handle that exception.
public class Exception_test {
public static void main(String[] args) throws InterruptedException {
Thread.sleep(1000);
}
}
Conclusion of throws
1. Throws keyword required only for checked exception and uses of throws for
unchecked exception there is impact.
2. Throws required only to convince compiler and uses of throws doesn’t prevent
abnormal termination of the program.
In the above program if we remove at least one throws statements then the code won’t
compile.
Page 354
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
If is recommended to use try catch over throws keyword.
Case-1: we can use throws keyword for method and constructor but not for classes.
Case-2: we can use thorws keyword only for throwable types if we are trying to use for
normal java classes then we will get compile time error saying incompatible types.
Page 355
https://gits-sln.blogspot.com Durga sir Java Notes
Case-3:
Case-4: within the try block if there is no chance of rising an exception we can’t write
catch block for that exception otherwise we will get compile time error saying
Exception XXX is never thrown in body of corresponding try statement
But this rule is applicable only for fully checked exception.
Page 356
https://gits-sln.blogspot.com Durga sir Java Notes
Page 357
https://gits-sln.blogspot.com Durga sir Java Notes
}
Note-
1) throw keyword is best suitable for users define or customized exception but not for
predefine exception.
2) It is highly recommended to define customized exception as unchecked that is we
have to extends RuntimeException but not Exception.
Page 358
https://gits-sln.blogspot.com Durga sir Java Notes
ArrayIndexOutOfBoundsException
It is the child class of runtime exception and hence it is unchecked
Rised automatically by JVM whenever we are trying to access array elements with
out of range index
int[] a={10,20,30};
System.out.println(a[4]);//ArrayIndexOutOfBoundsException
NullPointerException
It is the child class of runtime exception and hece it is unchecked
Rised automatically by JVM whenever we are trying to perform any operation on
null
String str1=null;
System.out.println(str1.length());//NullPointerException
ClassCastException
It is the child class of runtime exception and hence it is unchecked
Rised automatically by JVM whenever we are trying to tycast parent object to child
type
class Test
{ public static void main(String[] args)
{ String s = new String("ratan");
String s=(string)
Object o = (Object)s;
Object oo = new Object();
String str = (String)oo; // java.lang.ClassCastException
}
}
RE: StackOverflowError
NoClassDefFoundError
Rised automatically by JVM whenever unable to find required .class file
Page 359
https://gits-sln.blogspot.com Durga sir Java Notes
class Test1
{ void m1()
{ System.out.println("Test1 class m1()");
}
}
class Test
{ public static void main(String[] args) throws ClassNotFoundException
{ Test1 t = new Test1();
t.m1();
Class.forName("Emp");
}
}
Observation-1:- In Test class we are hard coding Test1 object but in target location Test1.class file is not available it will
generate RE: java.lang.NoClassDefFoundError.
ExceptionInInilializerError
It is the child class of error and hence it is unchecked
Rised automatically by JVM if any exception occur while executing static variable
assignment and static block
class Test
{ static int a=10/0;
public static void main(String[] args) { }
}
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
class Test
{
static
{ String s=null;
System.out.println(s.length());
}
}
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
IllegalArgumentException
It is the child class of runtime exception and hence it is unchecked
Rised explicitely either by programmer or by API developer to indicate that a
method has been invoked with illegal argument
Thread priority range is 1-10
1 --->low priority 10 --->high priority
Thread t=new Thread();
t.setPriority(11);//IllegalArgumentException
NumberFormatException
It is the direct child class of illegal argument exception which is the child class of
runtime exception and hence it is unchecked.
Rised explicitly either by programmer or by API developer to indicate that we are
trying to convert string to number and the string is not properly formatted.
String str1="abc";
int b=Integer.parseInt(str1);
Page 360
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(b);//NumberFormatException
IllegalStateException
It is the child class of runtime exception and hence it is unchecked.
Rised explicitly either by programmer or by API developer to indicate that a
method has been invoked at wrong time.
After starting a thread we are not allowed to restart same thread again
Thread t=new Thread ();
t.start();
:
:
:
t.start();//RE: IllegalStateException
AssertionError
It is the child class of error and hence it is unchecked.
Rised explicitely by the programmer or by API developer to indicate that assert
statement fails.
Assert(X>10);
If X is not greater than 10 then we will get runtime exception saying assertion error.
Page 361
https://gits-sln.blogspot.com Durga sir Java Notes
Page 362
https://gits-sln.blogspot.com Durga sir Java Notes
Page 363
https://gits-sln.blogspot.com Durga sir Java Notes
We can declare multiple resources but these resources should be separated with
semicolon
try(r1; r2; r3)
{
:
:
}
Example-
try with multiple resource every resource separated with semicolon.
import java.util.*;
import java.io.*;
class Test
{ public static void main(String[] args)
{ try(Scanner s = new Scanner(System.in);FileInputStream fis = new FileInputStream("abc.txt"))
{ System.out.println("enter id");
int a = s.nextInt();
System.out.println("input value="+a);
}
catch (Exception e)
{ System.out.println("entered input wrong .......");
}
}
}
Page 364
https://gits-sln.blogspot.com Durga sir Java Notes
Conclusion
All resources should be auto closeable resources
A resources said to be auto closeable if and only if corresponding class implement
java.lang.AutocloseableInterface
All IO related resources, data base related resources and network related resources
are already implemented auto closable interface.
Being a programmer we are not required to do anything just we should aware the
point
Auto closable interface came in 1.7 v and it contain only one method close().
All resource reference variable are implicitly final and hence within try block we cannot
perform reassignment otherwise we will get compile time error.
The main advantage of try with resource is we are not required to write finally block
explicitly because we are not required to close resources explicitly hence until 1.6 v
finally block is just like hero but form 1.7 v onwards it is dummy and becomes zero.
Page 365
https://gits-sln.blogspot.com Durga sir Java Notes
To overcome this problem sun people introduce multi catch block in 1.7 v
According to this we can write a single catch block that can handle multiple different type
of exception
Page 366
https://gits-sln.blogspot.com Durga sir Java Notes
The main advantage of this approach is length of the code wil reduce and readability of
code will be improved.
Page 367
https://gits-sln.blogspot.com Durga sir Java Notes
Exception propagation
Inside a method if an exception rised and if we are not handling that exception than
exception object will be propagated to caller then caller method is responsible to handle
exception this process is called exception propagation.
Re-throwing Exception
To convert one type of exception to another type exception.
Page 368
https://gits-sln.blogspot.com Durga sir Java Notes
Garbage Collector
Introducton
• In Old Languages Like C+ +, Programmer is Responsible for Both Creation and
Destruction of Objects. Usually Programmer taking Very Much Care while creating
Objects and neglecting Destruction of Useless Objects. Due to his Negligence at certain
Point ,for Creation of New Object, Sufficient Memory May Not be Available and entire
Application will be Down with Memory Problems.Hence Out0fMemoryError is Very
Common Problem in Old Languages Like C+
• But in Java, Programmer is Responsible Only for Creation of Objects and he is Not
Responsible for Destruction of Useless Objects. SUN People provided One Assistant which
is Always Running in the Background for Destruction of Useless Objects. Just because of
this Assistant, the Chance of failing Java Program with Memory Problems is Very very
Less (It is also one reason for Robustness of JAVA). This Assistant is Nothing but
Garbage Collector.
• Hence the Main Objective of Garbage Collector is to Destroy Useless Objects.
• Garbage Collector is best example for Daemon Thread as it is always running in the
background..
• An Object is said to be Eligible for GC if and Only if it doesn't contain any Reference.
The following are Various Possible Ways to Make an Object Eligible for GC.
1) Nullifying the Reference Variable:
If an Object is No Longer required, then Assign null to all its Reference Variables,
Then that Object Automatically Eligible for Garbage Collection.
Page 369
https://gits-sln.blogspot.com Durga sir Java Notes
Page 370
https://gits-sln.blogspot.com Durga sir Java Notes
4) Island of isolation:
Page 371
https://gits-sln.blogspot.com Durga sir Java Notes
Note:
1) If an Object doesn't have any Reference variable then it is Always Eligible for GC.
2) Even though Object having Reference variable Still sometimes it May be a eligible for
Garbage Collection (If All References are Internal References)
Eg: Island of Isolation
Page 372
https://gits-sln.blogspot.com Durga sir Java Notes
Page 373
https://gits-sln.blogspot.com Durga sir Java Notes
Finalization:
• Just Before Destroying an Object Garbage Collector Calls finalize() to Perform Cleanup
Activities (resource deallocation activity).Once finalize() Completes Automatically GC
Destroys that Object.
• finalize() Present in Object Class with the following Prototype (with empty
implementation ).
protected void finalize() throws Throwable { }
• Based on Our Requirement we can Override finalize() method in Our Class to define
our own Cleanup Activities.
Case 1:
• Just before Destroying an Object Garbage Collector Always Calls finailze() on that
Object, then the Corresponding Class finalize() will be executed. For Example, if String
Page 374
https://gits-sln.blogspot.com Durga sir Java Notes
Object Eligible for GC, then String Class finalize() will be executed, but Not Test Class
finalize() method.
public class Test {
public static void main(String[] args) {
String s=new String("Durga");
s=null;
System.gc();
System.out.println("End of main");
}
public void finalize()
{
System.out.println("finalize method call");
}
}
• In the Above Example String Object Eligible for GC and Hence String Class finalize()
got executed, which has Empty Implementation. Hence in this Case Output is End of
Main.
• If we Replace String Object with Test Object, then Test object eligible for GC and hence
Test Class finalize() method will be executed. In this Case Output is
End of Main
finalize Method Called
OR
finalize Method Called
End of Main
public class Test {
public static void main(String[] args) {
Test s=new Test();
s=null;
System.gc();
System.out.println("End of main");
}
public void finalize()
{
System.out.println("finalize method call");
}
}
Case 2:
• Based on Our Requirement we can Call finalize() method Explicitly, then it will be
executed Just Like a Normal Method Call and Object won't be Destroyed. But before
destroying an Object Garbage Collector Always Calls finalize() method.
public class Test {
public static void main(String[] args) {
Test t=new Test();
t.finalize();
t.finalize();
t=null;
System.gc();
System.out.println("End of main");
}
public void finalize()
{
System.out.println("finalize() call");
}
}
Output:
finalize() Called
finalize() Called
Page 375
https://gits-sln.blogspot.com Durga sir Java Notes
finalize() Called
End of main()
• In the Above Example finalize() got executed 3 Times, In that 2 Times explicitly by the
Programmer and 1 Time by the Garbage Collector.
Note:
• Before destroying Servlet Object, Web Container Always Calls destroy() to Perform
Cleanup Activities. But Based on Our Requirement we can Call destroy() from init() and
service() Methods Explicitly, then it will be executed Just Like Normal Method Call and
Servlet Object won't be Destroyed.
Case 3:
If the Programmer Calls finalize() Explicitly and while executing that finalize() if any
Exception Occurs and which is Uncaught (that is there is no catch block), then the
Program will be terminated Abnormally by raising that exception.
If Garbage Collector Calls finalize() method and while executing that finalize() method ,
if any Exception raised which is Uncaught then JVM ignores that exception and rest of
the Program will be executed Normally.
public class Test {
public static void main(String[] args) {
Test t=new Test();
//t.finalize();//called by programmer
t=null;
System.gc();//called by garbage collector
System.out.println("End of main");
}
public void finalize()
{
System.out.println("finalize() call");
System.out.println(10/0);
}
}
If we are Not Commenting Line 1 then Programmer Calls finalize() method and while
executing that finalize() method ArthimeticException raised which is Uncaught. Hence
the Program will be terminated abnormally by raising ArthimeticException. In this the
Output is
finalize() Called
Exception in thread "main" jaya.lang.ArithmeticException: / by zer ()
If we Comment Line 1 then Garbage Collector Calls finalize() method and while
executing that finalize() method ArthemeticException raised which is Uncaught. JVM
Ignores that Exception and Rest of the Program will be executed Normally.
Q: Which of the following is true?
• JVM Ignores Every Exception which are raised while Executing finalize() method.
//False • JVM Ignores Only Uncaught Exceptions which are raised while executing
finalize() method. //true
Case:4
Page 376
https://gits-sln.blogspot.com Durga sir Java Notes
On any object garbage collector calls finalize() once, ever though that object eligible for
GC multiple time.
public class Test {
static Test s;
public static void main(String[] args) throws InterruptedException {
Test t=new Test ();
System.out.println(t.hashCode());
t=null;
System.gc();
Thread.sleep(5000);
System.out.println(s.hashCode());//f and s indicate same object so hashcode is same
s=null;
System.gc();//gc don’t go finalize() method second time they directly destroy object
Thread.sleep(10000);
System.out.println("End of main");
}
public void finalize()
{
System.out.println("finalize() call");
s=this;
}
}
In the above example even though object eligible for GC two times but GC calls finalize()
only once.
Case 5:
We can't Expect Exact Behavior of the Garbage Collector. It is JVM Vendor Dependent. It
is varied from JVM to JVM. Hence for the following Questions we can't Answer Exactly.
1) Exactly at what Time JVM Runs Garbage Collector?
2) In which Order Garbage Collector Identifies Eligible Objects?
3) In which Order Garbage Collector Destroys the Objects?
4) Whether Garbage Collector Destroys All Eligible Objects OR Not?
5) What is the Algorithm followed by Garbage Collector. Etc
Note:
• Usually whenever the Program Runs with Low Memory JVM will Run Garbage Collector.
But we can't Expect Exactly at what Time.
• Most of the Garbage Collectors follow Mark and Sweep Algorithm. But it doesn't Means
Every Garbage Collector follows the Same Algorithm.
Page 377
https://gits-sln.blogspot.com Durga sir Java Notes
In the above program if we keep on increasing i value at certain point memory problem
will be raised and JVM run automatically GC.
Annotations
Annotations are introduced in 1.5 version it represent metadata of the program.
Annotations can be used attach the some additional information to the interfaces,
classes, methods, constructors which can be used by compiler and JVM.
An annotation is present in our program up to .java file, .class file and runnable file.
Annotations are executed by using predefined tool APT (Annotation Processing Tool ).
Page 378
https://gits-sln.blogspot.com Durga sir Java Notes
Lexical Analyzer –
It is also called scanner. It reads the characters from source program and groups them into lexemes
(sequence of characters that “go together”). Each lexeme corresponds to a token. Tokens are defined by
regular expressions which are understood by the lexical analyzer. It also removes lexical errors (for e.g.
erroneous characters), comments and white space.
Page 379
https://gits-sln.blogspot.com Durga sir Java Notes
based
Struts 1.x Struts 2.X
JSF 1.X JSF 2.X
Hibernet 3.2.4 Hibernet 3.2.5
Spring 2.x Spring 3.x
EJB 2.X EJB 3.X
o @Override
o @SuppressWarnings
o @Deprecated
o @Target
o @Retention
o @Inherited
o @Documented
@Override
@Override annotation assures that the subclass method is overriding the parent class
method. If it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to
mark @Override annotation that provides assurity that method is overridden.
class Animal{
void eatSomething(){System.out.println("eating something");}
}
class TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
Page 380
https://gits-sln.blogspot.com Durga sir Java Notes
}}
Test it Now
Output:Comple Time Error
@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("sonoo");
list.add("vimal");
list.add("ratan");
for(Object obj:list)
System.out.println(obj);
}}
Test it Now
Now no warning at compile time.
If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at
compile time because we are using non-generic collection.
@Deprecated
@Deprecated annotation marks that this method is deprecated so compiler prints
warning. It informs user that it may be removed in the future versions. So, it is better
not to use such methods.
class A{
void m(){System.out.println("hello m");}
@Deprecated
void n(){System.out.println("hello n");}
}
class TestAnnotation3{
public static void main(String args[]){
A a=new A();
a.n();
}}
Test it Now
Page 381
https://gits-sln.blogspot.com Durga sir Java Notes
At Compile Time:
Note: Test.java uses or overrides a deprecated API.
Types of Annotation
There are three types of annotations.
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
Page 382
https://gits-sln.blogspot.com Durga sir Java Notes
1) Marker Annotation
@interface MyAnnotation{}
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation{
int value();
}
@interface MyAnnotation{
int value() default 0;
}
Page 383
https://gits-sln.blogspot.com Durga sir Java Notes
3) Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For
example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
}
}
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")
}
class Exception_test{
public static void main(String args[]){
}
}
Example-2: create and use of annotation with member value and default value. If we
are not creating the value of member then by default default value will work but if we
are creating the value of member and default value then creating value work.
Page 384
https://gits-sln.blogspot.com Durga sir Java Notes
{
String os() default “symbian”;
int version() default 1;
}
@SmartPhone(os="Anroid",version=6) //using of annotation with member value
class NokieASeries //using annotation for this class
{
}
class Exception_test{
public static void main(String args[]){
}
}
}
class Exception_test{
public static void main(String args[]){
}
}
Example-4:
@Target(ElementType.TYPE) //meta annotation
@Retention(RetentionPolicy.RUNTIME) //meta annotation
@interface SmartPhone {
String os()default "symbian";
int version()default 1;
}
@SmartPhone(os="Anroid",version=6)
class NokieASeries
{
String model;
int size;
public NokieASeries(String model, int size) {
super();
this.model = model;
this.size = size;
}
Page 385
https://gits-sln.blogspot.com Durga sir Java Notes
class Exception_test{
public static void main(String args[]){
NokieASeries ns=new NokieASeries("Fire",5);
//System.out.println(ns.toString());
Class c=ns.getClass();
Annotation an=c.getAnnotation(SmartPhone.class);
SmartPhone s=(SmartPhone)an;
System.out.println(s.os());
}
}
@Target
FIELD fields
METHOD Methods
CONSTRUCTOR Constructors
PARAMETER Parameter
Page 386
https://gits-sln.blogspot.com Durga sir Java Notes
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
Example to specify annotation for a class, methods or fields
@Retention
RetentionPolicy Availability
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
Let's see the simple example of creating, applying and accessing annotation.
Page 387
https://gits-sln.blogspot.com Durga sir Java Notes
File: Test.java
//Creating annotation
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation{
int value();
}
//Applying annotation
class Hello{
@MyAnnotation(value=10)
public void sayHello(){System.out.println("hello annotation");}
}
//Accessing annotation
class TestCustomAnnotation1{
public static void main(String args[])throws Exception{
MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
System.out.println("value is: "+manno.value());
}}
Test it Now
Output:value is: 10
@Inherited
@Inherited
@interface ForEveryone { }//Now it will be available to subclass also
Page 388
https://gits-sln.blogspot.com Durga sir Java Notes
@interface ForEveryone { }
class Superclass{}
@Documented
Enum
If we want to represent a group named constant then we should go for Enum.
enum month{
jan, feb, mar, ……… dec;
}
;(semicolon) is optional.
Enum concept introduced in 1.5 version.
The main objective of enum is to define our own data types (Enumerated data types).
When compared with old language enum , java enum is more powerful.
Note- inside enum toString() method implemented to return name of the constant
directly.
Page 389
https://gits-sln.blogspot.com Durga sir Java Notes
We can Declare enum either Outside Class OR Inside the Class but Not Inside a
Method. If we are trying to declare inside a method then we will get Compile time
error.
If we declare enum outside of the class then application modifiers are: public, default
and strictfp.
If we declare enum within a class then applicable modifiers are
• Hence 1.5 Version onwards we can Pass enum Type Also as an Argument to switch
Statement.
enum Beer{
KF,KO,RC,FO;//enum constant
}
public class EnumTest {
public static void main(String[] args) {
Beer b=Beer.KF;
switch(b)
{
case KF:
System.out.println("KF...");
break;
case KO:
System.out.println("KO...");
break;
Page 390
https://gits-sln.blogspot.com Durga sir Java Notes
case RC:
System.out.println("RC...");
break;
case FO:
System.out.println("FO...");
break;
default:
System.out.println("not match...");
}
}
}
If we are taking enum type as an argument to switch statement then every case label
should be valid enum constant.
enum Vs Inheritance:
• Every enum in Java is a Direct Child Class of java.lang.Enum Class. Hence we can't
extend any Other enum.
• Every enum is Always final Implicitly and Hence we can't Create Child enum.
• Hence Because of Above Reasons we can conclude that Inheritance Concept is Not
Applicable for enums.
• Hence we can't Use extends Key Word for enums.
Page 391
https://gits-sln.blogspot.com Durga sir Java Notes
interface X{}
enum Y implements X{}
java.lang.Enurn:
• Every enum in Java is the Direct Child Class of java.lang.Enum. Hence this Class Acts
as base Class for All Java enums.
• It is the Direct Child Class of Object and it is an Abstract Class.
• It Implements Serializable and Comparable Interfaces.
values():
Every enum Implicitly contains values() to Return All Values Present Inside enum. Eg:
Beer[] b = Beer.values();
Ordinal():
• Within the enum the Order of Constants are Important and we can Represent this
Order by using Ordinal Value.
• We can find the Ordinal Value of enum Constant by using ordinal() method. public final
int ordinal();
• Ordinal Values are 0 Based Like Array Index.
enum Beer{
KF,KO,RC,FO;
}
public class EnumTest {
public static void main(String[] args) {
Beer[] b=Beer.values();
for(Beer b1:b)
{
System.out.println(b1+":"+b1.ordinal());
}
}
}
Output
KF:0
KO:1
RC:2
FO:3
Page 392
https://gits-sln.blogspot.com Durga sir Java Notes
Output
enum main
• In Addition to Constants if we are declaring any Extra Members Like a Method, then
List of Constants should be in the 1st Line and should Ends with Semicolon (;).
• Inside enum if we are declaring any Extra Members Like a Method, then the 1st should
contain List of Constants, at least Semicolon (;).
• Any Way an Empty enum is a Valid Java Syntax. Eg: enum Fish{}
enum Vs Constructor:
• enum can contain Constructor and it is executed Separately for Every enum Constant
at the Time of enum Class loading.
enum Beer{
KF,KO,RC,FO;
Beer()
{
System.out.println("constructor");
}
}
public class EnumTest {
public static void main(String[] args) {
Beer b=Beer.KF;
System.out.println("Hello");
}
}
Output
constructor
constructor
constructor
constructor
Hello
If we comment Beer b=Beer.KF; This line then the output is Hello.
Page 393
https://gits-sln.blogspot.com Durga sir Java Notes
We can’t create enum object explicitly and hence we can’t invoke enum constructor
directly.
Eg: Beer b=new Beer();
CE: enum type may not be instantiated
enum Beer{
KF(100),KO(75),RC(90),FO;
int price;
Beer(int price)
{
this.price=price;
}
Beer()
{
this.price=65;
}
public int getPrice()
{
return price;
}
}
public class EnumTest {
public static void main(String[] args) {
Beer[] b=Beer.values();
for(Beer b1:b)
{
System.out.println(b1+":"+b1.getPrice());
}
}
}
Output
KF:100
KO:75
RC:90
FO:65
Note-
KF-> public static final Beer KF=new Beer();
KF(100)-> public static final Beer KF=new Beer(100);
Note-
Inside enum we can declare a method, but should be concreate methods only i.e. we
can’t declare abstract methods.
Case 1:
Every enum Constant Represents an Object of the type enum. Hence whatever the
Methods we can Call on Normal Java Objects, we can Call Same Methods on enum
Constants Also.
Page 394
https://gits-sln.blogspot.com Durga sir Java Notes
Case 2:
• If we want to Use Class Name Directly from Outside Package then Required Import is
Normal Import.
• If we want to Access Static Member Directly without Class Name, then Required Import
is Static Import.
Page 395
https://gits-sln.blogspot.com Durga sir Java Notes
Case-3:
Assertion
Very common behave debugging uses of sop statement but the problem with the sop
is after fixing the bug compulsory we have to delete sop statement otherwise these
sop’s will be executed at run time for every request , which create performance
problem and disturbed server log’s.
To overcome this problem sun people introduce assertion concept in 1.4 versions.
Page 396
https://gits-sln.blogspot.com Durga sir Java Notes
The main advantage of assertion when compared with sop’s is after fixing the bug we
are not required to remove assert statement because they won’t be executed by
default at run time.
Based on our requirement we can enable or disable assertion and by default assertion
are disable.
Hence the main objective of assertion is to perform debugging.
Usually we can perform debugging in development and test environment but not in
production environment hence assertion concept applicable for development and test
environment but not for production.
javac AssertDemo1.java
CE: as of release 1.4 version, ‘assert’ is a keyword, and may not be used as an
identifiers (use –source 1.3 or lower to use assert as an identifiers)
javac –source 1.3 AssertDemo1.java
compiles fine but with warning
java AsertDemo1
10
Note-
If we are using assert as identifiers and if we are trying to compile according to old
version (1.3 or lower) then the code compile is fine but with warning.
We can compile a java program according to a particular version by using –source
option.
Page 397
https://gits-sln.blogspot.com Durga sir Java Notes
1. Simple version
Syntax-
assert(b);
Where b should be Boolean type. If b is true then our assumption satisfied and hence
rest of the program will be executed normally. But if b is false then our assumption false
that is somewhere something goes wrong and the program will be terminated
abnormally by rising assertion error. Once we got assertion error we will analyze the
code and we can fix the problem.
Enabling Assertions
By default, assertions are disabled. We need to run the code as given. The syntax for enabling
assertion statement in Java source code is:
java –ea Test
Or
java –enableassertions Test
Disabling Assertions
The syntax for disabling assertions in java are:
java –da Test
Or
java –disableassertions Test
2. Augmented version
We can augment some description with assertion error by using augmented version.
Syntax-
assert(b):e;
Where b is a Boolean type and e can be any type but mostly string type
Page 398
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(x);
}
}
Javac AssertDemo1.java
Java AssertDemo1
10
Java –ea AssertDemo1
RE: AssertionError: here x value should be >10 but it is not
Conclusion-1
assert(b):e;
e will be executed if and only if first argument is false that is if the first argument is true
then second argument won’t be evaluated.
public class AssertDemo1 {
public static void main(String[] args) {
int x=10;
:
:
assert(x==10):++x;
System.out.println(x);
}
}
Javac AssertDemo1.java
Java AssertDemo1
10
Java –ea AssertDemo1
10
Conclusion-2
assert(b):e;
For the second argument we can take method call but void return type method call is not
allowed otherwise we will get compile type error.
public class AssertDemo1 {
public static void main(String[] args) {
int x=10;
assert(x>10):m();
System.out.println(x);
}
public static int m()
{
return 777;
}
}
Javac AssertDemo1.java
Java AssertDemo1
10
Java –ea AssertDemo1
RE: AssertionError: 777
Note-
If m() method return type is void then we will get compile time error saying void
type not allowed here.
Among two version of assertion it is recommend to use augmented version because it
provide more information for debugging.
Page 399
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
We can enable and disable assertion either class wise or package wise also.
Page 400
https://gits-sln.blogspot.com Durga sir Java Notes
Inappropriate way:
public void withdraw(double amount)
{
if(amount > 100)
process Request;
}
2. While performing debugging in our program if there is any place where the control is
not allowed to reach that is the best place to use assertion
Page 401
https://gits-sln.blogspot.com Durga sir Java Notes
Question:
Page 402
https://gits-sln.blogspot.com Durga sir Java Notes
Question:
Question:
Page 403
https://gits-sln.blogspot.com Durga sir Java Notes
AssertionError
It is a child class of error and it is unchecked.
If assert statement fails (that is argument is false) then we will get AssertionError.
Even though it is legal to catch AssertionError but it’s not a good programming
practices.
Page 404
https://gits-sln.blogspot.com Durga sir Java Notes
Note-
In the case of web application if we run java program in debug mode automatically
assert statements will we executed.
Regular Expressions
1) Regular Expressions 2) Pattern 3) Matcher
}
Output
0:2:ab
2:4:ab
5:7:ab
the number of occurances:3
A b a b b a b a
0 1 2 3 4 5 6 7
end() is always return end value index+1.
Pattern:
• A Pattern Object Represents a compiled Version of Regular Expression.
• We can Create a Pattern Object by using compile() of Pattern Class.
public static Pattern compile(String regularExpression);
Matcher:
• We can Use Matcher Object to Match the given Pattern in the target String.
• We can create Matcher Object by using matcher() of pattern classes.
public Matcher matcher(String target);
Page 406
https://gits-sln.blogspot.com Durga sir Java Notes
Page 407
https://gits-sln.blogspot.com Durga sir Java Notes
}
Output-
3:
If we suppose the value of compile() method is X and on the basis of different X value
the result will be
Quantifiers
We can use quantifiers to specify number of occurrence to match.
Page 408
https://gits-sln.blogspot.com Durga sir Java Notes
If we suppose the value of compile() method is X and on the basis of different X value
the result will be
If X=a+ then
0:a
2:aa
5:aaa
If we suppose the value of compile() method is X and on the basis of different X value
the result will be
If X=a? Then
0:a
1:
2:a
3:a
4:
5:a
6:a
7:a
8:
9:
If we suppose the value of compile() method is X and on the basis of different X value
the result will be
If X=a* Then
0:a
1:
2:aa
4:
5:aaa
8:
9:
Page 409
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(s1);
}
}
}
Output-
Garima
Infotech
Solutions
That means except space remaining are token in target string
If we suppose the value of compile() method is X and on the basis of different X value
the result will be
If X=\\. Or X=[.] are given same result
public class RegExDemo1 {
public static void main(String[] args) {
Pattern p=Pattern.compile("X");//this is pattern or regular expression
String[] s=p.split("www.gits.com");//target string as an argument
for(String s1:s)
{
System.out.println(s1);
}
}
}
Output-
www
gits
com
String Tokenizer
It is a specially designed class for tokenization activity.
This class present in java.util package.
Page 410
https://gits-sln.blogspot.com Durga sir Java Notes
{
System.out.println(st.nextToken());
}
}
}
Output-
Garima
Infotech
Solutions
Note-
The default regular expression of StringTokenizer is space.
10 Digit OR 11 Digit:
If the number contains 11 digits then the first digit should be 0
0?[7-9][0-9]{9}
Page 411
https://gits-sln.blogspot.com Durga sir Java Notes
[a-k][0369][a-zA-Z0-9#$]*
Regular Expression to represent all Names starts with a or A and ends with l or
L
[aA][a-zA-Z]*[lL]
Page 412
https://gits-sln.blogspot.com Durga sir Java Notes
Page 413
https://gits-sln.blogspot.com Durga sir Java Notes
Q:Write a Program to Extract All Valid Mail ID's Present in the given
text File where Mail ID's are Mixed with Normal Text Data?
In the Above Program we have to Replace Mobile Number Regular Expression with the
following Mail-ID Regular Expression
[a-zA-Z0-9][a-zA-Z0-9._]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+
JVM Architecture
1) Virtual Machine
2) Types of Virtual Machines
Page 414
https://gits-sln.blogspot.com Durga sir Java Notes
Page 415
https://gits-sln.blogspot.com Durga sir Java Notes
Virtual Machine:
It Provides Several Logical Systems on the Same Computer with Strong Isolation from
Each Other. (Eg: on a single machine we can create different user account which is
isolated form each other)
Examples:
1) KVM (Kernel Based Virtual Machine) for Linux Systems
2) VMware (Virtual Machine ware)
3) Xen
4) Cloud computing
The main advantage of Hard-ware based Virtual Machines is for effective utilization of
hard-ware resources.
Examples:
1) JVM Acts as Runtime Engine to Run Java Applications
2) PVM (Parrot VM) Acts as Runtime Engine to Run Scripting Languages Like PERL.
3) CLR (Common Language Runtime) Acts as Runtime Engine to Run .Net Based
Applications.
JVM
JVM is a part of JRE.
JVM is responsible to load and run java application.
Page 416
https://gits-sln.blogspot.com Durga sir Java Notes
Page 417
https://gits-sln.blogspot.com Durga sir Java Notes
The Class Object can be used by Programmer to get Class Level Information Like Fully
Qualified Name of the Class, Parent Name, Methods and Variables Information Etc.
class Student
{
private String name;
private int rollNo;
public String getName() {
return name;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
}
public class JVM_Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s=new Student();
Class c=s.getClass();
System.out.println(c.getName());//class information
Method[] m=c.getDeclaredMethods();
for(int i=0;i<m.length;i++)
{
System.out.println(m[i]);//method information
}
Page 418
https://gits-sln.blogspot.com Durga sir Java Notes
Field[] f=c.getDeclaredFields();
for(int i=0;i<f.length;i++)
{
System.out.println(f[i]);//variable information
}
}
Output-
com.java.ppteSst.Student
public java.lang.String com.java.ppteSst.Student.getName()
public void com.java.ppteSst.Student.setRollNo(int)
private java.lang.String com.java.ppteSst.Student.name
private int com.java.ppteSst.Student.rollNo
In the above example by using Student class class object we can get its methods and its
variable methods.
Note-
For every loaded .class file only one class object will be created, even though we are
using class multiple times in our program.
2) Linking:
Linking Consists of 3 Activities
1) Verification
2) Preparation
3) Resolution
Verification:
It is the Process of ensuring that Binary Representation of a Class is Structurally
Correct OR Not.
That is JVM will Check whether .class File generated by Valid Compiler OR Not. i.e
whether .class File is Properly Formatted OR Not.
Page 419
https://gits-sln.blogspot.com Durga sir Java Notes
Preparation:
In this Phase JVM will Allocate Memory for the Class Level Static Variables and Assign
Default Values (But Not Original Values).
Note: Original Values will be assigned in Initialization Phase.
Resolution:
• It is the Process of Replacing Symbolic References used by the Loaded Type with
Original References.
• Symbolic References are Resolved into Direct References by searching through Method
Area to Locate the Referenced Entity.
For the Above Class, ClassLoader sub system Loads Test.class, String.class,
Student.class, and Object.class.
The Names of these Class Names are stored in Constant Pool of Test Class.
In Resolution Phase these Names are Replaced with Actual References from Method
Area.
3) Initialization:
In this Phase All Static Variables will be assigned with Original Values and Static Blocks
will be executed from from top to bottom and from Parent to Child.
Page 420
https://gits-sln.blogspot.com Durga sir Java Notes
Note: While Loading, Linking and Initialization if any Error Occurs then we will get
Runtime Exception Saying java.lang.LinkageError. Of course VerifyError is child class of
LinkageError only.
Every Class Loader Sub System contains the following 3 Class Loaders.
This Class loader responsible for loading core java API classes i.e. the classes present in
rt.jar.
Location: Jdk\jre7\lib\rt.jar
This Location is called Bootstrap Class Path i.e. Bootstrap Class Loader is Responsible to
load Classes from Bootstrap Class Path.
Page 421
https://gits-sln.blogspot.com Durga sir Java Notes
Bootstrap Class Loader Is by Default Available with the JVM. It is implemented in Native
Languages Like C and C++.
2) Extension Class Loader:
It Is the Child of Bootstrap Class Loader. The Class Loader Is Responsible to load Classes
from Extension Class Path.
Location: jdk\jre\lib\ext
This class loader is implemented in java and the corresponding .class file name is
sun.misc.Launcher$ExtClassLoader.class
Assume that Student.class present in both extension and application classpaths and
Test.class present in only Application classpath.
For String Class:
From Bootstrap Class Path by Bootstrap Class Loader Output is null(b'z BootStrap class
Loader is not implemented In Java and It is not Java object)
For Student Class:
From Extension Class Path by Extension Class Loader Output is
sun.misc.Launcher$ExtClassLoader@1234
For Test Class:
From Application Class Path by Application Class Loader Output Is
sun.misc.Launcher$AppClassLoader@3456
Note:
Page 422
https://gits-sln.blogspot.com Durga sir Java Notes
Bootstrap Class Loader is not Java Object. Hence we are getting null In the 1st Case but
Extension Class Loader and Application Class Loader are Java Objects and Hence wo are
getting proper output.
ClassName@HexaDecimal String of Hashcode
Class Loader Subsystem will give Highest Priority for Bootstrap Class Path and then
Extension Class followed by Application Class Path.
Page 423
https://gits-sln.blogspot.com Durga sir Java Notes
Note: The ClassLoader Delegation Hierarchy Model always functions in the order
Application ClassLoader->Extension ClassLoader->Bootstrap ClassLoader. The Bootstrap
ClassLoader is always given the higher priority, next is Extension ClassLoader and then
Application ClassLoader.
1. Delegation Model: The Java Virtual Machine and the Java ClassLoader use an
algorithm called the Delegation Hierarchy Algorithm to Load the classes into the
Java file.
Page 424
https://gits-sln.blogspot.com Durga sir Java Notes
The ClassLoader works based on a set of operations given by the delegation model.
They are:
ClassLoader always follows the Delegation Hierarchy Principle.
Whenever JVM comes across a class, it checks whether that class is already
loaded or not.
If the Class is already loaded in the method area then the JVM proceeds with
execution.
If the class is not present in the method area then the JVM asks the Java
ClassLoader Sub-System to load that particular class, then ClassLoader sub-
system hands over the control to Application ClassLoader.
Application ClassLoader then delegates the request to Extension ClassLoader
and the Extension ClassLoader in turn delegates the request to Bootstrap
ClassLoader.
Bootstrap ClassLoader will search in the Bootstrap classpath(JDK/JRE/LIB). If
the class is available then it is loaded, if not the request is delegated to
Extension ClassLoader.
Extension ClassLoader searches for the class in the Extension
Classpath(JDK/JRE/LIB/EXT). If the class is available then it is loaded, if not the
request is delegated to the Application ClassLoader.
Application ClassLoader searches for the class in the Application Classpath. If
the class is available then it is loaded, if not then
a ClassNotFoundException exception is generated.
2. Visibility Principle: The Visibility Principle states that a class loaded by a parent
ClassLoader is visible to the child ClassLoaders but a class loaded by a child
ClassLoader is not visible to the parent ClassLoaders. Suppose a class GEEKS.class
has been loaded by the Extension ClassLoader, then that class is only visible to the
Extension ClassLoader and Application ClassLoader but not to the Bootstrap
ClassLoader. If that class is again tried to load using Bootstrap ClassLoader it gives
an exception java.lang.ClassNotFoundException.
3. Uniqueness Property: The Uniquesness Property ensures that the classes are
unique and there is no repetition of classes. This also ensures that the classes
loaded by parent classloaders are not loaded by the child classloaders. If the parent
class loader isn’t able to find the class, only then the current instance would attempt
to do so itself.
Page 425
https://gits-sln.blogspot.com Durga sir Java Notes
Page 426
https://gits-sln.blogspot.com Durga sir Java Notes
Page 427
https://gits-sln.blogspot.com Durga sir Java Notes
Page 428
https://gits-sln.blogspot.com Durga sir Java Notes
Page 429
https://gits-sln.blogspot.com Durga sir Java Notes
JDBC
What is JDBC ?
JDBC is an acronym for Java Database Connectivity.
It’s an advancement for ODBC ( Open Database Connectivity ).
JDBC is an standard API specification developed in order to move data from
frontend to backend. This API consists of classes and interfaces written in
Java. It basically acts as an interface (not the one we use in Java) or channel
between your Java program and databases i.e it establishes a link between the two
so that a programmer could send data from Java code and store it in the database
for future use.
Why JDBC came into existence ?
ODBC being platform dependent had a lot of drawbacks. ODBC API was written in
C,C++, Python, Core Java and as we know above languages (except Java and some part
of Python )are platform dependent .
Therefore to remove dependence, JDBC was developed by database vendor which
consisted of classes and interfaces written in Java.
Page 430
https://gits-sln.blogspot.com Durga sir Java Notes
Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
If type-4, type-3 and type-2 driver is not available then we used it.
3. Network Protocol driver (fully java driver)- converts JDBC calls directly or indirectly
into the vendor-specific database protocol
Page 431
https://gits-sln.blogspot.com Durga sir Java Notes
4. Thin driver (fully java driver)- converts JDBC calls directly into the vendor-specific
database protocol
If you are using only one type of database.
It is used for standalone application and small scale web application
Note-
Type-1, type-2 and type-3 driver need extra component to communicate with
Database so it is called thick driver
Type-4 no need extra component to communicate with Database so it is called thin
driver.
Class.forName("oracle.jdbc.driver.OracleDriver");
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put
vender's Jar in the classpath, and then JDBC driver manager can detect and load the
driver automatically.
2) Create the connection object
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","password");
con.close();
Page 432
https://gits-sln.blogspot.com Durga sir Java Notes
To connect java application with the Oracle database ojdbc14.jar file is required to be
loaded.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially,
cursor points to before the first row.
Note- By default, ResultSet object can be moved forward only and it is not updatable.
Page 433
https://gits-sln.blogspot.com Durga sir Java Notes
1) public boolean next(): is used to move the cursor to the one row next from the current
position.
2) public boolean previous(): is used to move the cursor to the one row previous from the
current position.
3) public boolean first(): is used to move the cursor to the first row in result set object.
4) public boolean last(): is used to move the cursor to the last row in result set object.
5) public boolean absolute(int is used to move the cursor to the specified row number in the
row): ResultSet object.
6) public boolean relative(int is used to move the cursor to the relative row number in the
row): ResultSet object, it may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of the
columnIndex): current row as int.
8) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.
9) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.
10) public String is used to return the data of specified column name of the
getString(String current row as String.
columnName):
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","or
acle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UP
DATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
Page 434
https://gits-sln.blogspot.com Durga sir Java Notes
con.close();
}}
PreparedStatement interface
is a subinterface of Statement. It is used to execute parameterized query.
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter
value) index.
public void setString(int paramIndex, sets the String value to the given parameter
String value) index.
public void setFloat(int paramIndex, sets the float value to the given parameter index.
float value)
public void setDouble(int paramIndex, sets the double value to the given parameter
double value) index.
public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
Page 435
https://gits-sln.blogspot.com Durga sir Java Notes
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
int i=stmt.executeUpdate();
System.out.println(i+" records updated");
Page 436
https://gits-sln.blogspot.com Durga sir Java Notes
stmt.setInt(1,101);
int i=stmt.executeUpdate();
System.out.println(i+" records deleted");
do{
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine());
System.out.println("enter name:");
String name=br.readLine();
System.out.println("enter salary:");
float salary=Float.parseFloat(br.readLine());
ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");
Page 437
https://gits-sln.blogspot.com Durga sir Java Notes
con.close();
}}
If you have to get metadata of a table like total number of column, column name,
column type etc. , ResultSetMetaData interface is useful because it provides methods to
get metadata from the ResultSet object.
Method Description
Page 438
https://gits-sln.blogspot.com Durga sir Java Notes
Page 439
https://gits-sln.blogspot.com Durga sir Java Notes
Page 440
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println("Enter emp_id:");
int eid=sc.nextInt();
System.out.println("Enter emp_name:");
String ename=sc.next();
System.out.println("Enter emp_dept:");
String edept=sc.next();
//String sqlQuery="insert into emp
values("+eid+",'"+ename+"',1'"+edept+"')";//traditional approach
String sqlQuery=String.format("insert into emp
values(%d,'%s','%s')", eid,ename,edept);//modern approach
st.executeUpdate(sqlQuery);
System.out.println("Record inserted successufully");
System.out.println("Do you want to insert one more record
[Yes/No]");
String option=sc.next();
if(option.equalsIgnoreCase("No"))
{
break;
}
}
con.close();
}
Page 441
https://gits-sln.blogspot.com Durga sir Java Notes
index
Servlet
Used to create a web application (resides at server side and generates a dynamic web
page).
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic
web page.
Page 442
https://gits-sln.blogspot.com Durga sir Java Notes
CGI vs Servlet
BASIS FOR
CGI SERVLET
COMPARISON
GET POST
Page 443
https://gits-sln.blogspot.com Durga sir Java Notes
5) Get request is more efficient and Post request is less efficient and
used more than Post. used less than get.
Servlets API’s:
Servlets are build from two packages:
javax.servlet(Basic)
javax.servlet.http(Advance)
Servlet container,
also known as Servlet engine is an integrated set of objects that provide run time environment for
Java Servlet components.
In simple words, it is a system that manages Java Servlet components on top of the Web
server to handle the Web client requests.
Page 444
https://gits-sln.blogspot.com Durga sir Java Notes
Servlet Interface
Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to
service the requests, and to destroy the servlet and 2 non-life cycle methods.
GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except the service
method.
Page 445
https://gits-sln.blogspot.com Durga sir Java Notes
For compiling the Servlet, jar file is required to be loaded. Different Servers provide
different jar files:
Jar file Server
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
There are too many elements in the web.xml file. Here is the illustration of some elements
that is used in the above web.xml file. The elements are as follows:
<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client
side to invoke the servlet.
Page 446
https://gits-sln.blogspot.com Durga sir Java Notes
War File
A war (web archive) File contains files of a web project. The war file combines all the
files into a single unit. It may have servlet, xml, jsp, image, html, css, js etc. files.
welcome-file-list in web.xml
A welcome file is the file that is invoked automatically by the server, if you don't specify
any file name.
By default server looks for the welcome file in following order:
1. welcome-file-list in web.xml
2. index.html
3. index.htm
4. index.jsp
If none of these files are found, server renders 404 error.
RequestDispatcher in Servlet
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Page 447
https://gits-sln.blogspot.com Durga sir Java Notes
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
Servlet Filter
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove
the entry of filter from the web.xml file, filter will be removed automatically and we don't
need to change the servlet.
Pagination in Servlet
To divide large number of records into multiple parts (means arrange in multiple pages one
by one), we use pagination. It allows user to display a part of records only. Loading all
records in a single page may take time, so it is always recommended to created pagination.
In servlet, we can develop pagination example easily.
JSP
JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to Servlet because it provides more functionality
than servlet such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags.
Page 448
https://gits-sln.blogspot.com Durga sir Java Notes
The JSP pages are easier to maintain than Servlet because we can separate designing
and development.
It provides some additional features such as Expression Language, Custom Tags, etc.
Page 449
https://gits-sln.blogspot.com Durga sir Java Notes
Example:2
File: index.html
<html>
<body>
<form action="welcome.jsp">
Page 450
https://gits-sln.blogspot.com Durga sir Java Notes
2. expression tag
It is mainly used to print the values of variable or method.
Syntex: <%= statement %>
Example-1
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Note: Do not end your statement with semicolon in case of expression tag
Example-2
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
3. declaration tag
used to declare fields and methods.
<html>
<body>
<%! int data=50; %>
Page 451
https://gits-sln.blogspot.com Durga sir Java Notes
<html>
<body>
<%!
int cube(int n){
return n*n*n;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
out JspWriter For writing any data to the buffer eg: out.print();
request HttpServletRequest get request information such as parameter, header information, remote
address, server name, server port, content type, character encoding etc. It
can also be used to set, get and remove attributes from the jsp request
scope.eg: request.getParameter();
response HttpServletResponse used to set the response content type, add cookie and redirect the
response. Eg: response.sendRedirect();
config ServletConfig used to get initialization parameter for a particular JSP page. Generally, it
is used to get initialization parameter from the web.xml file.Eg:
String driver=config.getInitParameter("dname");
application ServletContext used to get initialization parameter from configuaration file (web.xml). It
can also be used to get, set or remove attribute from the application
scope.Eg: String driver=application.getInitParameter("dname");
pageContext PageContext used to set,get or remove attribute from page, request, session,
application.
Page Object This object is assigned to the reference of auto generated servlet class.
exception Throwable This object can be used to print the exception. But it can only be used in
error pages.
Page 452
https://gits-sln.blogspot.com Durga sir Java Notes
JSP directives
JSP directives are the elements of a JSP source code that guide the web container on how
to translate the JSP page into it’s respective servlet.
Syntax :
<%@ directive attribute = "value"%>
There are three types of directives:
1-page directive
<%@page attribute = "value"%>
Attributes of JSP page directive-
import
contentType
extends
info
buffer
language
isELIgnored
isThreadSafe
autoFlush
session
pageEncoding
errorPage
isErrorPage
<%-- provide a description of the JSP This information is not forward to client as
container ignores the information given in info attribute. --%>
<%-- The buffer attribute sets the buffer size in kilobytes to handle output
generated by the JSP page.The default size of the buffer is 8Kb. --%>
<%-- The language attribute specifies the scripting language used in the JSP page.
The default value is "java". --%>
<%@ page language="java" %>
Page 453
https://gits-sln.blogspot.com Durga sir Java Notes
<%-- The errorPage attribute is used to define the error page, if exception occurs
in the current page, it will be redirected to the error page. --%>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
<%--By classifying a page as an error page, it can use the implicit object
‘exception’ which can be used to display exceptions that have occured.--%>
//JSP code for error page, which displays the exception
<%@ page isErrorPage = "true" %>
<h1>Exception caught</h1>
The exception is: <% = exception %>
Output:
2-include directive
Used to include static resource into the current JSP page at translation time.
3-taglib directive
Taglib directive is used to define tag libraries in JSP page. It enables user to use custom
tags within JSP file. A JSP page can contains more than one taglib directives.
Page 454
https://gits-sln.blogspot.com Durga sir Java Notes
If we input No1 field value as 12 and No2 field value as 0 then we can find error by
error.jsp page
Page 455
https://gits-sln.blogspot.com Durga sir Java Notes
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.
includes the original content in the generated servlet. calls the include method.
JavaBean
A JavaBean is a Java class that should follow the following conventions:
o It should have a no-arg constructor.
o It should be Serializable.
o It should provide getter and setter methods.
A bean encapsulates many objects into one object so that we can access this object from
multiple places.
//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
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;}
}
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
Page 456
https://gits-sln.blogspot.com Durga sir Java Notes
System.out.println(e.getName());
}}
Example:
index.html
<form action="welcome.jsp"/>
Enter Name:<input type="text" name="name"/>
<input type="submit" value="go" />
</form>
welcome.jsp
<jsp:useBean id="obj" class="com.javatpoint.User" />
<jsp:setProperty name="obj" property="*" />
Welcome, <jsp:getProperty name="obj" property="name" />
User.java
package com.javatpoint;
public class User{
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
pageScope it maps the given attribute name with the value set in the page scope
requestScope it maps the given attribute name with the value set in the request scope
Page 457
https://gits-sln.blogspot.com Durga sir Java Notes
sessionScope it maps the given attribute name with the value set in the session scope
applicationScope it maps the given attribute name with the value set in the application scope
Example:
index.jsp
<form action="process.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.name }
Example:
index.jsp
<form action="process.jsp">
Enter value1:<input type="text" name="v1" /><br/>
Enter value2:<input type="text" name="v2" /><<br/>
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.v1+param.v2 }
Addition +
Substraction -
Page 458
https://gits-sln.blogspot.com Durga sir Java Notes
Multiplication *
Equals == and eq
Or || and or
*MVC in JSP
MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.
1. Model represents the state of the application i.e. data. It can also have business
logic.
2. View represents the presentaion i.e. UI(User Interface).
3. Controller acts as an interface between View and Model. Controller intercepts all the
incoming requests.
Advantage of MVC (Model 2) Architecture
1. Navigation Control is centralized
2. Easy to maintain the large application
Page 459
https://gits-sln.blogspot.com Durga sir Java Notes
Example:
1. Fast Development JSTL provides many tags that simplify the JSP.
2. Code Reusability We can use the JSTL tags on various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.
JSTL Tags
Core tags The JSTL core tag provides variable support, URL management, flow
control, etc. The prefix of core tag is c.
Function tags The functions tags provide support for string manipulation and string
length. prefix is fn.
Formatting The Formatting tags provide support for message formatting, number
tags and date formatting, etc. prefix is fmt.
XML tags The XML tags provide flow control, transformation, etc. prefix is x.
SQL tags The JSTL SQL tags provide SQL support. prefix is sql.
Page 460
https://gits-sln.blogspot.com Durga sir Java Notes
The syntax used for including JSTL core library in your JSP is:
Tags Description
c:out It display the result of an expression, similar to the way <%=...%> tag
work.
*c:import It Retrives relative or an absolute URL and display the contents to either a
String in 'var',a Reader in 'varReader' or the page.
c:remove It is used for removing the specified scoped variable from a particular
scope.
c:catch It is used for Catches any Throwable exceptions that occurs in the body.
c:if It is conditional tag used for testing the condition and display the body
content only if the expression evaluates is true.
c:choose, c:when, It is the simple conditional tag that includes its body content if the
c:otherwise evaluated condition is true. Choose like switch, when like case,
otherwise like default
c:forEach It is the basic iteration tag. It repeats the nested body content for fixed
number of times or over collection.
c:redirect It redirects the browser to a new URL and supports the context-relative
URLs.
Page 461
https://gits-sln.blogspot.com Durga sir Java Notes
<title>Tag Example</title>
</head>
<body>
<c:out value="${'Welcome to javaTpoint'}"/>
</body>
</html>
fn:endsWith() It is used to test if an input string ends with the specified suffix.
fn:trim() It removes the blank spaces from both the ends of a string.
fn:startsWith() It is used for checking whether the given string is started with a
particular string value.
fn:substring() It returns the subset of a string according to the given start and end
position.
Page 462
https://gits-sln.blogspot.com Durga sir Java Notes
items in a collection.
fn:replace() It replaces all the occurrence of a string with another string sequence.
</body>
</html>
fmt:timeZone It specifies a parsing action nested in its body or the time zone for any time
formatting.
fmt:formatNumber It is used to format the numerical value with specific format or precision.
fmt:bundle It is used for creating the ResourceBundle objects which will be used by their
tag body.
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.
fmt:setBundle It loads the resource bundle and stores it in a bundle configuration variable
or the named scoped variable.
Page 463
https://gits-sln.blogspot.com Durga sir Java Notes
fmt:formatDate It formats the time and/or date using the supplied pattern and styles.
To be continuing….
There are two ways to use the custom tag. They are given below:
https://www.javatpoint.com/crud-in-jsp
Hibernate
General meaning is sleep mode
Page 464
https://gits-sln.blogspot.com Durga sir Java Notes
It is work in a DAO (data access object) of model part of MVC architecture (model view
controller).
Sun microsystem--EJB--EJB team member Gavline develop---Hibernate
Without dependency of any web server we can run Hibernet application.
Feature-
1) Auto ddl support(create a automatic table no need to create a table)
2) HQL query support(data base independence query).
3) Cache support
4) Primary key generator support.
5) Data validation support(by annotation)
6) Exception free
7) ORM Support for RDBMS(provide a ISA and HasA relationship)
8) OGM(object graph mapping) for non sql
9) Search feature
10) Connection pool
Persistence
The process of storing and managing data for a long time is known as persistence. We cannot
think about any service set of project without using persistence.
Terminology used in persistence
I/O stream
It is used for only small scale application.
Serialization-the process of capturing object data and convert it into bits and byte is known as
serialization.---writing process occur
Deserialization- reading data from a file and construct into in object.-- reading process
occur
Page 465
https://gits-sln.blogspot.com Durga sir Java Notes
Hibernate frame work first let us see what the draw backs of JDBC are
Introduction of Hibernate:
Hibernate is a Java framework that simplifies the development of Java application to interact
with the database. It is an open source, lightweight, non-invasive, ORM (Object Relational
Mapping) tool, object based database software independent persistence logic.
Lightweight-
1. Small size
2. No need of heavy server and container for execution.
3. Can be used alone or with other java technologies and frameworks.
non-invasive- whatever classes developed is loosely coupled with hibernate API. i.e. need
not to implement or extends hibernate API.
ORM- provide abstraction layer on JDBC and simplifies persistence logic development.
Page 466
https://gits-sln.blogspot.com Durga sir Java Notes
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database
object based database software independent persistence logic
2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in hibernate
framework. There are two types of cache in hibernate framework first level cache and second
level cache. First level cache is enabled by default.
Page 467
https://gits-sln.blogspot.com Durga sir Java Notes
4. Persistence operation can be done directly on the object without converting them into the
simple value.
Hibernate Architecture
The Hibernate architecture is categorized in four layers.
o Java application layer
o Hibernate framework layer
o Backhand api layer
o Database layer
This is the high level architecture of Hibernate with mapping file and configuration file.
Page 468
https://gits-sln.blogspot.com Durga sir Java Notes
Session
A Session is used to get a physical connection with a database. The session objects should not
be kept open for a long time because they are not usually thread safe.
Transaction (optional)
A Transaction represents a unit of work with the database.
ConnectionProvider (optional)
It is a factory of JDBC connections. It abstracts the application from DriverManager or
DataSource.
TransactionFactory (optional)
It is a factory of Transaction.
Page 469
https://gits-sln.blogspot.com Durga sir Java Notes
3) Create the Persistent class or pojo class or setter and getter class
To create the persistent class, Right click on src - New - Class - specify the
class(Customer.java) with package name (e.g. com.java.myfirsthb) - finish .
package com.java.myfirsthb;
public class Customer {
private int Cid;
private String Cname;
private String email;
private Long phone;
private String city;
/*public Customer(int cid, String cname, String email, Long phone, String city) {
super();
Cid = cid;
Cname = cname;
this.email = email;
this.phone = phone;
this.city = city;
}*/
public Customer() {
super();
}
public int getCid() {
return Cid;
}
public void setCid(int cid) {
Cid = cid;
}
public String getCname() {
return Cname;
}
public void setCname(String cname) {
Cname = cname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
public String getCity() {
return city;
}
public void setCity(String city) {
Page 470
https://gits-sln.blogspot.com Durga sir Java Notes
this.city = city;
}
}
4) Create the mapping file for Persistent class
To create the mapping file, Right click on src - new - file - specify the file name (e.g.
customerm.hbm.xml) - ok. It must be outside the package.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- <hibernate-mapping> as the root element which contains all the <class> elements. -->
<hibernate-mapping package="com.java.myfirsthb">
<class name="Customer" table="customer"><!-- here name is class name and table is
database table name -->
<!--id tag element maps the unique ID attribute in class to the primary key of
the database table.The name attribute of the id element refers to the property in the class
and the column attribute refers to the column in the database table. The type attribute holds
the hibernate mapping type, this mapping types will convert from Java to SQL data type. -->
<id name = "Cid" type = "int" column = "cid">
<!-- generate tag element within the id element is used to generate the primary
key values automatically. -->
<generator class="increment"/>
</id>
<!-- property tag element is used to map a Java class property to a column in the
database table.and name,column,type attribute same as above comment -->
<property name = "Cname" column = "cName" type = "string"/>
<property name = "email" column = "email" type = "string"/>
<property name = "phone" column = "phone" type = "long"/>
<property name = "city" column = "city" type = "string"/>
</class>
</hibernate-mapping>
5) Create the Configuration file
To create the configuration file, right click on src - new - file. Now specify the configuration file
name e.g. hibernate.cfg.xml.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- specify database driver -->
<property name =
"hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name =
"hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
<!-- true value shows SQL query that is generated by hibrnate -->
<property name="show_sql">true</property>
Page 471
https://gits-sln.blogspot.com Durga sir Java Notes
</session-factory>
</hibernate-configuration>
Demo.java
package com.java.myfirsthb;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Demo {
public static void main( String[] args )
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
Customer c= new Customer();
c.setCname("Suraj");
c.setCity("Bangalore");
c.setEmail("[email protected]");
c.setPhone(123456789L);
c.setCity("Banglor");
session.save(c);
t.commit();
System.out.println("successfully saved");
session.close();
}
}
HibernateUtil.java
package com.java.myfirsthb;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
Page 472
https://gits-sln.blogspot.com Durga sir Java Notes
To run the hibernate application, right click on the Demo.java class - Run As - Java
Application.
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
Dialect class is java class, which contains code to map between java language data type
database data type.
All Dialect classes extend the Dialect abstract class.
Dialect is used to convert HQL statements to data base specific statements.
RDBMS Dialect
Page 473
https://gits-sln.blogspot.com Durga sir Java Notes
Oracle9i org.hibernate.dialect.Oracle9iDialect
Oracle10g org.hibernate.dialect.Oracle10gDialect
MySQL org.hibernate.dialect.MySQLDialect
Page 474
https://gits-sln.blogspot.com Durga sir Java Notes
Page 475
https://gits-sln.blogspot.com Durga sir Java Notes
Page 476