67% found this document useful (3 votes)
2K views477 pages

Java Ebook by Durga Sir

The document discusses Java concepts including the JDK, JRE, JVM, classloaders, memory areas, and differences between C++ and Java. It notes that the JDK contains the JRE and development tools, the JRE contains libraries and files for runtime, and the JVM is an abstract machine that executes bytecode. It lists the five memory areas allocated by the JVM and the three built-in classloaders. Key differences between C++ and Java include Java being platform independent, not supporting multiple inheritance or pointers, and everything deriving from Object.

Uploaded by

Prabhakar Pathak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
67% found this document useful (3 votes)
2K views477 pages

Java Ebook by Durga Sir

The document discusses Java concepts including the JDK, JRE, JVM, classloaders, memory areas, and differences between C++ and Java. It notes that the JDK contains the JRE and development tools, the JRE contains libraries and files for runtime, and the JVM is an abstract machine that executes bytecode. It lists the five memory areas allocated by the JVM and the three built-in classloaders. Key differences between C++ and Java include Java being platform independent, not supporting multiple inheritance or pointers, and everything deriving from Object.

Uploaded by

Prabhakar Pathak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 477

Durga sir Java Notes https://gits-sln.blogspot.

com

GARIMA INFOTECH SOLUTION

Java E-Book
Durga Software Solution
By- Durga Sir, Ameerpet Hyderabad

All the content collected and compose by -Garima infotech Solution


https://gits-sln.blogspot.com Durga sir Java Notes

Point to be remember-

 Stealth ProjectGreen ProjectOakJava


 First java based web browser-Hot Java
 Unused term i.e. memory removed by garbage collector of JVM.
 Garbage Collector used many type of algorithm to removed unused term but most common
algorithm is “mark & Sweep”.
 Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

JDK-JDK is an acronym for Java Development Kit. It physically exists.


It contains JRE (set of libraries + JVM) + development tools


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.

How many types of memory areas are allocated by JVM?-5


1. Class(Method) Area-
Area stores per-class structures such as the runtime constant pool, field and method data,
the code for methods.
2. Heap-
It is the runtime data area in which objects are allocated.
3. Stack-
Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.
4. Program Counter Register

Page 3
https://gits-sln.blogspot.com Durga sir Java Notes

Contains the address of the JVM instruction currently being executed.


5. Native method stacks−
Similar to Java stack, native methods are executed on the Native method stacks.
Execution Engine-It contain -
1) A virtual processor
2) Interpreter
3) JIT compiler

5 feature for any object oriented programming language –


1. Class and object
2. Encapsulation
3. Abstraction
4. Inheritance
5. Polymorphism
C++ vs Java
There are many differences and similarities between the C++ programming language and Java. A list
of top differences between C++ and Java are given below:
Comparison C++ Java
Index
Platform- C++ is platform-dependent. Java is platform-independent.
independent
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.
Design Goal C++ was designed for systems Java was designed and created as an
and applications programming. interpreter for printing systems but later
It was an extension of C extended as a support network
programming language. computing. It was designed with a goal
of being easy to use and accessible to a
broader audience.
Goto C++ supports Java doesn't support the goto statement.
the goto statement.
Multiple inheritance C++ supports multiple Java doesn't support multiple
inheritance. inheritance through class. It can be
achieved by interfaces in java.
Operator C++ supports operator overloading. Java doesn't support operator
Overloading overloading.
Pointers C++ supports pointers. You can Java supports pointer internally.
write pointer program in C++. However, you can't write the pointer
program in java. It means java has

Page 4
https://gits-sln.blogspot.com Durga sir Java Notes

restricted pointer support in java.


Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter both.
Interpreter compiled and run using the Java source code is converted into
compiler which converts source bytecode at compilation time. The
code into machine code so, C++ interpreter executes this bytecode at
is platform dependent. runtime and produces output. Java is
interpreted that is why it is platform
independent.
Call by Value and C++ supports both call by value Java supports call by value only. There is
Call by reference and call by reference. no call by reference in java.
Structure and Union C++ supports structures and Java doesn't support structures and
unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.
Documentation C++ doesn't support Java supports documentation comment
comment documentation comment. (/** ... */) to create documentation for
java source code.
Virtual Keyword C++ supports virtual keyword so Java has no virtual keyword. We can
that we can decide whether or override all non-static methods by
not override a function. default. In other words, non-static
methods are virtual by default.
unsigned right shift C++ doesn't support >>> Java supports unsigned right shift >>>
>>> operator. operator that fills zero at the top for the
negative numbers. For positive numbers,
it works same like >> operator.
Inheritance Tree C++ creates a new inheritance Java uses a single inheritance tree always
tree always. because all classes are the child of Object
class in java. The object class is the root
of the inheritance tree in java.
Hardware C++ is nearer to hardware. Java is not so interactive with hardware.
Object-oriented C++ is an object-oriented Java is also an object-oriented language.
language. However, in C However, everything (except
language, single root hierarchy fundamental types) is an object in Java. It
is not possible. is a single root hierarchy as everything
gets derived from java.lang.Object.
Note
 Java doesn't support default arguments like C++.
 Java does not support header files like C++. Java uses the import keyword to include
different classes and methods.

Page 5
https://gits-sln.blogspot.com Durga sir Java Notes

Valid java main method signature--


·public static void main(String[] args)
·public static void main(String []args)
·public static void main(String args[])
·public static void main(String... args)
·static public void main(String[] args)
·public static final void main(String[] args)
·final public static void main(String[] args)
·final strictfp public static void main(String[] args)
static final synchronized strictfp public void main(String …pp)
if a class contain main() method not present
class Test
{
………
}
Javac Test.java
Java Test
RE:nosuchmethodError:main
That means compile successfully but given runtime error
###
public static void main(String[] args)
public to call by the JVM anywhere
static without existing object also JVM has to call this method
void  main() method would not return anything to JVM
main  this is the name which is configure inside JVM
String[] args  command line argument

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

To compile: javac Hard.java

To execute: java Simple


Q-Can you have multiple classes in a java source file?-yes

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.
There are four types of Java access modifiers:

Access Modifier Within within outside package outside


class package by subclass only package

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.

Visibility Private Default Protected Public

Within the same class Y Y Y Y

Page 7
https://gits-sln.blogspot.com Durga sir Java Notes

From child class of same package N Y Y Y

From non-child class of same N Y Y Y


package

From child classes of outside N N Y[We should use child Y


package reference only]

From non-child classes of outside N N N Y


package

 The most restricted modifiers is—private


 The most access able modifiers is—public
 Recommented modifiers for data member or variable—private
 Recommented modifiers for method(means service) is--public
Private <default<protected<public
Below Table summarizes the access modifiers

Modifie Top Level Inne Constructo metho Data/ Object Child


r Class r r d Variabl Creatio class
Class es n

Public Yes Yes Yes Yes Yes

Protecte Yes Yes Yes Yes


d

Default Yes Yes Yes Yes Yes

Private Yes Yes Yes Yes

Static Yes Yes(blo Yes


ck)

Final Yes Yes Yes Yes NO

Abstract Yes Yes Yes No NO Yes

strictfp Yes Yes Yes No

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.

Total reserve word (53)

Keyword (50) Reserved literal (3)


true
Used (48) Unused (2) Page 10
false
https://gits-sln.blogspot.com Durga sir Java Notes

Flow control keyword-11


If, else, switch, case, default, while, do, for, foreach, break, continue.
Access Modifiers Keyword-11
Public, private, protected, static, final, abstract, synchronized, native, strictfp, transicant, volatile.
Exception handling Keyword-6
Try, catch, finally, throw, throws, assert.
Class related Keyword-6
Class, interface, extends, implements, package, impact.
Object related Keyword-4
New, instanceof, super, this.
Return type Keyword
Void.
Unused keyword-2
goto, const =>banned these keyword in java.
Literal type reserved word-3
true, false => value for Boolean data type
null => default value for object reference
enum keyword
Define a group of name constant.

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 Variable can be accessed only by creating objects.


 The value of instance variable is varies from object to object.
 For every object a separate copy of instance object is created.
 It is not required to perform initialization of instance variable because JVM provide a
default value when we run program.
 Not a thread safe.
3.static variable or class variable-
 declared using the static keyword within a class outside any method constructor or block.
 we can only have one copy of a static variable per class irrespective of how many objects
we create.
 Static variables are created at the start of program execution and destroyed automatically
when execution ends.
 Its default value is 0
 We can access static variable by using 1-class_name.static_variable 2-
class_object.static_variable
 Not a thread safe.
Note- If we are declaring a variable without using any modifiers then they will be treated as
a default by default but this rules is applicable only for instance and class variable not for
local variable.

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

int x=10.5;  int x=10;

boolean y=0;  Boolean y=false;

So java is strongly type. And type capability check by the compiler.

 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

 byte b=128; compile time error


possible loss of precision
found: int
required: byte
 byte b=true; CE: incompatible type
found: Boolean
required: byte

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.

Data Type Default value


Byte 0
Short 0
Int 0
long 0
float 0.0
double 0.0
boolean False
char 0 (represent a space character)

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;
intdatatype/ keyword
x variable/ identifiers
10 constant value/ literal

Integer type literal: By default any integer literal is int type.


Page 14
https://gits-sln.blogspot.com Durga sir Java Notes

1. decimal literal (base 10) int x=10;


2. octal literal (base 8) int x=010;(0 is used as a prefix)
3. Hexadecimal literal (base 16) int x=0x10;(0x or 0X used as a prefix and number 0 to 9 and
a/A to z/Z).
 Int x=0768; CE: integer no too large
 Int x=0xface;
 Int x=oxBeeF;
 Int x=oxBeer; CE: semicolon error
 int x=10;
 long x=10L;
 int x=10L; CE: possible loss of precision found: long required : int
 byte b=128; CE: possible loss of precision found: int required : byte
 There is no any direct way to specifying byte and short literal as octal and hexadecimal.

Floating point literal: every float literal is double by default.


float f=12.37; compile time error show because it is treat as a double type
floar f=12.37F; (we should be used a prefix as f or F)
double d=12.37;
double d=0123.456; (it is a double literal but not octal literal)
double d=0x123.456; CE: mal format floating point literal.
double d=0786; CE: integer no to large
double d=0xface;
double d=0786.0;
double d=0xFace.0; CE

Boolean type literal:


boolean b=true;
boolean b=0; CE: incompatible type

char type literal:


single character within a single code.
Any Unicode no value of any character without any single code.
char c=a; CE:
char c=”a”; CE:
char c=’a’;
char c=’ab’; CE:
char c=65;
char c=065;
char c=0x65;
char c=’\u0061’; sop(c);  a

Page 15
https://gits-sln.blogspot.com Durga sir Java Notes

Why char uses 2 byte in java and what is \u0000 ?


It is because java uses Unicode system not ASCII code system.
lowest value:\u0000
highest value:\uFFFF
char c=’\n’;
we can also use some escape character such as \n,\t,\r,\b,\f, \’, \”,\\

string type literal:


String str=”---”;

Binary type literal:


Int x=0B111;(0B is used as a prefix)

Using of underscore symbol In numeric literal


double d=123456.789;
double d=1_23_456.7_8_9;
double d=1_ _23_ _456.7_8_9;
double d=_1_23_ _456.7_8_9; CE

integer data type: byte, short, int, log, char


float data type: float, double

 Memory representation of integer data type and float data type is completely different.
float f=10l;
Sop(f); 10.0

Java Switch Statement


The switch statement works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.

Command line argument


 The argument which are passing from command prompt.

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

Ideal programming phenomena in java


A calculator based program for adding two number
class A
{
public int m(int x, int y)
{
return x+y;
}
}
As an expert programmer the above program we can write in this way
package com.java.test;
public class Calculator
{
public static int add(int num1, int num2)
{
return num1+num2;
}
}

Class name

Page 18
https://gits-sln.blogspot.com Durga sir Java Notes

 Usually class name are noun.


 Start naming by using upper case character if name contain multiple word then every
word start with capital character.
Example- MyClass
Interface name
Interface name is same as class name.
Example- RunnableInterface
Method name
It is start with small letter if its combination contain more than one word then
Other word start with capital letter.
Example- getName(), setName()
Variable name
Variable name can create same way as method name.
Example-name,mobileNumber
Constant name
Example- PI, MAX_VALUE

Java Bean coding statement


 Java bean is a class.
 It contain private method.
 It contain get and set method.
public class StudentBean
{
private String name;
public void setName(String Name)
{
this.name=name;
}
public String getName()
{
return name;
}
}

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

Final int x=10; Boolean b=true;


X++; CE b++; CE
Sop(x); Sop(b);
Double d=10.5;
d++;
sop(d);-11.5

Arithmetic operator
If we are applying any arithmetic operation between two variable then result can be
found by

Max(int, type of A, type of B)

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[];

Instantiation of an Array in Java

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[];

int[] a,b; a->1D,b->1D


int[] a[],b; a->2D,b->1D
int[] a[],b[]; a->2D,b->2D
int[] []a,b; a->2D,b->2D
int[] []a,b[]; a->2D,b->3D
int[] []a,[]b; CE:

Array is an object in java.


Int[] a=new int[3];
Sop(a.getClass().getName());  [I
if array is 2D  [ [ I

Note: Every array type corresponding class are available under these class part of java
language not available for programmer level.

Array Type Corresponding class name


int[] [I

Page 21
https://gits-sln.blogspot.com Durga sir Java Notes

int[][] [ [I
double[] [ D
short[] [ S
byte[] [ B
boolean[] [ Z

Note:- allowed data type in array byte, short, int, char


Example:
 int[] x=new int[ ‘a’ ];
 byte b=10;
int[] x=new int[b];
 int[] x=new int[3];
sop(x);  [ I @ hash value in hexadecimal value
sop(x[0]);  0
 int[][] x=new int[2][3];
sop(x); [ [ I @ hashvalue
sop(x[0]); [ I @ hashvalue
sop(x[0][0]); 0
 int[][] x=new int[2][];
sop(x); [ [ I @ hashvlaue
sop(x[0]); null
sop(x[0][0]); RE: null point exception
 Array declaration, creation and initialization in a single line
int[] x={10,20};//1D array
int[][] x={{10,20},{30,40,50}};//2D array
 Array support length variable not length() method sop(x.length);
 String[] s={“A”,”AA”,”AAA”};
Sop(s.length); 3
Sop(s[0].length()); 1

int x=10; int[] x={10,20,30};
or or
int x; int[] x;
x=10; x={10,20,30};// CE:

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

Number Type array: byte, short, int, long, float, double.


Number[] n=new Number[10];
n[0]=new Integer(10);
n[1]=new Double(10.5);
n[2]=new String(“Ram”); CE:

Runnable type array:

Page 23
https://gits-sln.blogspot.com Durga sir Java Notes

Runnable[] r=new Runnable[10];


Here we create a runnable object array not a runnable object.
r[0]=new Thread();
r[1]=new String(“Ram”); CE:

Array type Allowed element type


Primitive array Any type which can be implicitly promated to declared type
Object type array Either declared type or its child class object
Abstract class type array It’s child class object.
Interface type array It’s implementation class object are allowed.

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

For static level


Static int[] x;
Sop(x);//-null
Sop(s[0]);//-RE:NPE
If we taken int[] x=new int[3];
Sop(x);//-[I@hashcode
Sop(x[0])//-0

For local level


Int[] x;
Sop(x);//CE:
Sop(x[0]);//CE:
If we taken int[] x=new int[3];
Sop(x);//-[I@hashcode

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

Java For Loop


There are three types of for loops in java.
1.Simple For Loop-
for(initialization;condition;incr/decr){
//statement or code to be executed
}
2.For-each or Enhanced For Loop
used to traverse array or collection in java.
for(Data_Type var_name : array_name){
//code to be executed
}
Example-
int[] numbers = {8, 2, 6, 4, 3};
int sum = 0;
for (int number : numbers) { // for each int number in int[] numbers
sum += number;
}
Page 25
https://gits-sln.blogspot.com Durga sir Java Notes

System.out.println("The sum is " + sum);


3.Labeled For Loop
we use label before the for loop. It is useful if we have nested for loop so that we can
break/continue specific for loop. Usually, break and continue keywords breaks/continues the
innermost for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Example:
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
11
12
13
21

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{

String name = "";

// Instance method to be called within the same class or


// from a another class defined in the same package
// or in different package.
public void geek(String name){

this.name = name;
}
}

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

// create an instance of the class.


Foo ob = new Foo();

// calling an instance method in the class 'Foo'.


ob.geek("GeeksforGeeks");
System.out.println(ob.name);
}
}
Output :

GeeksforGeeks

2-class method/ static method:-


 Static method(s) are associated to the class in which they reside i.e. they can be called even
without creating an instance of the class i.e ClassName.methodName(args).
 They are designed with aim to be shared among all Objects created from the same class.
 Static methods cannot be overridden. But can be overloaded since they are resolved
using static binding by compiler at compile time.
// Example to illustrate Accessing the Static method(s) of the class.
import java.io.*;

class Geek{

public static String geekName = "";

public static void geek(String name){

geekName = name;
}

Page 27
https://gits-sln.blogspot.com Durga sir Java Notes

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

// Accessing the static method geek() and


// field by class name itself.
Geek.geek("vaibhav");
System.out.println(Geek.geekName);

// Accessing the static method geek() by using Object's reference.


Geek obj = new Geek();
obj.geek("mohit");
System.out.println(obj.geekName);

}
}
Output:
vaibhav
mohit

package com.java.test;

public class instance_m_vs_class_m {

void display(int a,int b)//instance method


{
System.out.println("hello "+(a+b));
}
public static void display1(int a,int b)//class method
{
System.out.println("hello "+(a+b));
}
public static void main(String[] args) {
// TODO Auto-generated method stub

instance_m_vs_class_m in=new instance_m_vs_class_m();


in.display(2,3);//instance method calling only by object
instance_m_vs_class_m.display1(4, 5);//class method calling by object and class name
in.display1(6,9);
}

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

When to use static methods ??


 When you have code that can be shared across all instances of the same class, put
that portion of code into static method.
 They are basically used to access static field(s) of the class.
Instance method vs Static method
 Instance method can access the instance methods and instance variables directly.
 Instance method can access static variables and static methods directly.
 Static methods can access the static variables and static methods directly.
 Static methods can’t access instance methods and instance variables directly. They
must use reference to object. And static method can’t use this keyword as there is
no instance for ‘this’ to refer to.

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.

public class AutoBoxingTest {

public static void main(String args[]) {

int num = 10; // int primitive

Integer obj = Integer.valueOf(num); // creating a wrapper class object

System.out.println(num + " " + obj);

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

public class UnboxingTest {

public static void main(String args[]) {

Integer obj = new Integer(10); // Creating Wrapper class object

int num = obj.intValue(); // Converting the wrapper object to primitive datatype

System.out.println(num + " " + obj);

Output

10 10

public class rnd {

int display(int a,int b)//instance method


{
return(a+b);

}
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

Variable Arguments (Varargs) in Java


Varargs -variable-length arguments could be handled two ways. One using overloaded
method(one for each) and another put the arguments into an array, and then pass this array to the
method. Both of them are potentially error-prone and require more code. The varargs feature offers a
simpler, better option.
Syntax of varargs :
A variable-length argument is specified by three periods(…). For Example,
public static void fun(int ... a)
{
// method body
}
This syntax tells the compiler that fun( ) can be called with zero or more arguments.
// Java program to demonstrate varargs
class Test1
{
// A method that takes variable number of integer
// arguments.
static void fun(int ...a)
{
System.out.println("Number of arguments: " + a.length);

// using for each loop to display contents of a


for (int i: a)
System.out.print(i + " ");
System.out.println();
}

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

// using for each loop to display contents of a


for (int i: a)
System.out.print(i + " ");

System.out.println();
}

public static void main(String args[])


{
// Calling fun2() with different parameter
fun2("GeeksforGeeks", 100, 200);
fun2("CSPortal", 1, 2, 3, 4, 5);
fun2("forGeeks");
}
}
String: GeeksforGeeks
Number of arguments is: 2
100 200
String: CSportal
Number of arguments is: 5
12345
String: forGeeks
Number of arguments is: 0
class Test2
{
Public static void m(int …x)
{
System.out.println("varargs method");
}
Public static void m(int x)
{
System.out.println("General method");
}

Page 32
https://gits-sln.blogspot.com Durga sir Java Notes

public static void main(String args[])


{
m();//varargs method call
m(10,20); //varargs method call
m(10); //general method call(but support both)
}
}
Note- m(int[] x ) that means 1D arrary method can be replaced by varargs method m(int
…x) but varargs can’t be replaced by 1D array.

Java OOPs Concepts


 Simula is considered the first object-oriented programming language.
 The programming paradigm where everything is represented as an object is known as a
truly object-oriented programming language.
 Smalltalk is considered the first truly object-oriented programming language.
Object
 instance of a class
 An object contains an address and takes up some space in memory.
 It’s physical or logical entity.
 All these objects have a state (i.e. variable) and a behaviour (i.e. method).
 If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
 The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
Class
 A class is a user defined blueprint or prototype or templete from which objects are created.
 Collection of objects is called class.
 Class doesn't consume any space.
 It is a logical entity.
 We can have multiple classes in different Java files or single Java file. we create classes and
use it from another class
No. Object Class

1) Object is an instance of a class. Class is a blueprint or template from


which objects are created.

2) Object is a real world entity such as pen, Class is a group of similar objects.
laptop, mobile, bed, keyboard, mouse, chair
etc.

3) Object is a physical entity. Class is a logical entity.

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

5) Object is created many times as per Class is declared once.


requirement.

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.

3 Ways to initialize object


There are 3 ways to initialize object in Java.
1. By reference variable-
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}

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

How many Ways to Create an Object in Java

There are five different ways to create an object in Java:


1. Java new Operator-
A new operator is also followed by a call to constructor which initializes the new object.
class_name object_name = new class_name();
2. Java Class.newInstance() method-
class_name object_name=class_name.class.newInstance();
3. Java newInstance() method of constructor-
Constructor<class_name> object = class_name.class.getConstructor();
Class_name obj= object.newInstance();
4. Java Object.clone() method-
The Cloneable interface must be implement while using clone() method.(class name must
be implements by Cloneable class)
 saves the extra processing task for creating the exact copy of an object.
 If we perform it by using the new keyword, it will take a lot of processing time to be
performed that is why we use object cloning.
class_name obj4=new class_name();
Class_name obj5=(class_name)obj4.clone();
5. Java Object Serialization and Deserialization-
6. Anonymous object-
Anonymous simply means nameless. An object which has no reference is known as an
anonymous object. It can be used at the time of object creation only.
new class_name().method_name() or variable_name;//calling method
with anonymous object
Example: System.out.println(new Object_creation_way().str);

Page 35
https://gits-sln.blogspot.com Durga sir Java Notes

7. Creating multiple objects by one type only-


class_name obj1=new class_name(), obj2=new class_name();

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

Constructor Overloading in Java?


 Overloading means more than one methods contain different parameters list.

Page 36
https://gits-sln.blogspot.com Durga sir Java Notes

Constructor vs method
Java Constructor Java Method

A constructor is used to initialize the state of A method is used to expose the


an object. behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

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.

Java Copy Constructor


There is no copy constructor in Java but we can use copy constructor by following way
1-By constructor
I. Copy value by using constructor
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

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

public static void main(String args[]){


Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}

2-By assigning the values of one object into another


3-By clone() method of Object class

Does constructor return any value?


Yes, it is the current class instance (You cannot use return type yet it returns a value).

Is there Constructor class in Java? Yes.


What is the purpose of Constructor class?
Java provides a Constructor class which can be used to get the internal information of a
constructor in the class. It is found in the java.lang.reflect package.

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

child object vs parent constructor


Whenever we are creating child class object automatically parent constructor will be executed
to perform initialization further instance variable which are inheriting from parent.
So parent constructor executing purpose for child class only.

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.

Java static keyword


It is used for memory management mainly.
The static can be:
1. Variable (also known as a class variable)
 used to refer to the common property (share) of all objects (which is not unique for each
object)
 gets memory only once in the class area at the time of class loading. (i.e., it saves
memory).
 Static member properties shared to all object.
किसी क्लास िे जितने भी डाटा में म्बर होते है उनिे ललए मेमोरी िा अलाट्में ट उतनी बार होगा जितनी
बार नया ऑब्िेक्ट बनाया िाएगा।यदि िोई मेम्बर ऐसा है कि उसिी वैलू हर बार एि समान रहती है तब
ऐसे मेम्बर िे ललए static िा प्रयोग िरते है ।जिसिे िारण उसिे ललए िेवल एि बार ही मेमोरी स्पेस
कियेट होता है ।
class test
{
static int x=10;
int y=20;
public static void main(String args[])
{
test t1=new test();
t1.x=888;
t1.y=999;
test t2=new test();
system.out.println(t2.x+” ”+t2.y);
}
}
Output-888 20
X=10
888

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

2. Method (also known as a class method)


 call static method by using class name Class_Name.static_method(); or by using object.
Class_Name obj=new Class_Name();
obj. static_method();
 A static method can access static data member and can change the value of it.
 this and super cannot be used in static context.
 Overloading and Inheritance concept is applicable but not applicable overriding but
intends of overriding method hiding concept is applicable.
Why is the Java main method static?
Ans) It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the problem of extra
memory allocation.

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:

static block is invoked

4. Nested class
Inner class can be static but outer class or top class can’t be static.

this keyword in java


 ‘this’ is a reference variable that refers to the current object.
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
this.instance_variable=instance_variable
If parameters (formal arguments) and instance variables are same then this keywords differ to
them.
1. class Student{ 1. class Student{
2. int rollno; 2. int rollno;
3. String name; 3. String name;
4. float fee; 4. float fee;
5. Student(int rollno,String name,float fee){ 5. Student(int rollno,String name,float fee){
6. rollno=rollno; 6. this.rollno=rollno;
7. name=name; 7. this.name=name;
8. fee=fee; 8. this.fee=fee;
9. } 9. }
In this way create a problem By using this keywords resolve the problem

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

3. this() can be used to invoke current class constructor.


Call the default constructor from parameterized constructor

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:

111 ankit java null


112 sumit java 6000

6. this can be passed as an argument in the method call.


It is mainly used in the event handling.
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}

Page 46
https://gits-sln.blogspot.com Durga sir Java Notes

7. this can be passed as argument in the constructor call.


It is useful if we have to use one object in multiple classes.
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

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

//Method that returns current class instance


Test get()
{
return this;
}

//Displaying value of variables a and b


void display()
{
System.out.println("a = " + a + " b = " + b);
}

public static void main(String[] args)

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

The relationship between the two classes is Programmer IS-A


Employee. Programmer is the subclass and Employee is the superclass.
Why use inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

Note: Multiple inheritance is not supported in java through class.

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:

Student Has-A Address (Has-a relationship between student and address)


College Has-A Address (Has-a relationship between college and address)
Staff Has-A Address (Has-a relationship between staff and address)
Hence we can improve code re-usability by using Aggregation relationship.

So if I have to write this in a program, I would do it like this:

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.

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading. Overloading is related to compile-time (or static) polymorphism.

Different ways to overload the method


There are two ways to overload the method in java

Page 50
https://gits-sln.blogspot.com Durga sir Java Notes

1. By changing number of arguments


2. By changing the data type

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.

Can we overload java main() method?


Yes, by method overloading. But JVM calls main() method which receives string array as
arguments only.
class test
{
public static void main(String[] args)
{
sop(“string[]”);
}
public static void main(int[] args)//method overloading of main method
{
sop(“int[]”);
}

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

public static void main(String args[]){


OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}
Output:Compile Time Error

Method Overloading in Java


If subclass (child class) has the same method as declared in the parent class. It is used for runtime
polymorphism.
Rules for Java Method Overriding

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

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Q-Can we override static method? A static method cannot be overridden.

Page 52
https://gits-sln.blogspot.com Durga sir Java Notes

Covariant Return Type


#################################################3

Super Keyword in Java


It is used to refer immediate parent class object.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
It is used if parent class and child class have same fields.
/* Base class vehicle */
class Vehicle
{
int maxSpeed = 120;
}

/* sub class Car extending vehicle */


class Car extends Vehicle
{
int maxSpeed = 180;

void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed); //invoke parent class instance
variable
}
}

2. super can be used to invoke parent class method.


It should be used if subclass contains the same method as parent class.

/* Base class Person */


class Person
{
void message()
{
System.out.println("This is person class");
}
}

/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}

// Note that display() is only in Student class


void display()
{
// will invoke or call current class message() method
message();

// will invoke or call parent class message() method

Page 53
https://gits-sln.blogspot.com Durga sir Java Notes

super.message();
}
}

3. super() can be used to invoke immediate parent class constructor.


/* superclass Person */
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}

/* subclass Student extending the Person class */


class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();

System.out.println("Student class Constructor");


}
}
Note: super() is added in each class constructor automatically by compiler if there is no super() or
this().
That means super class constructor invoke first in inheritance if we creating subclass object.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created

super example: real use


class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}

Page 54
https://gits-sln.blogspot.com Durga sir Java Notes

class Emp extends Person{


float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}
Output:
1 ankit 45000

Instance initializer block


Instance Initialization Blocks or IIB are used to initialize instance variables. IIBs are
executed before constructors. They run each time when object of the class is created.
 Initialization blocks are executed whenever the class is initialized and before
constructors are invoked.
 They are typically placed above the constructors within braces.
 It is not at all necessary to include them in your classes.
// Java program to illustrate
// Instance Initialization Block
class GfG
{
// Instance Initialization Block
{
System.out.println("IIB block");
}

// Constructor of GfG class


GfG()
{
System.out.println("Constructor Called");
}
public static void main(String[] args)
{
GfG a = new GfG();
}
}
Output :
IIB block
Constructor Called

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

Rules for instance initializer block :


There are mainly three rules for the instance initializer block. They are as follows:

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

{System.out.println("instance initializer block is invoked");}

public static void main(String args[]){


B2 b=new B2();
}
}
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked

Final Keyword In Java


final is a non-access modifier applicable only to a variable, a method or a class.
 We can achieved a security and uniqueness implementation for all by using final keyword.
 By using final keyword we are missing oops implementation such as inheritance (because of
final class) and polymorphism (because of final method).
 If in a program there is no any specific requirement then we ignore its uses.
 Following are different contexts where final is used.

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.

public class FinalTest {


final int a=2;//
final int b;
static final double PI=3.14;
static final double area;
/*
//final uninitialized variable initialize
{
b=3;
}
*/
//final uninitialized variable initialize
FinalTest()
{
b=3;//sice b is a final instance variable so value assignment is required.
//if b is only instance variable then value assignment is not required because JVM
//provide default value of variable.
}
//static final uninitialized variable initialize
static
{
area=2.5;
}
void Display()
{

System.out.println(a);
System.out.println(b);
System.out.println(PI);
System.out.println(area);
}

public static void main(String[] args) {

FinalTest ft=new FinalTest();


ft.Display();
}

}
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

 If the static variable declared as a final then compulsory it should be initialized a)


at the time of declaration b) inside static block. If we are trying another way of
initialization then we get compile time error.
2. Final Method-
 If we declare any method in a parent class then by default it is available to the
child through inheritance. If the child is not satisfied with parent method
implementation then child is allowed to redefined that method based on its
requirement this process is called overriding.
 If the parent class method is declared as a final then we can’t override that
method in a child class because its implementation is final.
class p
{
public void property()
{
System.out.println("cash+gold+land");
}
public final void marry()
{
System.out.println("Subhlaximi");
}
}
class p extends p
{
public void marry()
{
System.out.println("Sobha or Rashmi");
}
}
3. Final Class-
 We can’t extends or create a child class that means inheritance is not possible.
 Every method inside a final class by default final but every variable present inside
in the final class need not be final.
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.

class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}

Q) Can we declare a constructor final?


No, because constructor is never inherited.

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

Runtime Polymorphism-method overriding==By using Upcasting ( variable of



Parent class refers to the object of Child class)
That’s means it is follow dynamic binding.
class A{}
class B extends A{}

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

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}

Output:

running safely with 60km.


A method is overridden, not the data members, so runtime polymorphism can't be achieved by data
members.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;

public static void main(String args[]){


Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}

Output:

90

Page 59
https://gits-sln.blogspot.com Durga sir Java Notes

Static Binding and Dynamic Binding


Connecting a method call to the method body is known as binding. There are two types of
binding

1. Static Binding (also known as Early Binding)-


When type of the object is determined at compiled time
 If there is any private, final or static method in a class, there is static binding.
 Used in method overloading cases (compile time polymorphism).

class Dog{
private void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Dog d1=new Dog();
d1.eat();
}
}

2. Dynamic Binding (also known as Late Binding)-


When type of the object is determined at run-time
 Used in method overriding cases (run time polymorphism).
class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}
Output: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.

(Object reference variable ) instanceof (class/interface type)

class Animal{}
class Dog1 extends Animal{//Dog inherits Animal

Page 60
https://gits-sln.blogspot.com Durga sir Java Notes

public static void main(String args[]){


Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
}
}

Downcasting with java instanceof operator


When Subclass type refers to the object of Parent class, it is known as downcasting.
###################

Abstract class in Java


Abstraction is a process of hiding the implementation details and showing only functionality to
the user. There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)-a class which is having a partial implementation not complete
implementation so it is not allowed to create an object.
2. Interface (100%)

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.

abstract class Bike{


int i=4;
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed "+ i);}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class AbstractTest{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

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

 Abstraction restrict some oops rules like Inheritance and Polymorphism.


The abstract class can also be used to provide some implementation of the interface. In such case, the end
user may not be forced to override all the methods of the interface.
Need of abstract class constructor

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

class A6 implements printable{


public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Output:

Hello

A class can extends another class and/ can implement one and more than one interface.

// Java program to demonstrate that a class can


// implement multiple interfaces
import java.io.*;
interface intfA
{
void m1();
}

interface intfB
{
void m2();
}

// class implements both interfaces


// and provides implementation to the method.
class sample implements intfA, intfB
{
@Override
public void m1()
{
System.out.println("Welcome: inside the method m1");
}

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

// calling the method implemented


// within the class.
ob1.m1();
ob1.m2();
}
}
Output;
Welcome: inside the method m1
Welcome: inside the method m2

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

public static void main(String args[]){


A7 obj = new A7();
obj.print();

Page 66
https://gits-sln.blogspot.com Durga sir Java Notes

obj.show();
}
}
Output:Hello
Welcome

Q) Multiple inheritance is not supported through class in java, but it is possible


by an interface,

Interface inheritance : An Interface can extend other interface.

// Java program to demonstrate inheritance in


// interfaces.
import java.io.*;
interface intfA
{
void geekName();
}

interface intfB extends intfA


{
void geekInstitute();
}

// class implements both interfaces and provides


// implementation to the method.
class sample implements intfB
{
@Override
public void geekName()
{
System.out.println("Rohit");
}

@Override
public void geekInstitute()
{
System.out.println("JIIT");
}

public static void main (String[] args)


{

Page 67
https://gits-sln.blogspot.com Durga sir Java Notes

sample ob1 = new sample();

// calling the method implemented


// within the class.
ob1.geekName();
ob1.geekInstitute();
}
}
Output:
Rohit
JIIT

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.

//How Serializable interface is written?


public interface Serializable{
}

Abstract class vs Interface


Abstract class Interface

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.

2) Abstract class doesn't Interface supports multiple inheritance.


support multiple
inheritance.

3) Abstract class can have Interface has only static and final variables.
final, non-final, static and
non-static variables.

4) Abstract class can provide Interface can't provide the implementation of


the implementation of abstract class.
interface.

5) The abstract keyword is The interface keyword is used to declare interface.


used to declare abstract class.

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.

7) An abstract class can be An interface can be implemented using keyword


extended using keyword "implements".
"extends".

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

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods


interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}

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

//Creating a test class that calls the methods of A interface


class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();

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

With having constructor in parent class (no more code redundancy)


In the below code we are using a constructor with some parameter in a parent class and
in child class all parent class parameter want to use then a simple way we can call all
parent class parameter by using super method that follow all parent parameter.

The main purpose of constructor is to perform initialization for instance variable.

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:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value of
a private variable

The Java Bean class is the example of a fully encapsulated class.

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

String vs StringBuffer vs StringBuilder


1. String (immutable, thread safe)
 String is immutable (once created cannot be changed) object. The object created as a
String is stored in the Constant String Pool.
 Every immutable object in Java is thread safe, that implies String is also thread safe.
String can not be used by two threads simultaneously.
 String once assigned cannot be changed.
String demo =” hello”;
// The above object is stored in constant string pool and its value can not be modified.

We can create a string object in two way


1. By using string literal
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't
exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created.


Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).

2. By using new keyword


String str1 = new String("Welcome");
String str2 = new String("Welcome");
In this case compiler would create two different object in memory having the same string.

public class Demo1


{

public static void main(String args[])


{
String s="We have drawn a nice drawing";
System.out.println(s);
String s1=new String();
s1="how are you.";
System.out.println(s1);
String s2= new String("string in block");
System.out.println(s2);
char c[]= {'h','e','l','l','o'};
String s3=new String(c);
System.out.println(s3);
String s4=new String(c,0,3);
System.out.println(s4);
//parsing value
String s5=new String("65");
System.out.println(s5);
int i=Integer.parseInt(s5);

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 have drawn a nice drawing

We

21

now are you.

cow are you.

cow are you.

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. StringBuilder (mutable, asynchronized-no thread safe)


 StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also
be modified .
 The main difference between the StringBuffer and StringBuilder is that StringBuilder is also
not thread safe.
 StringBuilder is fast as it is not thread safe .
StringBuilder demo2= new StringBuilder(“Hello”);
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder(“Bye”);
// Above statement is right as it modifies the value which is allowed in the StringBuilder

In Summary, following are notable difference between StringBuffer


and StringBuilder:
1) StringBuilder is non synchronized version of StringBuffer class. Methods in StringBuilder e.g.
all overloaded version of append() method is not synchronized.

2) StringBuilder is definitely faster than StringBuffer because of no overhead of acquiring and


releasing locks associated with synchronized methods.

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

//converting any number value into string or any other type


int num=1234;
String nts=Integer.toString(num);

Output method in Java


1. System.out.print();-without using new line term
2. System.out.println();-with using new line term
3. System.out.printf(“formatted specifer”,arg1,arg2.arg3); -this is known as formatted
output pattern just like to as a ‘C’ language formation.
4. By using format() method.

Formatter out = new Formatter(new File("out.txt"));


// Write to file with format() method (similar to printf())
int num1 = 1234;
double num2 = 55.66;
String name = "Paul";
out.format("Hi %s,%n", name);
out.format("The sum of %d and %.2f is %.2f%n", num1, num2, num1 + num2);

Input method in Java

1. By using Buffered Reader Class

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));


2. Using Scanner Class

Scanner in = new Scanner(System.in);


3. Using Console Class
It provides a readLine() method which reads a line from the key-board.

Console console = System.console();

String name = console.readLine();

int age = Integer.parseInt(console.readLine());

4. INPUT VIA A DIALOG BOX

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

Object class in Java


 The Object class is the parent class of all the classes in java by default. In other
words, it is the topmost class of java.
 The Object class is beneficial if you want to refer any object whose type you don't
know.

Page 80
https://gits-sln.blogspot.com Durga sir Java Notes

 Object class methods are available to all Java classes


 Object class acts as a root of inheritance hierarchy in any Java Program.
Following are various methods of Object class:

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.

Java Strictfp Keyword


Java strictfp(means strict floating point) keyword ensures that you will get the same result on
every platform if you perform operations in the floating-point variable(because floating point
result varies from one processor to another processor).
 Strictfp provide a all floating point calculation result on the basis of IEEE 754 standard result.
 The strictfp keyword can be applied on methods, classes and interfaces
 The strictfp keyword cannot be applied on abstract methods, variables or constructors.
//Java program to illustrate strictfp modifier

public class Test


{
// calculating sum using strictfp modifier
public strictfp double sum()
{
double num1 = 10e+10;

double num2 = 6e+08;

return (num1+num2);

public static strictfp void main(String[] args)


{

Page 81
https://gits-sln.blogspot.com Durga sir Java Notes

Test t = new Test();

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
{

public abstract strictfp double sum(); //provide a illegal combination.

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

public class Account


{
private double balance;// data hiding term
:
:
public double getBalance()// data abstraction term for user because it work internally.
{
//validation
return balance;
}
public void setBalance(double balance)//data abstraction term for user because it
//work internally.
{
//validation
this.balance=balance;
}
}
Advantage:
1. We can achieved security.
2. Enhancement will become easy.
3. It improve main ability of the application.
The main advantage of Encapsulation is we can achieved security but the main
disadvantage of encapsulation is it increases length of code and slow shutdown
execution.
Tightly encapsulated class
If and only if each and every variable declared as private. Whether class contain
corresponding getter and setter method are not and whether these method are declared
as public or not these things we are not required to check.
public class Account
{
private double balance;
public double getBalance()
{
return balance;
}
}

Find which class is tightly encapsulated


class A
{
int a=10; //not tightly encapsulated
}

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

class C extends A,B


{
// compiler given error
}

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
{

Why java not support multiple inheritance?


There may be a chance of ambiguity problem hence java would not provide support for
multiple inheritance. Example-
If P1 class contain m() method and P2 class contain m() method. If class C extends to
P1 and P2 (by using multiple inheritance). So when child object(class C) call m() method
then in this case a ambiguity problem occur.

Why ambiguity problem not occur in interface?


Because method declaration is occur in parent class A and B. and implementation of
method is taken place in client interface.
By using interface we can achieved multiple inheritance
interface A{ void m(); }
interface B{ void m(); }

interface C extends A,B


{
void m()
{
-----
}
}

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

Car Has-A Engine reference.

Difference between composition and aggregation?


Composition
Without existing container object if there is no chance of existing contain object then
container and contain object are strongly associated and this strong association is
nothing but composition.
Example-
University consist of several department without existing university there is no chance of
existing department hence university and the department are strongly associated and
this strong association is nothing but composition.
Container object university
Contained object  university several department
Aggregation
Without existing container object if there is a chance of existing contained object then
container and contained object are weakly associated and this weak association is
nothing but aggregation.
Example-
Department consist of several professor without existing of department there may by
chance of existing professor object. Hence department and professor object are weakly
associated and this weak association is nothing but aggregation.
Department container object
Professor  contained object

Is-A vs Has-A Relationship


If total functionality of a parent class is required for child class automatically then we go
for Is-A relationship.
If we want to use some functionality is required in child class from total functionality of a
parent class then we go for Has-A relationship.

Method Signature
It consist of method name followed by argument types. Example-

Page 89
https://gits-sln.blogspot.com Durga sir Java Notes

public static int m(int i, float f)  m(int, float)


method return type is not part of method signature of java.
Compile will use method signature to resolve method call (that means it is used to check
that method signature is present in appropriate format or not)
Class Test
{
Public void m(int i)
{ }
Public int m(int j)
{ }
}
Test t=new Test();
t.m(10); CE: ambiguity problem
within a class two method with a same signature not allowed although return type is
differ or same.
Overloading
Two method are said to be overloading if and only if both method having same name but
different argument type in a same class.
It is also known as compile time polymorphism or static time polymorphism or
early binding.
m(int i)
m(float j)
Example- abs(int i), abs(long l), abs(float f)

Case-1: Automatic promotion in overloading


Class Test
{
Public void m(int i)
{
Sop(“int argu”);
}
Public void m(float f)
{
Sop(“int argu”);

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

Case-2: Automatic promotion in overloading not working if more than one


argument with same signature but different pattern term work in method
Class Test
{
Public void m(int i, float f)
{
Sop(“int-float argu”);
}
Public void m(float f, int i)
{
Sop(“float-int argu”);

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

Case-3: Overloading of method for general method and variable argument


(varargs) method
Class Test
{
Public void m(int i)
{
Sop(“general method”);
}
Page 91
https://gits-sln.blogspot.com Durga sir Java Notes

Public void m(int… i)


{
Sop(“varargs method”);

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

Case-4: Automatic precedence in method overloading if argument is different


level
Class Test
{
Public void m(String s)
{
Sop(“String version”);
}
Public void m(Object o)
{
Sop(“object version”);

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

Rules for overriding


1. Method name and argument types must be matched that is method signature must
be same.
2. Return type must be same but this rule is applicable until 1.4 version only form 1.5
version on words we can take co-variant return type according to this child class
method return type need not be same as parent method return type its child type
also allowed.
class p
{
public object m()
{
return null;
}

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.

Par fin No Abst Non synchro Non- Na No Stri Non


ent al n- ract - nized synchro tiv n- ctfp -
clas fin abst nized e na stri
s al ract tiv ctfp
met e
hod
Chil N fin Non abst Non- synchro No na Non Stri
d on al - ract synchro nized n- tiv - ctfp
clas fin abst nized nat e stri
s al/ ract ive ctfp
met fin
hod al
N V Vali Vali Valid Valid Va Va Val vali
ot ali d d lid lid id d
va d
li
d

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

The most accessible term is taken place as


public >protected >default >private

Parent public protected Default Private


class

Page 96
https://gits-sln.blogspot.com Durga sir Java Notes

method

Child public Protected/ Default/ Overriding for


class public protected/ public private is not
method applicable

Checked and unchecked

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 class method non-static and child class method static


class Parent
{
public void m()//non-static method//overridden method
{
System.out.println("parent");
}
}
class Child extends Parent
{
public static void m() //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
{

public static void main(String[] args)


{
Parent p=new Parent();
p.m();//parent method
Child c=new Child();
c.m();//child method
Parent p1=new Child();
P1.m();//parent method
//it is execute parent method because it is not a method overriding it is method hiding so in
method hiding work on the compile time based of reference term.
}
}

Method hiding Overriding


Both parent and child class method Should be non-static
should be static
Compile is responsible for method JVM is always responsible for method
resolution based on reference type resolution based on runtime object
It is also known as compile time It is also known as runtime
polymorphism, static polymorphism, polymorphism, dynamic polymorphism,
early binding late binding

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

Overriding with var-arg method


If we overriding a var-arg method with general method then it is not an
overriding it is known as overloading term.
class Parent
{
public void m(int... x)// var-arg method
{
System.out.println("parent");
}
}
class Child extends Parent
{
public void m(int x) //normal method
{
System.out.println("child");
}
}
public class Test

Page 100
https://gits-sln.blogspot.com Durga sir Java Notes

public static void main(String[] args)


{
Parent p=new Parent();
p.m(10);//parent method
Child c=new Child();
c.m(10);//child method
Parent p1=new Child();
P1.m(10);//parent method
//because it is not overriding(because method name same but signature is differ) it is overloading
of method.

}
}

If we override a var-arg method with another var-arg method


class Parent
{
public void m(int... x)// var-arg method
{
System.out.println("parent");
}
}
class Child extends Parent
{
public void m(int x) //normal method
{
System.out.println("child");
}
}
public class Test
{

public static void main(String[] args)


{
Parent p=new Parent();
p.m(10);//parent method
Child c=new Child();
c.m(10);//child method
Parent p1=new Child();
P1.m(10);//child method //because it is overriding
}
}

Overriding with variable


Variable resolution always takes care by compile based on reference type respective of
whether the variable is static or non-static (overriding concept applicable only for
method not for variable)
class Parent
{
int x=10;
}
class Child extends Parent
{
int x=20;
}
public class Rnd3

Page 101
https://gits-sln.blogspot.com Durga sir Java Notes

public static void main(String[] args)


{
Parent p=new Parent();
System.out.println(p.x);//10
Child c=new Child();
System.out.println(c.x);//20
Parent p1=new Child();
System.out.println(p1.x); //10
}
}

variable Pv non- Pv static Pv non- Pv static


static Cv non- static Cv static
Cv non- static Cv static
static
Result 10 10 10 10
20 20 20 20
10 10 10 10

Difference between overloading and overriding

Property Overloading Overriding


Method name Must be same Must be same
Argument type Must be different (at least Must be same (including
order) order)
Method signature Must be different Must be same
Return type No restriction Must be same until 1.4v
but from 1.5 v co-variant
return type allowed
Private, static, final Can be overloaded Can not be overridden
method
Access modifiers No restriction The scope of access
modifiers cannot be
reduced but we can
increase.
Throws clause No restriction If child class method
throws any checked
exception compulsory
parent class method
should throws the same
checked exception in it’s
parent but …
Method resolution Always take care by Always take care by JVM
compiler based on based on runtime object
reference type
Known as Compile time Runtime polymorphism,
polymorphism, static dynamic polymorphism,
polymorphism, early late binding
binding,

Page 102
https://gits-sln.blogspot.com Durga sir Java Notes

Consider the following method in parent class

public void int m(int x) throws IOException

In the child class which of the following method we can take

Polymorphism

One name but multiple form is a concept of polymorphism. Example-


1. Method name is the same but we can apply for different type of arguments
overloading
2. Method signature is same but in parent class one type of implementation and in
the child class another type of implementation overriding
3. Uses of parent reference to hold child object is the concept of polymorphism.

Page 103
https://gits-sln.blogspot.com Durga sir Java Notes

List l=nes ArrayList() | new LinkedList() | new Vector() | new Stack();


a) Parent class reference can be used to hold child object but by using that reference we
can call only the method available in parent call and we cannot call child specific
method.
If class Parentm1()
And class Child m2()
Parent p=new Child();
p.m1();
p.m2(); CE
b) but by using child reference we can call both parent and child class method
Child c=new Child();
c.m1();
c.m2();
so when we should go for parent reference to hold child object.
c) If we don’t know exact runtime type of object then we should go for parent reference.
Example- the first element present in the array list can be any type student object or
customer object or string object or stringbuffer object. Hence the return type of get
method is object, which can hold any object.
Object o=l.get(0);

d)

Page 104
https://gits-sln.blogspot.com Durga sir Java Notes

Child c=new Child(); Parent p=new Parent();


ArrayList al=new ArrayList()l; List l=new ArrayList();
Use if we know exact runtime object If we don’t know exact runtime type of
object
We can call both parent and child class We can call only parent class method but
method(advantage) not child class
method.(disadvantage)
We can use only child class reference to Use parent class reference to hold any
hold child class object.(disadvantage) child class object. ( advantage)

Page 105
https://gits-sln.blogspot.com Durga sir Java Notes

Advanced Oops feature

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.

Static control flow


The flow of program taken place on the basis of following three rules-
1-identification of static member from top to bottom
2-execution of static variable assignment and static block from top to bottom
3-execution of main method

public class Rnd3


{
Pass-1 static int i=10; //pass-7
Pass-2 static
{
m();//pass-8
System.out.println("first static block");//pass-10
}

Pass-3 public static void main(String[] args)


{
m();//pass-13
System.out.println("main method block");//pass-15

Pass-4 public static void m()


{
System.out.println(j); //pass-9//pass-14
}
Pass-5 static
{
//m();

Page 112
https://gits-sln.blogspot.com Durga sir Java Notes

System.out.println("second static block");//pass-11


}
Pass-6 static int j=20;//pass-12
}

1. i=0(read indirectly write only) //from pass-1


2. j=0 (read indirectly write only) //from pass-6
3. the above step-1 and step-2 from pass-1 to pass-6 follow rule no-1

4. i=10(read and write) //from pass-7


5. goto pass-8
6. goto pass-9 and execute 0(j=0)
7. goto pass-10 and execute first static block
8. goto pass-11 and execute second static block
9. goto pass-12 and assign 20(j=20 )
10. the above step-4 to step-9 of pass-7 to pass-12 follow rule no-2

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

public class Rnd3


{
{
System.out.println("hi how are you");
System.exit(0);
}
}

public class Rnd3


{
Rnd3()
{
System.out.println("hi how are you");
System.exit(0);
}

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.

Static control flow in parent to child relationship


Whenever we are executing child the following sequence of event will be executed
automatically-
Step-1 Identification of static member from parent to child
Step-2 Execution of static variable assignment and static block from parent to child
Step-3 Execution of only child class main method

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

P-11 static int y=200; p-22


}

If we Save as Derived.java then execution are taken place in this way

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

p-22 redirect p-24 given 200 (y=200)


p-25 Derived main
rule no-3 taken place from p-23 to p-25

If we Save as Base.java then execution are taken place in this way


0
base class static block
20
base class main

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.

Instance control flow


Whenever we are creating an object Execution follow in this way-
Step-1 Identification of instance member from top to bottom.
Step-2 Execution of instance variable assignment and instance block from top to
bottom.
Step-3 Execution of constructor.
But if we are not creating any object then in this case only main method block will be
executed.
class Rnd3
{
p-3 int i=10;//instance variable p-9
p-4 {//instance block
m1(); p-10
System.out.println("first instance block"); p-12
}
p-5 Rnd3()
{
System.out.println("constructor"); p-15
}
p-1 public static void main(String[] args)
{
p-2 Rnd3 r=new Rnd3();//object creation
System.out.println("main"); p-16
}
p-6 public void m1()
{
System.out.println(j); p-11
}
p-7 {//instance block
System.out.println("second instance block"); p-13
}
p-8 int j=20;//instance variable p-14
}

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

p-13 second instance block


p-14 j=20[R&W]
p-9 to p-14 follow rule no-2
p-15 given constructor
p-16 given main
if we not creating object of class then output
main

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.

Instance control flow in parent to child relationship


The follow for this are given below as
Step-1 Identification of instance member from parent to child
Step-2 Execution of instance variable assignment and instance block only in parent class
Step-3 Execution of parent constructor
Step-4 Execution of instance variable assignment and instance block only in child class
Step-5 Execution of child constructor

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

int j=20;//instance variable


}
class child extends parent
{
int x=100;//instance variable
{//instance block
m1();
System.out.println("child first instance block");
}
child()
{
System.out.println("child constructor");
}
public static void main(String[] args)
{
child r=new child();
System.out.println("child main");
}
public void m1()
{
System.out.println(y);
}

int y=200;//instance variable


}

If we save this program as parent.java then output will be


0
parent first instance block
parent constructor

Page 120
https://gits-sln.blogspot.com Durga sir Java Notes

parent main

if we save this program as child.java then output will be


0
parent first instance block
parent constructor
0
child first instance block
child constructor
child main

Page 121
https://gits-sln.blogspot.com Durga sir Java Notes

Instance block with static block


Rule
1. Static block is a onetime activity.
2. Instance block is multiple time activity follow on the basis of object creation.
class Rnd3
{
{
System.out.println("first instance block");
}
static
{
System.out.println("first static block");
}
Rnd3()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
Rnd3 r1=new Rnd3();
System.out.println("main");
Rnd3 r2=new Rnd3();
}
static
{
System.out.println("second static block");
}

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

Instance control flow and static control flow both simultaneously


package com.java.test;
class Rnd3
{
private static String m1(String msg)
{
System.out.println(msg);
return msg;
}
public Rnd3()
{
m=m1("1");
}
{
m=m1("2");
}
String m=m1("3");
public static void main(String[] args)
{
Object o=new Rnd3();
}
}

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

Rnd3 r=new Rnd3(); //whenever creating an object


System.out.println(r.x);
}
}

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.

Difference between constructor and instance block


1. The main purpose of constructor is initialization of an object
2. But other than initialization if we want to perform any activity for every object
creation then we should go for instance block (like updating one entry in the
database for every object creation or incrementing count value for every object
creation.)
3. Both constructor and instance block have they own different purpose and replacing
one concept with another concept may not work always.
4. Both constructor and instance block will be executed for every object creation but
instance block first followed by constructor.
Demo program to print no of object created for a class
class Rnd3
{
static int count=0;
{
count++;
}
Rnd3()
{

}
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

Rules of writing constructor


Name of the class and name of the constructor must be matched.
Return type concept not applicable for Constructor even void also.
By mistake if we are trying to declare return type for the constructor then we won’t get
any compile time error because compiler treats it as a method. Hence it is legal but not
recommended.
Modifiers applicable for constructor are public, private, protected, default only.
Default constructor
1. Compiler is responsible to generate default constructor (but not JVM)
2. If we are not writing any constructor then only compiler will generate default
constructor that is if we are writing at least one constructor then compiler wouldn’t
generate default constructor hence every class in java can contain constructor it
may be default constructor generated by compiler or customizable constructor
explicitly provided by the programmer but not both simultaneously.
Prototype of default constructor
1. It is always no-arg constructor.
2. The access modifiers of default constructor is exactly same as access modifiers of
class (this rule is applicable only for public and default).
3. It contain only one line super();
4. It is a no-arg call to super class constructor.

Programmer generated code Compiler generated code


class Test class Test
{ {
Test()
} {
super();
}
}
public class Test public class Test
{ {
public Test()
} {
super();
Page 126
https://gits-sln.blogspot.com Durga sir Java Notes

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

class Test class Test


{ {
Test() Test()
{ {
this(10); this(10);
} }
Test(int i) Test(int i)
{ {
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() and this() conclusion


1. We can use only in constructor
2. We can use only in first line inside constructor
3. We can use only one at a time not both at a time.

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

public static void main(String[] args)


{
//m1();//if we calling this method then runtime error: StackOverflowError
System.out.println("hello");
//System.out.println("-----------------");
}
}

If we are using constructor recursive calling program


class Rnd3
{
Rnd3()
{
this(10);
}
Rnd3(int i)
{
this();

Page 129
https://gits-sln.blogspot.com Durga sir Java Notes

public static void main(String[] args)


{

}
}

This program given compile time error: recursive constructor invocation

Note- constructor recursion is not possible.


Case-2 if parent class contain any arg constructor then while child classes we have to
take special care with respect to constructor.
Whenever we are writing any arg constructor it is highly recommended to write no-arg
constructor also.

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

1. The main purpose is to create an object invalid


2. The main purpose is to perform initialization of an object valid
3. The name of the constructor need not be the same as class name
invalid
4. Return type concept applicable for constructor but only void
invalid
5. We can apply any modifier for constructor
invalid
6. Default constructor generate by JVM
invalid
7. Compiler is responsible to generate default constructor
valid
8. Compiler will always generate default constructor
invalid
9. If we are not writing no-arg constructor then compiler will generate default
constructor
invalid
10. Every no-arg constructor is always default constructor
invalid
11. Default constructor is always no-arg constructor
valid
12. The first line inside every constructor should be eithr super or this if we are not
writing anything then compiler will generate this.
Invalid
13. For constructor both overloading and overriding concept is applicable
invalid
14. Inheritance concept applicable but not overriding
invalid
15. Only concrete class can contain constructor but abstract class cannot
invalid
16. Interface can contain constructor
invalid
17. Recursive construcot invocation is a runtime excetion
invalid
18. If parent class constructor throws some checked excetion then child class
constructor should through the same exception or it parent
valid
19.

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

Runtime, Bussinessdelegae, Servicelocator etc.


Advantage of singleton class
If several people have same requirement then it is not recommended to create a
separate object for every requirement we have to create only one object and we can
reuse the same object for every similar requirement so that performance and memory
utilization will be improve. This is the central idea of singleton classes.

How to create our own singleton classes ?


We have to use private constructor and private static variable and public factory method
Approach-1

Runtime class is internally implemented by using this approach.


Approach-2

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

File class constructor

Page 134
https://gits-sln.blogspot.com Durga sir Java Notes

Important method of file class

Page 135
https://gits-sln.blogspot.com Durga sir Java Notes

Page 136
https://gits-sln.blogspot.com Durga sir Java Notes

FileWriter

fw.write(100); menas 100 will be converted to its equivalent ascii characterd


fw.write(‘d’); char to int promotion accepted
after writing data in a file it is mandatory to run flush() method.
After completing all reading and writing operation it is mandatory to close() it.

Page 137
https://gits-sln.blogspot.com Durga sir Java Notes

FileReader

Page 138
https://gits-sln.blogspot.com Durga sir Java Notes

 int read() return unicode value


 int read(char[] ch) it is used to copy no of character from file into array
 void close() it is used to close the file

Page 139
https://gits-sln.blogspot.com Durga sir Java Notes

BufferWriter

 BufferedWriter is used to overcome the problem of FileWriter (line seperator).


newLine() method is work as a line separator bw.newLine()
 BufferedReader is used to read line by line intends of character by character.

Page 140
https://gits-sln.blogspot.com Durga sir Java Notes

Page 141
https://gits-sln.blogspot.com Durga sir Java Notes

bw.write(100) means insert d character since 100 unicode value is d

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.

Case-1: Type safety


Array are type safe that means we can give the guarantee for the type of element
present inside array
Example
If our programmer required is to hold only string type of object we can choose string
array by mistake if we are trying to add any other type of object we will get compile time
error.
String[] s=new String[1000];
s[0]=”Druga”;
s[1]=”Ravi”;
//s[2]=new Integer(10);CE: incompatible type found: Integer Required: String
s[2]=”Shiva”;

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

String name1=l.get(0); //CE: incompatible type found: Object required: String


String name1=(String)l.get(0); //type casting is mandatory
Hence type casting is a bigger headache in collection.
To overcome above problem of collection sun people introduce generic concept in 1.5
version.

Page 149
https://gits-sln.blogspot.com Durga sir Java Notes

Hence the main objective of generic are


1-To provide type safety.
2-To resolve type casting problem.
To hold only sting type of object we can create generic version of array list object as
follows
ArrayList<String> l=new ArrayList<String>
l.add(“Durga”);
l.add(“Ravi”);
by mistake if we are trying to add any other type then we will get compile time error
l.add(new Integer(10));// CE:
l.add(“Shiva”);
Hence through generic we are getting type safety.
At the time of retrivel we are not required to perform typecasting
ArrayList<String> l=new ArrayList<String>
l.add(“Durga”);
String name1=__l.get(0); // __ type casting is not required
So through generic we can solve typecasting problem.

ArrayList l=new ArrayList(); ArrayList<String> l=new


ArrayList<String>;
Non generic version of array list object It is a generic version of array list object
For this array list we can add any type For this array list we can add only string
of object and hence it is not type safe type of object and hece it is type safe.
At the time of retrival compulsory we At the time of retrival we are not required
have to perform type casting to perform typecasting

There are two conclusion are


Conclusion-1
Polymorphism concept applicable only for base type but not for parameter type (uses of
parent reference to hold child object is concept of polymorphism)

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

Where X can be either class or interface.

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

Wild chad character? Used

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

a) we can call this method only string type


b) but within the method we can add only string type of object to the list by mistake
if we are trying to add any other type then we will get compile time error.

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)

This type of method is best suitable for read-only operation.


m(AL<?> l)
{
Sop(l);
}

m(AL<? extends X> l)

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

Communication with non-generic code


If we send generic object to non-generic area then it start behaving like non-generic
object similarly if we send non generic object to generic area then it start behaving like
generic object that it the location in which object present based on that behavior will be
defined.

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

ArrayList<String> l=new ArrayList<String>();


ArrayList<String> l=new ArrayList();
The above both line are equal meaning.so for these array list object we can add only
string type of object.

Java. Lang package

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

Time complexity of liner search- O(n)


Time cocmplexity of binary search- O(log n)
Time complexity of hashing-- O(1)
Hash code based on address of an object means by using address of an object a hash
code is generated.

Page 166
https://gits-sln.blogspot.com Durga sir Java Notes

Program to find total no of object method with method name


import java.lang.reflect.Method;

public class Ob {

public static void main(String[] args) throws ClassNotFoundException {


// TODO Auto-generated method stub
int count=0;
Class c=Class.forName("java.lang.Object");
Method[] m=c.getDeclaredMethods();
for(Method m1:m)
{
count++;
System.out.println(m1.getName());
}
System.out.println("the number of method:"+count);
}

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

int rollnum2=s.rollnum; //RE:NPE


if(name1.equals(name2) && rollnum1==rollnum2)
{
return true;
}
else
{
return false;
}

}
catch(ClassCastException e) { return false;}
catch(NullPointerException e) { return false;}
}

Simplified version of equals method

Page 170
https://gits-sln.blogspot.com Durga sir Java Notes

Now more simplified version of equals method are

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

Used to get the runtime class definition of an Object.

Syntax- public final Class getClass()

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;

public class Test {

public static void main(String[] args) {


// TODO Auto-generated method stub
Object ob=new String("durga");
Class c=ob.getClass();
System.out.println("fully quallified class name"+ob.getClass());
System.out.println("fully quallified class name"+c.getClass());
Method[] m=c.getDeclaredMethods();
System.out.println("method information");
for(Method m1:m)
{
System.out.println(m1.getName());
}
}

Example-To display database vendor specific connection interface implemented class


name

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.

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


 We can use these method for inter-thread communication
 The thread which is expecting updating which is responsible to call wait() then
immediately the thread will enter into waiting state.
 The thread which is responsible to perform updating, after preforming updating the
thread can call notify().
 The waiting thread will get that notification and then continue its execution with those
updates.

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);//falseused for reference comparison
System.out.println(s1.equals(s2));//true it is an string class equals() method

//used for content comparison

StringBuffer sb1=new StringBuffer("durga");


StringBuffer sb2=new StringBuffer("durga");
System.out.println(sb1==sb2);//false  used for reference comparison
System.out.println(sb1.equals(sb2));//false it is an object class equals() method so used for

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-

So total no of object created in the above program is 3


Whenever we are using new operator compulsory a new object will be created in the
heap area hence there may be a chance of existing two object with same content in the
heap area but not in scp that is duplicate object are possible in the heap area but not in
scp.
Example-
String s1=new String("durga");
s1.concat("software");

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.

Constructor of String class


String s=””; //string object is their but its length is zero.
String s=null; //string object is not their
There are different way to create a constructor of string class
1) String s=new String();
an empty length of object is created
2) String s=new String(String literal);
create a string object on the heap for the given string literal
3) String s=new String(StringBuffer sb);
Create an equivalent string object for the given string buffer
4) String s=new String(char[] ch);
Create an equivalent string object for the given char array
Ex- char[] ch={‘a’,’b’,’c’,’d’};
String s=new String(ch);
Sop(s);// abcd
5) String s=new String(byte[] b);
Create an equivalent string object for the given byte array
Ex- byte[] b={100,101,102,103};
String s=new String(b);
Sop(s);//defg

Page 175
https://gits-sln.blogspot.com Durga sir Java Notes

Important method of String Class


1. public char charAt(int index)
return the character locating at specified index
example-
String s=”Druga”;
System.out.println(s.charAt(3));// g
System.out.println(s.charAt(30));//RE:stringindexoutofboundexception
2. public String concat(String s)
the overloaded + and += operator is same as concatenation purpose only.
String s=”Durga”;
s=s.concat(“software”);
//s=s+”software”;
//s+=”software”;
Sop(s);//Durgasoftware

3. public boolean equals(Object o)


to perform content comparison where case is important.
This is overriding version of Object class equals() method.
String s=”java”;
Sop(s.equals(“JAVA”));//false
4. public boolean equalsIgnoreCase(String o)
to perform content comparison where case is not important.
String s=”java”;
Sop(s.equalsIgnoreCase(“JAVA”));//true
Note-
In general we can use equalsIgnoreCase() method to validate use name where case is
not important whereas we can use equals() method to validate password where case is
important.
5. public String substring(int begin)
return substring from beginning index to end of the string.
String s=”abcdefg”;
Sop(s.substring(3));//defg
6. public String substring(int begin, int end)
Return substring from beginning index to end-1 index.
String s=”abcdefg”;
Page 176
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

9. public String toLowerCase()

10. public String toUpperCase()

11. public String trim()


to remove the blank spaces present at beginning and end of the string but not the
middle blank spaces.
12. public int indexOf(char ch)
Return index of first occurrence of a specified character.
String s=”ababa”;
Sop(s.indexOf(‘b’));//1
13. public int lastIndexOf(char ch)
Return index of last occurrence of a specified character.
String s=”ababa”;
Sop(s.lastIndexOf(‘b’));//3

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

How to create our own immutable class?


Once we create an object we cannot perform any change in that object if we are trying
to perform any change and if there is a change in the content then with those changes a
new object will be created.

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.

We can create our own immutable class

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

Hence final and immutable both are different concept.

Which are the following are meaningful?


1. Final variable //valid
2. Immutable variable //invalid
3. Final object //invalid
4. Immutable object //valid

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

1) StringBuffer sb=new StringBuffer();


Create an empty StringBuffer object with default initial capacity 16. Once StringBuffer
reaches max capacity a new StringBuffer object will be created with new capacity
New capacity=(current capacity+1)*2
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//16

Page 180
https://gits-sln.blogspot.com Durga sir Java Notes

sb.append("abcdefghijklmnop");//16 character add


System.out.println(sb.capacity());//16
sb.append("q");//1 character add means 17th character add which exceed max limit
of stringbuffer //capacity
System.out.println(sb.capacity());//(16+1)*/2=34

2) StringBuffer sb=new StringBuffer(int initialcapacity);


Create an empty StringBuffer object with specified initialcapacity.
3) StringBuffer sb=new StringBuffer(String s);
Create an equivalent StringBuffer of given String with capacity
Capacity=s.length()+16
StringBuffer sb=new StringBuffer("durga");
System.out.println(sb.capacity());//5+16=21

Important method of StringBuffer


1) public int length()
2) public int capacity()
3) public char charAt(int index)
4) public void setCharAt(int index, char ch)
to replace the character located at the specified index with provided character
5) public StringBuffer append(String s)
public StringBuffer append(int i)
public StringBuffer append(long l)
public StringBuffer append(char ch)
public StringBuffer append(boolean b)
:
:
:
these are overloaded method.
append() method is used to insert a term after a string.
StringBuffer sb=new StringBuffer();
sb.append("PI value is");
sb.append(3.14);
sb.append(true);
System.out.println(sb);

Output-PI value is3.14true


6) public StringBuffer insert(int index, String s)
public StringBuffer insert(int index, int i)
public StringBuffer insert(int index, double d)
public StringBuffer insert(int index, char ch)
public StringBuffer insert(int index, boolean b)
:
:
These are overloaded method.

Page 181
https://gits-sln.blogspot.com Durga sir Java Notes

insert() method is used to insert a term at the specified index location.


7) public StringBuffer delete(int begin, int end)
To delete character located from begin index to end-1 index.
8) public StringBuffer deleteCharAt(int index)
To delete the character located at specified location.
9) public StringBuffer reverse()
10) public void setLength(int lenght)
Example-
StringBuffer sb=new StringBuffer(“abcdefgh”);
sb.setLength(5);
sop(sb); //abcde
11) public void ensureCapacity(int capacity)
to increase capacity on fly based on our requirement.
StringBuffer sb=new StringBuffer();
Sop(sb.capacity());//16
sb.ensureCapacity(1000);
sop(sb.capacity());//1000
12) public void trimToSize();
to deallocated extra allocated memory.
StringBuffer sb=new StringBuffer(1000);
sb.append(“abc”);
sb.trimToSize();
sop(sb.capacity());//3

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

Note- Except the above difference everything is same in StringBuffer and


StringBuilder including method and constructor.

Page 182
https://gits-sln.blogspot.com Durga sir Java Notes

String vs StringBuffer vs StringBuilder


If the content is fixed and won’t change frequently then we should go for String.
If the content is not fixed and keep on changing but thread safety required then we
should go for StringBuffer.
If the content is not fixed keep on changing but thread safety is not required then we
should go for StringBuilder.

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()…….

StringBuffer sb=new StringBuffer();

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

Wrapper class Corresponding constructor argument


Byte byte or String
Short short or String
Integer integer or String
Long long or String

Page 183
https://gits-sln.blogspot.com Durga sir Java Notes

Float float or String or double


Double double or String
Character char
Boolean boolean or String

A special term for Boolean-


If we are passing String type as argument then case and content both are not important.
If the content is case insensitive String of true or TRUE then it is treated as true
otherwise it is treated as false.
Boolean x=new Boolean("yes");
Boolean y=new Boolean("no");
Boolean x1=new Boolean("true");
Boolean y1=new Boolean("false");
System.out.println(x);//false
System.out.println(y);//false
System.out.println(x1);//true
System.out.println(y1);//false

In all wrapper classes toString() method is overridden to return content directly.


In all wrapper classes .equals() method is overridden for content comparision.

Utility method of wrapper classes


1.valueOf()
we can use valueOf() method to create wrapper object for given primitive or String
Form-1
Every wrapper class except character class contain static value of method to create
wrapper object for the given String
public static wrapper valueOf(String s)
Example
Integer I = Integer.valueOf("10");
System.out.println(I);
Double D = Double.valueOf("10.0");
System.out.println(D);
Boolean B = Boolean.valueOf("true");
System.out.println(B);

// Here we will get RuntimeException


Integer I1 = Integer.valueOf("ten");
Output-
10
10.0
true
Exception in thread "main" java.lang.NumberFormatException: For input string:
"ten"

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

1. public byte byteValue()


2. public short shortValue()
3. public int intValue()
4. public long longValue()
5. public float floatValue()
6. public float doubleValue()

Integer I = new Integer(130);


System.out.println(I.byteValue());
System.out.println(I.shortValue());
System.out.println(I.intValue());
System.out.println(I.longValue());
System.out.println(I.floatValue());
System.out.println(I.doubleValue());

Output:

-126
130
130
130
130.0
130.0

3.parseXxx() method : We can use parseXxx() methods to convert String to primitive.


There are two types of parseXxx() methods:

 primitive parseXxx(String s) : Every Wrapper class except character class


contains the following parseXxx() method to find primitive for the given String
object.
Syntax:

public static primitive parseXxx(String s);


int i = Integer.parseInt("10");
double d = Double.parseDouble("10.5");
boolean b = Boolean.parseBoolean("true");
System.out.println(i);
System.out.println(d);
System.out.println(b);

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

public static primitive parseXxx(String s, int radix);


int i = Integer.parseInt("1000", 2);
long l = Long.parseLong("1111", 4);
System.out.println(i);
System.out.println(l);

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:

public String toString();


Integer I = new Integer(10);
String s = I.toString();
System.out.println(s);

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:

public static String toString(primitive p, int radix);


String s = Integer.toString(15, 2);
System.out.println(s);
String s1 = Long.toString(11110000, 4);
System.out.println(s1);

Output:

Page 187
https://gits-sln.blogspot.com Durga sir Java Notes

1111
222120121300

 toXxxString():Integer and Long wrapper classes let you convert numbers in


base 10 to other bases. (Binary, Hexadecimal, Octal)
String s3 = Integer.toHexString(254); // convert 254 to hex
System.out.println("254 is " + s3); // result: "254 is fe"

String s4 = Long.toOctalString(254); // convert 254 to octal


System.out.print("254(oct) ="+ s4); // result: "254(oct) =376"
Output:
254 is fe
254(oct) =376

Page 188
https://gits-sln.blogspot.com Durga sir Java Notes

Partial hierarchy of java.lang package

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

Void is the class representation of void keyword in java.

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

But buffer concept is available only in the following range

Excepted this range in all remaining cases a new object will be created.

Internally autoboxing concept is implemented by using valueOf() method hence buffering


concept is applicable for valueOf() method also.

Page 193
https://gits-sln.blogspot.com Durga sir Java Notes

Overloading with respect to autoboxing, widening and var-arg


method
Case-1

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

public static void main(String[] args) {


// TODO Auto-generated method stub
int x=10;
m1(x);
}
}
Output- widening
Widening dominates autoboxing.
Case-2

Widening vs varg-arg method


public class Ob {
public static void m1(int... x)
{
System.out.println("var-arg");
}
public static void m1(long l)
{
System.out.println("widening");
}

public static void main(String[] args) {


// TODO Auto-generated method stub
int x=10;
m1(x);
}
}

Output- widening
Widening dominates varg-arg method.
Case-3

Autoboxing vs varg-arg method


public class Ob {
public static void m1(int... x)
{
System.out.println("var-arg");
}
public static void m1(Integer I)

Page 194
https://gits-sln.blogspot.com Durga sir Java Notes

{
System.out.println("autoboxing");
}

public static void main(String[] args) {


// TODO Auto-generated method stub
int x=10;
m1(x);
}
}

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

Widening followed by autoboxing is not allowed in java whereas autoboxing followed by


widening is allowed.

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; //validautoboxing
int i=10L; //invalid
Long l=10L: //validautoboxing
Long l=10; //invalid
long l=10; //valid-widening
Object o=10; //validautoboxing followed by widening
double d=10; //valid widening
Double D=10; //invalid
Number N=10; //validautoboxing followed by
widening

Relation between == operator and equal() method


1) If two object are equal by == operator then these object are always equal by
.equals() method that is
If r1==r2 is true then r1.equals(r2) is always true.

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

Difference between == operator and .equals() method


To use == operator compulsory there should be some relation between argument types
(either child to parent or parent to child or same type ) otherwise we will get compile
time error incomparable types
If there is no relation between argument types .equals() method won’t rise any compile
time or run time error simply it return false.

== operator .equals() method


It is applicable for both primitives and Applicable for only object types but not
object types. primitive types.
Use for object reference (or address) By default it is present in object class
comparison only. also met for reference comparison.
We cannot override == operator for We can override .equals() method for
content comparison content comparison.
To use == operator compulsory there If there is no relation between argument
should be some relation between types then .equals() method won’t rise
argument type(either child to parent or any compile time or runtime error and

Page 197
https://gits-sln.blogspot.com Durga sir Java Notes

parent to child or same type) otherwise simply return false.


we will get compile time error saying
incomparable types.

One line answer


In general we can use == operator for reference comparison and .equals() method for
content comparison.
For any object reference are
r==rull or r.equals(null) is always return false.
Example:
Thread t=new Thread();
Sop(t==null);//false
Sop(t.equals(null));//false
Note- hashing related data structure follow the following fundamental rules
Two equivalent object should be placed in same bucket but all object present in the
same bucket need not be equal.

Contract between .equals() method and hashCode()


method
If two object are equals by .equals() method then there hashcode must be equal that is
two equivalent object should have same hashcode that is
If r1.equals(r2) is true then r1.hashCode()==r2.hashCode() is always same.
Object class .equals() method and hashCode() method follows above contract hence
whenever we are overriding .equals() method compulsory we should override
hashCode() method to satisfied above contract. That is two equivalent object should
have same hashCode.
1. If two object are not equal by .equals() method then there is no restriction on
hashCode may be equal or may not be equal.
2. If hasCode of two object are equal then we cannot conclude any thing obout
.equals() method if may return true or false.
3. If hasCode of two object are not equal then this object are always not equal by
.equals() method.
Note- to satisfied contract between equals() and hashCode() mehod whenever we are
overriding .equals() method compulsory we have to override hashCode() method
otherwise we won’t get any compile time or runtime error but it is not a good
programming practices.

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

Note- based on which parameters we override .equals() method it is highly recommend


to use same parameters while overriding hashCode() also.
In all collection classes, in all wrapper classes and in String class .equals() is overridden
for content comparison hence it is highly recommended to override equals() method in
our class also for content comparison.

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

public class Ob implements Cloneable {

int i=10;
int j=20;

public static void main(String[] args) throws CloneNotSupportedException {


Ob t1=new Ob();
Ob t2=(Ob) t1.clone();
t2.i=111;
t2.j=222;
System.out.println(t1.i+" "+t1.j);
System.out.println(t2.i+" "+t2.j);
}
}

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 vs Deep cloning

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

public static void main(String[] args) throws CloneNotSupportedException{


Cat c=new Cat(20);
Dog d1=new Dog(c,10);
System.out.println(d1.i+" "+d1.c.j);
Dog d2=(Dog)d1.clone();
d2.i=888;
d2.c.j=999;

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 {

public static void main(String[] args) throws CloneNotSupportedException{


Cat c=new Cat(20);
Dog d1=new Dog(c,10);
System.out.println(d1.i+" "+d1.c.j);
Dog d2=(Dog)d1.clone();
d2.i=888;
d2.c.j=999;

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

Scp area and heap area

Page 205
https://gits-sln.blogspot.com Durga sir Java Notes

Interning of String object


We can use intern() method to get corresponding scp object reference by using heap
object reference.
OR
By using heap object reference if we want to get corresponding scp object reference then
we should go for intern() method.
Example-

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

Importance of String constant pool

In our program if a string object is repeatedly required then it is not recommended to


create separate object for every requirement because it create performance and memory
problem.
Instated of creating a separate object for every requirement we have to create only one
object and we can reuse the same object for every requirement so that performance and
memory utilization will be improved this things is possible of SCP.
The main advantage of SCP are
Memory utilization and performance will be improved.
But main problem in SCP is, as several reference pointing to the same object, by using
one reference if we are trying to change the content then remaining reference will be
affected.
To overcome this problem sun people implement string object as immutable that is once
we create string object we cannot perform any changes in the existing object if we are
trying to perform any changes with those changes a new object will be created.
Hence SCP is the only reason for immutability of string object.

Page 208
https://gits-sln.blogspot.com Durga sir Java Notes

Frequently asked question-

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

1. Normal or regular inner classes


If we are declaring any named class (means no any anonymous inner class) directly
inside a class (means no any method local inner classes) without static modifiers (means
no static nested classes) such type of inner classes is called normal or inner 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

Case.1-Accessing inner class code from static area of outer class.


public class Outer {
class Inner
{
public void m()
{
System.out.println("inner class method");
}
}

public static void main(String[] args) {


//Outer o=new Outer();
//Outer.Inner i=o.new Inner();
//Outer.Inner i=new Outer().new Inner();//above two line can be combine by using this line
//i.m();
new Outer().new Inner().m();//above two line and method calling combine by this line
}

Case.2-Accessing inner class code from instance area of outer class.


public class Outer {
class Inner
{
public void m1()
{
System.out.println("inner class method");
}
}
public void m2()
{
Inner i=new Inner();
i.m1();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Outer o=new Outer();
o.m2();
}

Case.3-Accessing Inner class code from outside of outer class


class Outer {

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

public static void main(String[] args) {

new Outer().new Inner().m1();


}

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 static void main(String[] args) {

new Outer().new Inner().m1();


}

The only applicable modifiers for outer classes are

Public default fina abstract strictfp

But for inner classes applicable modifiers are

Public default final abstract strictfp private protected static

Nesting of inner classes


Inside inner class we can declare another inner class that is nesting of inner classes is
possible
class A
{
class B
{
class C
{
public void m1()
{
System.out.println("innermost class method");
}
}
}

}
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

A.B.C c=b.new C();


c.m1();

2. Method local inner classes


Sometimes we can declare a class inside a method such type of inner classes are called
method local inner classes.
The main purpose of method local inner class is to defined method specific repeated
required functionality.
Method local inner classes are best suitable to meet nested method requirement.
We can access method local inner classes only within the method where we declare
outside of the method we cannot access because of its less scope method local inner
classes are most rarely used of inner classes.
public class Outer
{
public void m1()
{
class Inner
{
public void sum(int x,int y)
{
System.out.println("the sum is"+(x+y));
}
}
Inner i=new Inner();
i.sum(10, 20);
i.sum(100, 200);
i.sum(1000, 2000);
}
public static void main(String[] args)
{
Outer o=new Outer();
o.m1();
}
}
Output-
the sum is30
the sum is300
the sum is3000
We can declare method local inner class inside both instance and static method. If we
declare inside static method a small difference is observe
 If we declare inner class inside instance method then form that method local inner
class we can access both static and non-static member of outer class directly.
 If we declare inner class inside static method then we can access only static
member of outer class directly from that method local inner class.

Page 216
https://gits-sln.blogspot.com Durga sir Java Notes

public class Outer


{
int x=10;
static int y=20;
public void m1()
{
class Inner
{
public void m2()
{
System.out.println(x);
System.out.println(y);
}
}
Inner i=new Inner();
i.m2();
}
public static void main(String[] args)
{
Outer o=new Outer();
o.m1();
}
}
Output-
10
20
If we declare m1() is static then sop(x) compile time error saying Cannot make a static
reference to the non-static field x

public class Outer


{
int x=10;
static int y=20;
public static void m1()
{
class Inner
{
public void m2()
{
System.out.println(x);//CE: Cannot make a static reference to the non-static field x

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

3. Anonymous inner classes


Sometime we can declare inner class without name such type of inner class are called
anonymous inner classes.
The aim purpose of anonymous classes is just for instance use (one time uses) .
Type of anonymous inner classes
1. Anonymous inner class that extends a classes
2. Anonymous inner classes that implements an interface
3. Anonymous inner class that defined inside argument

A. Anonymous inner class that extends a classes

class PopCon
{
public void taste()
{
System.out.println("salty");
}
}
public class Test
{
public static void main(String[] args)
{

PopCon p=new PopCon()


{
public void taste()
{
System.out.println("spicy");
}
};
p.taste(); //spicy
PopCon p1=new PopCon();
p1.taste(); //salty
PopCon p2=new PopCon()
{
public void taste()

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

 PopCon p1=new PopCon();


Just we are creating PopCon Object

 PopCon p2=new PopCon()


{

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

II. In the child class we are overriding taste() method.


III. For that child class we are creating an object with parent reference.

Defining a Thread by extending Thread class


Normal class approach and anonymous class approach

public class Outer


{
public static void main(String[] args)
{
Thread t=new Thread()
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(i+" child thread");
}
}
};
t.start();
for(int i=0;i<10;i++)
{
System.out.println(i+" main thread");
}

}
}

B. Anonymous inner class that implements an interface


Defining a Thread by implementing runnable interface

Page 221
https://gits-sln.blogspot.com Durga sir Java Notes

C. Anonymous inner class that defined inside argument

Normal java classes vs anonymous inner classes


1) A normal java class can extends only one class at a time off course anonymous
inner class can extends only one class at a time.
Page 222
https://gits-sln.blogspot.com Durga sir Java Notes

2) A normal java class can implements any no of interface simultaneously but


anonymous inner class can implements only one interface at a time.
3) A normal java class can extends a class and can implements any no of interface
simultaneously but anonymous inner class can extends a class or can implements
an interface but not bot simultaneously.
In normal java class we can write any no of constructor
But in anonymous inner classes we cannot write any constructor explicitly (because the
name of the class and the name of the constructor must be the same but anonymous
inner classes not having any name.
Note- if the requirement is standards and required several times then we should go for
normal top level class.
If the requirement is temporary and the required only once (instant use) then we should
go for anonymous inner class.
Where anonymous inner classes are best suitable?
We can use anonymous inner classes frequently in GUI based application to implements
event handling.

Page 223
https://gits-sln.blogspot.com Durga sir Java Notes

5. Static nested classes


Some time we can declare inner class with static modifiers such type of inner classes are
called static nested classes.
In the case of normal or regular inner class without existing outer class object there is no
chance of existing inner class object that is inner class object is strongly associated with
outer class object.
But in the case of static nested classes without existing outer class object there may be
chance of existing nested class object hence static nested class object is not strongly
associated with outer class object.
public class Outer
{
static class Nested
{
public void m()
{
System.out.println("static nested class method");
}
}
class Inner
{
public void m()
{
System.out.println("non static nested class method");
}
}
public static void main(String[] args)
{
Nested n=new Nested();//Outer class object not required
n.m();
//Outer o=new Outer();
//Inner i=o.new Inner();
Inner i=new Outer().new Inner();//Outer class object required
i.m();
}
}
Output-
static nested class method
non static nested class method

Difference between normal inner class and static nested class


 if we want to create nested class object from outside of outer class then we can
create as follows
Outer.Nested n=new Outer.Nested();

 In normal or regular inner classes we cannot declare any static members.


But in static nested classes we can declare static member including main method hence
we can invoke static nested class directly from command prompt
public class Test

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

public static void main(String[] args)


{
System.out.println("Outer 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);
}
}

public static void main(String[] args)


{
Nested n=new Nested();
n.m();

}
}

Difference between normal or regular inner classes and static nested classes

Normal or regular inner classes Static nested classes


Without existing outer class object there Without existing outer class object there
is no chance of inner class object that is may be a chance of existing static nested
inner class object in strongly associated class object hence static nested class
with outer class object. object is not strongly associated with
outer class object.
In normal or regular inner classes we In static nested classes we can declare

Page 225
https://gits-sln.blogspot.com Durga sir Java Notes

cannot declare static member. static members.


In normal or regular inner class we In static nested classes we can declare
cannot declare main method and hence main method and hence we can invoke
we cannot invoke inner class directly nested class directly from command
from command prompt. prompt.
Form normal or regular inner classes we Form static nested classes we can access
can access both static and non- static only static member of outer class.
member and outer class directly.

Various combination of nested classes and interfaces


Case.1- class inside a class
Without existing of one type of object if there is no chance of existing another type of
object then we can declare a class inside a class.
Example-
University consist of several department. Without existing university there is no chance
of existing of department hence we have to declare department class inside university
class.
class University
{
class Department
{

}
}

Case.2- Interface inside a class


Inside a class if we required multiple implementation of an interface an all these
implementation are related to a particular class then we can define interface inside a
class.
Example-

Page 226
https://gits-sln.blogspot.com Durga sir Java Notes

Case.3- interface inside interface


We can declare interface inside interface
Example- a map is a group of key value pairs and each key value pair is called an entry.
Without existing map object there is no chance of existing entry object. Hence interface
entry is defined inside map interface.

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

class Test11 implements Out


{
public void m1()
{
System.out.println("outer interface mehtod implementaion");
}
}
class Test22 implements Out.Inn
{
public void m2()
{
System.out.println("inner interface mehtod implementaion");
}
}
public class Outer
{
public static void main(String[] args)
{
Test11 t1=new Test11();
t1.m1();
Test22 t2=new Test22();
t2.m2();
}
}

Case.4- class inside interface


If functionality of a class is closely associated with interface then it is highly
recommended to declare class inside interface

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.

Difference between array and collection


Array Collection
Fixed in size Grow able in nature
Memory point of view array is not Collection is recommended.
recommended
Performance point of view array is Collection is not recommended.

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.

Basic term of collection

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)

9 key interface of collection framework


1) Collection (Interface)
a) If we want to represent a group of individual object as a single entity then we
should go for collection.
b) Collection interface defines the most common method which are applicable for any
collection object.
c) In general collection interface is consider as root interface of collection framework.
d) There is no concrete class which implement collection interface directly.
Collection vs collections
I. Collection is an interface if we want to represent a group of individual object as a
single entity then we should go for collection.
II. Collections is a utility class present in java.util package to define several utility
method for collection object like sorting, searching etc.
2) List(interface)
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 allow and insertion order must be persevered then we should go for
list.

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

Difference between list and set

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-

c) Both key and value are object only.


d) Duplicate key are not allowed but value can be duplicated.

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.

The following are legacy character present in collection framework


1. Enumeration(interface)
2. Dictionary(abstract class)
3. Vector(class)
4. Stack(class)
5. Hashtable(class)
6. Properties(class)

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-

No. Method Description


1 public boolean add(E e) It is used to insert an element in this collection.
public boolean addAll(Collection<? It is used to insert the specified collection elements in the
2
extends E> c) invoking collection.
3 public boolean remove(Object element) It is used to delete an element from the collection.
public boolean It is used to delete all the elements of the specified
4
removeAll(Collection<?> c) collection from the invoking collection.
default boolean removeIf(Predicate<? It is used to delete all the elements of the collection that
5
super E> filter) satisfy the specified predicate.
public boolean retainAll(Collection<?> It is used to delete all the elements of invoking collection
6
c) except the specified collection.
7 public int size() It returns the total number of elements in the collection.
It removes the total number of elements from the
8 public void clear()
collection.
public boolean contains(Object
9 It is used to search an element.
element)
public boolean It is used to search the specified collection in the
10
containsAll(Collection<?> c) collection.
11 public Iterator iterator() It returns an iterator.

Page 237
https://gits-sln.blogspot.com Durga sir Java Notes

12 public Object[] toArray() It converts collection into array.


It converts collection into array. Here, the runtime type of
13 public <T> T[] toArray(T[] a)
the returned array is that of the specified array.
14 public boolean isEmpty() It checks if collection is empty.
It returns a possibly parallel Stream with the collection as
15 default Stream<E> parallelStream()
its source.
It returns a sequential Stream with the collection as its
16 default Stream<E> stream()
source.
It generates a Spliterator over the specified elements in the
17 default Spliterator<E> spliterator()
collection.
18 public boolean equals(Object element) It matches two collections.
19 public int hashCode() It returns the hash code number of the collection.

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:

 ListIterator(extends Iterator) is used to iterate over List element. List iterator


is bidirectional iterator. For more details about ListIterator refer Iterators in Java.

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.

 List subList(int fromIndex, int toIndex):This method returns List view of


specified List between fromIndex(inclusive) and toIndex(exclusive).

List interface is implemented by the classes (4 type of classes)


1. ArrayList
2. LinkedList
3. Vector
4. Stack.

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

public class ArrayListDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList l=new ArrayList();
System.out.println(l.size());
l.add("A");

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.

Question- how to get a synchronized version of array list?


By default arraylist is non-synchronized but we can get synchronized version of arraylist
object by using synchronizedList() method of collection class.

Page 240
https://gits-sln.blogspot.com Durga sir Java Notes

public static List synchronizedList(List l)


Example-
ArrayList l=new ArrayList();
List l1=Collections.synchronizedList(l);
Here l1 is synchronized and l is non-synchronized
Similarly we can get synchronized version of Set and Map object by using the following
method of collection class.
public static set synchronizedSet(Set s)
public static Map synchronizedMap(Map m)
2. LinkedList
a) The underline data structure is double linked list.
b) Insertion order is preserved.
c) Duplicate object are allowed.
d) Heterogeneous object allowed.
e) Null insertion is possible.
f) Linked list implement serializable and clone able interface but not random access.
g) Linked list is the best choice if our frequent operation is insertion or deletion in the
middle.
h) Linked list is the worst choice if our frequent operation is retrieval operation.
Constructor of LinkedList
1. LinkedList l=new LinkedList();
Create an empty LinkedList object.
2. LinkedList l=new LinkedList(Collection c);
Create an equivalent LinkedList object for the given Collection.
Usually we can use LinkedList to develop stacks and queues to provide support for this
requirement LinkedList class defined following specific methods.
Methods of Java LinkedList
void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.
Object getFirst() It is used to return the first element in a list.
Object getLast() It is used to return the last element in a list.
Object removeFirst() It removes and returns the first element from a list.
Object removeLast() It removes and returns the last element from a list.

Example-
import java.util.*;
public class ArrayListDemo {

Page 241
https://gits-sln.blogspot.com Durga sir Java Notes

public static void main(String[] args) {


// TODO Auto-generated method stub
LinkedList l=new LinkedList();
System.out.println(l.size());
l.add("Prabhakar");
l.add(10);
l.add(null);
l.add("Prabhakar");
System.out.println(l);
l.set(0, "Software");
System.out.println(l);
l.add(0, "Pathak");
System.out.println(l);
l.removeLast();
System.out.println(l);
l.addFirst("javaclass");
System.out.println(l);
}
}

Output-
0
[Prabhakar, 10, null, Prabhakar]
[Software, 10, null, Prabhakar]
[Pathak, Software, 10, null, Prabhakar]
[Pathak, Software, 10, null]
[javaclass, Pathak, Software, 10, null]

Difference between ArrayList and LinkedList


ArrayList LinkedList
Best choice if our frequent operation is Best choice if our frequent operation is
retrieval operation insertion or deletion in the middle.
Worst choice if our frequent operation is Worst choice if our frequent operation is
insertion or deletion in the middle retrieval operation.
because internally several shift operation
is performed.
The element will be stored in consecutive The element won’t be store in
memory location and hence retrieval consecutive memory location and hence
operation will easy. retrieval operation are difficult and
complex.

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

f) It implement seriliazible cloneable and random access interface.


g) Every method present in the vector is thread synchorinized and hence vector
object is thread safe.
Constructor of Vector
I. Vector v=new Vector();
Creates an empty vector object with default initial capacity 10.
Once vector reaches it max capacity then a new vector object will be created with
New capacity=current capacity*2

II. Vector v=new Vector(int initial_capacity);


III. Vector v=new Vector(int initial_capacity, int incremental_capacity);
IV. Vector v=new Vector(Collection c);

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

Some other method


I. int size()
Returns the number of components in this vector.
II. int capacity()
Returns the current capacity of this vector.
III. Enumeration elements()
Returns an enumeration of the components of this vector.

Example-
import java.util.*;

public class VectoDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
Vector v=new Vector();
System.out.println(v.capacity());
for(int i=0;i<10;i++)
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v);
}

}
Output-
10
10
20
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A]
import java.util.*;

public class ArrayListDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
Vector v=new Vector(10,5);
System.out.println(v.capacity());
for(int i=0;i<10;i++)
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v);
}

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

public class ArrayListDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
Stack s=new Stack();
s.push("A");
s.push("B");
s.push("C");
System.out.println(s);
System.out.println(s.search("A"));
System.out.println(s.search("z"));
System.out.println(s.peek());
System.out.println(s.pop());
System.out.println(s);
System.out.println(s.empty());
}

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

public class EnumerationDemo {


public static void main(String[] args) {

Page 246
https://gits-sln.blogspot.com Durga sir Java Notes

// TODO Auto-generated method stub


Vector v=new Vector();
System.out.println(v.capacity());
for(int i=0;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v);
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer I=(Integer)e.nextElement();
if(I%2==0)
System.out.println(I);
}
System.out.println(v);
System.out.println(v.capacity());
}
}
Output-
10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0
2
4
6
8
10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
20

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

// same as next() method of Iterator


public Object next();

// Returns the next element index


// or list size if the list iterator
// is at the end of the list
public int nextIndex();

// **for Backward direction**


// Returns true if the iteration has more elements
// while traversing backward
public boolean hasPrevious();

// Returns the previous element in the iteration


// and can throws NoSuchElementException
// if no more element present
public Object previous();

// Returns the previous element index


// or -1 if the list iterator is at the
// beginning of the list
public int previousIndex();

// **Other Methods**
// same as remove() method of Iterator
public void remove();

// Replaces the last element returned by


// next() or previous() with the specified element
public void set(Object obj);

// Inserts the specified element into the list at


// position before the element that would be returned
// by next(),
public void add(Object obj);

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

Properties Enumeration Iterator ListIterator


, remove(),
set(Object obj),
and add(Object
obj)
Is it
Yes No No
legacy?
ListIterator ltr =
Vector v = new
Iterator itr = col.iterator(); list.listIterator()
Vector();
For ;
example Where col = any collection
Enumeration e =
class Where list =
v.elements();
any List objects

Internal implementation of cursor


import java.util.*;
public class ArrayListDemo
{
public static void main(String[] args)
{
Vector v=new Vector();
Enumeration e=v.elements();
Iterator itr=v.iterator();
ListIterator litr=v.listIterator();

System.out.println(e.getClass().getName());
System.out.println(itr.getClass().getName());
System.out.println(litr.getClass().getName());
}

Output-

java.util.Vector$1 (1 means anynomous inner class present in vector class)


java.util.Vector$Itr (Itr means Iterator inner class present in vector class)
java.util.Vector$ListItr (ListItr means ListIterator inner class present in vector class)

Page 251
https://gits-sln.blogspot.com Durga sir Java Notes

Set

 It is the child interface if collection.


 If we want to represent a group of individual object where duplicate are not
allowed and insertion order is not preserved then we should go for 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

Fill ratio or load factor


After filling how much ratio a new hash set object will be created this ratio is called filled
ratio or load factor example fill ratio 0.75 means after filling 75% ratio a new hashset
object will be created.
Example-
import java.util.*;

public class HashSetDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet h=new HashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z"));
System.out.println(h);
}
}

Output-
false
[null, D, B, C, 10, Z]

LinkedHashSet

 It is child class of hashset.


 It is excetelly same as hashset (including constructor and method) except the
following difference.

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]

That means insertion order preserved.

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.

Methods of Sorted Set interface:


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.

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

This program given runtime exception: ClassCastException

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.

 An object is said to comparable if and only if corresponding class implement


comparable interface
 Sting class and all wrapper classes already implement comparable interface but
stringbuffer class doesn’t implement comparable interface hence we got
classcastexception in the above example.
Comparable interface
It is present in java.lang package and it contain only one method compareTo()
public int compareTo(Object obj)
obj1.compareTo(obj2)
1. return –ve if obj1 has to come before obj2
2. return +ve if obj1 has to come after obj2
3. return 0 if obj1 and obj2 are equal
import java.util.*;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet h=new TreeSet();

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)

Whenever we are implementing comparator interface compulsory we should provide


implantation only for compare method and we are not required to provide
implementation for equals() method because it is already available in our class form
object class through inheritance.
Write a program to insert interger object into the treeset where the sorting
order is descending order.
import java.util.*;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub

Page 257
https://gits-sln.blogspot.com Durga sir Java Notes

TreeSet h=new TreeSet(new MyComparator());//line-1


h.add(10);
h.add(0);
h.add(15);
h.add(5);
h.add(20);
h.add(20);
System.out.println(h);
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
Integer I1=(Integer)obj1;
Integer I2=(Integer)obj2;
if(I1<I2)
return +1;
else if(I1>I2)
return -1;
else
return 0;
}

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

Write a program to insert stringbuffer object in a treeset where sorting order is


alphabetical order.

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-

[chiru 50, nag 100, venki 150, balaiah 200]


[balaiah 200, chiru 50, nag 100, venki 150]

Comparison of comparable and comparator

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.

Comparison table of set implemented classes

Properties HashSet LinkedHahSet TreeSet


Underlaying HashTable A combination of Balanced tree
datastructure LinkedList and
HashTable
Duplicate Object Not allowed Not allowed Not allowed
Insertion order Not preserved preserved Not preserved
Sorting order Not applicable Not applicable Applicable
Heterogeneous Allowed Allowed Not allowed
object
Null acceptance Allowed Allowed Empty tree set as
first element null
is allowed.

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)

 Map is not child interface of collection.


 If we want to represent a group of object as a key value pairs then we should go
for map.

 Both key and value is object only.


 Duplicate key are not allowed but value can be duplicated.
 Each key value pair is called entry hence map is considered as a collection of entry
object.

Page 264
https://gits-sln.blogspot.com Durga sir Java Notes

Map interface method


Sr.No. Method & Description
void clear( )
1
Removes all key/value pairs from the invoking map.
boolean containsKey(Object k)
2
Returns true if the invoking map contains k as a key. Otherwise, returns false.
boolean containsValue(Object v)
3
Returns true if the map contains v as a value. Otherwise, returns false.
Set entrySet( )
4
Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This
method provides a set-view of the invoking map.
boolean equals(Object obj)
5
Returns true if obj is a Map and contains the same entries. Otherwise, returns false.
Object get(Object k)
6
Returns the value associated with the key k.
int hashCode( )
7
Returns the hash code for the invoking map.
boolean isEmpty( )
8
Returns true if the invoking map is empty. Otherwise, returns false.
Set keySet( )
9
Returns a Set that contains the keys in the invoking map. This method provides a set-view of the
keys in the invoking map.
Object put(Object k, Object v)

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.

Object put(Object k, Object v)

To add key value pair to the map.


If the specified key is already available then old value will be replaced with new value
and old value will be return.

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

2. HashMap(int initial capacity): It creates a HashMap instance with specified


initial capacity and load factor 0.75.
HashMap m=new HashMap(int initial capacity);

3. HashMap(int initial capacity, float loadFactor): It creates a HashMap instance


with specified initial capacity and specified load factor.
HashMap m=new HashMap(int initial capacity, float loadFactor);

4. HashMap(Map map): It creates instance of HashMap with same mappings as


specified map.
HashMap m=new HashMap(Map map);

Example-
import java.util.*;

public class HashMapDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap m=new HashMap();
m.put("chiranjeevi",700);
m.put("balaiah",800);
m.put("venkatesh",200);
m.put("nagarjuna",500);
System.out.println(m);//{nagarjuna=500, venkatesh=200, balaiah=800,
chiranjeevi=700}
System.out.println(m.put("chiranjeevi", 1000));//700
System.out.println(m);//{nagarjuna=500, venkatesh=200, balaiah=800,
chiranjeevi=1000}
Set s=m.keySet();

Page 267
https://gits-sln.blogspot.com Durga sir Java Notes

System.out.println(s);//[nagarjuna, venkatesh, balaiah, chiranjeevi]


Collection c=m.values();
System.out.println(c);//[500, 200, 800, 1000]
Set s1=m.entrySet();
System.out.println(s1);//[nagarjuna=500, venkatesh=200, balaiah=800,
chiranjeevi=1000]
Iterator itr=s1.iterator();
while(itr.hasNext())
{
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey()+"........"+m1.getValue());
if(m1.getKey().equals("nagarjuna"))
{
m1.setValue(1000);
}
}
System.out.println("m="+m);//{nagarjuna=1000, venkatesh=200, balaiah=800,
chiranjeevi=1000}
}

Difference between HashMap and HashTable

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.

How to get synchronized version of HashMap?


By default HashMap object is not synchronized but we can get synchronized version by
using SynchronizedMap() of collection classes.
Map m=Collections.synchronizedMap(HashMap hm);
Where m is synchronized but hm is non-synchronized.

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}

That is insertion order is preserved.


Note-
LinkedHashSet and LinkedHashMap are commonly used for developing chche based
application.
Difference between == operator and .equals() method
In general == operator meant for reference comparison or address comparison whereas
.equals() method meant for content comparison.
Integer I1=new Integer(10);
Integer I2=new Integer(10);
Sop(I1==I2);//false
Sop(I1.equals(I2));//true

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

I1 and I2 are duplicate keys because I1.equals(I2) return true.


If we replace HashMap with IdentityHashMap then I1 and I2 are not duplicate Keys
because I1==I2 return false.
In this case output is
IdentityHashMap m=new IdentityHashMap();
Integer I1=new Integer(10);
Integer I2=new Integer(10);
m.put(I1, "pawan");
m.put(I2, "kalyan");
System.out.println(m);// {10=kalyan, 10=pawan}

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

// 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";
}
// finalize method
public void finalize()
{
System.out.println("Finalize method is called");
}
}

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

Constructs an empty treemap that will be sorted using


TreeMap( )
the default natural order of its keys.

TreeMap(Comparator Constructs an empty tree-based map that will be


comp) customized sorted order using the Comparator comp.

Initializes a treemap with the entries from m, which will


TreeMap(Map m)
be sorted using the natural order of the keys.

Initializes a treemap with the entries from the


TreeMap(SortedMap
SortedMap sm, which will be sorted in the same order as
sm)
sm.

Example- A program for default natural sorting order


import java.util.*;

public class HashMapDemo {

Page 273
https://gits-sln.blogspot.com Durga sir Java Notes

public static void main(String[] args) {


// TODO Auto-generated method stub
TreeMap m=new TreeMap();
m.put(100, "zzz");
m.put(103, "yyy");
m.put(101, "xxx");
m.put(104, 106);
m.put(102,null);
//m.put("FFFF", "xxxx");//ClassCastException
//m.put(null, "xxxx");//NullPointerException

System.out.println(m);

Output-

{100=zzz, 101=xxx, 102=null, 103=yyy, 104=106}

Example- A program for customize sorting order


package com.java.pptest;

import java.util.*;

public class TreeMapDemo {

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

{zzz=30, xxx=10, lll=40, aaa=20}

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

 Heterogeneous object are allowed for both keys and values.


 Null keys not allowed for both key and value otherwise we will get runtime
exception saying nullpoinerexception.
 It implement serializable and clone able interface but not random access.
 Every method present in hashtable is synchronized and hence hashtable object is
threadsafe.
 Hashtable is the best choice if our frequent operation is search operation.
Constructor of HashTable

Sr.No Constructor & Description


Hashtable( )

This is the default constructor of the hash table it instantiates the Hashtable
1
class.

Default initial capacity-11 and default fill ratio- 0.75


Hashtable(int initialcapacity)
2
This constructor accepts an integer parameter and creates a hash table that
has an initial size specified by integer value size.

Hashtable(int initialcapacity, float fillRatio)

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

public class TreeMapDemo {

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

{6=C, 10=F, 5=A, f=D, 2=B, 17=E}


Here 6,10,5,f,2,17 by default work in hexadecimal format.

Page 276
https://gits-sln.blogspot.com Durga sir Java Notes

If we configure initial capacity as 25 then

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

Following is the list of constructors provided by the properties class.

Sr.No. Constructor & Description


Properties( )
1
This constructor creates a Properties object that has no default values.
Properties(Properties propDefault)
2
Creates an object that uses propDefault for its default values. In both cases,
the property list is empty.

Properties define the following methods(where keypname and valuepvalue) –

String getProperty(String key)

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.

Object setProperty(String key, String value)

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

Queue 1.5 version inhancement (queue interface)


 It is the child interface of collection.

 If we want to represent a group of individual object prior to processing then we


should go for queue.
For example-
Before sending sms message all mobile number in some data structure. In which order
we added mobile number in same order only message should be send or delivered for
these FIFO requirement queue is the best choice.

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.

Methods of Java Queue Interface


Method Description
boolean It is used to insert the specified element into this queue and return
add(object) true upon success.
boolean
It is used to insert the specified element into this queue.
offer(object)
Object remove() It is used to retrieves and removes the head of this queue.
It is used to retrieves and removes the head of this queue, or
Object poll()
returns null if this queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this queue.
It is used to retrieves, but does not remove, the head of this queue,
Object peek()
or returns null if this queue is empty.

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.

Constructors of PriorityQueue class

 PriorityQueue(): Creates a PriorityQueue with the default initial capacity (11)


that orders its elements according to their natural ordering.
 PriorityQueue(Collection c): Creates a PriorityQueue containing the elements in
the specified collection.
 PriorityQueue(int initialCapacity): Creates a PriorityQueue with the specified
initial capacity that orders its elements according to their natural ordering.
 PriorityQueue(int initialCapacity, Comparator c): Creates a PriorityQueue
with the specified initial capacity that orders its elements according to the specified
comparator.
 PriorityQueue(PriorityQueue c): Creates a PriorityQueue containing the
elements in the specified priority queue.

Page 281
https://gits-sln.blogspot.com Durga sir Java Notes

 PriorityQueue(SortedSet s): Creates a PriorityQueue containing the elements in


the specified sorted set.

import java.util.*;

public class PriorityQueueDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
PriorityQueue pq=new PriorityQueue();
System.out.println(pq.peek());
//System.out.println(pq.element());
for(int i=0;i<=10;i++)
{
pq.offer(i);
}
System.out.println(pq);
System.out.println(pq.peek());
System.out.println(pq.poll());
System.out.println(pq);

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

1.6 version enhancement in collection framework


As a part of 1.6 version the following two concept introduced in collection framework

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

public class NavigableSetDemo1 {

/**
* @param args
*/

Page 283
https://gits-sln.blogspot.com Durga sir Java Notes

public static void main(String[] args) {


// TODO Auto-generated method stub
TreeSet<Integer> t=new TreeSet<Integer>();
t.add(1000);
t.add(2000);
t.add(3000);
t.add(4000);
t.add(5000);
System.out.println(t);
System.out.println(t.ceiling(2000));
System.out.println(t.higher(2000));
System.out.println(t.floor(3000));
System.out.println(t.lower(3000));
System.out.println(t.pollFirst());
System.out.println(t.pollLast());
System.out.println(t.descendingSet());
System.out.println(t);
System.out.println(t.descendingIterator());

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

public class NavigableSetDemo1 {

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

Sorting the element of a list


1. public static void sort(List l)
 Use this method to sort according to default natural sorting order.
 In this case list should be compulsory contain homogeneous and comparable
otherwise runtime exception classcastexception.
 List should not contain null otherwise we will get nullpointerexcetion.
import java.util.*;

public class NavigableSetDemo1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
ArrayList l=new ArrayList();
l.add("Z");
l.add("A");
l.add("K");
l.add("N");
System.out.println("Befor soritng"+l);
Collections.sort(l);
System.out.println("After soritng"+l);

Output-

Befor soritng[Z, A, K, N]
After soritng[A, K, N, Z]

2. public static void sort(List l,Comparator c)


 to sort based on customize sorting order
import java.util.*;

public class NavigableSetDemo1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
ArrayList l=new ArrayList();
l.add("Z");
l.add("A");
l.add("K");
l.add("N");
System.out.println("Befor soritng"+l);// Befor soritng[Z, A, K, N]
Collections.sort(l, new MyComparator2());
System.out.println("After soritng"+l);// After soritng[Z, N, K, A]

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

Searching the element of a list


1) public static int binarySearch(List l, Object target)
If the list is sorted according to default natural sorting order then we have to use this
method.
2) public static int binarySearch(List l, Object target, Comparator c)
If the list is sorted according to customize sorting order then we have to use this
method.

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

public class NavigableSetDemo1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
ArrayList l=new ArrayList();
l.add("Z");
l.add("A");
l.add("M");
l.add("K");
l.add("a");
System.out.println(l);
Collections.sort(l);
System.out.println(l);
System.out.println(Collections.binarySearch(l, "Z"));
System.out.println(Collections.binarySearch(l, "J"));
}

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

public class NavigableSetDemo1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
ArrayList l=new ArrayList();
l.add(15);
l.add(0);
l.add(20);
l.add(10);
l.add(5);
System.out.println(l);
Collections.sort(l,new MyComparator2());
System.out.println(l);
System.out.println(Collections.binarySearch(l,10,new MyComparator2()));
System.out.println(Collections.binarySearch(l,13,new MyComparator2()));
System.out.println(Collections.binarySearch(l,17));
}

class MyComparator2 implements Comparator


{
public int compare(Object obj1, Object obj2)
{
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
return i2.compareTo(i1);
}
}
Output-
[15, 0, 20, 10, 5]
[20, 15, 10, 5, 0]
2
-3
-6

Page 288
https://gits-sln.blogspot.com Durga sir Java Notes

Note- for the list of n element , in the case of binarysearch method


1. Successful search result range 0 to (n-1)
2. Unsuccessful search result range -(n+1) to -1
3. Total result range -(n+1) to (n-1)
Example-

Reversing element of list


Collections class define the following reverse method to reverse the element of list
public static void reverse(List l)
example-
import java.util.*;

public class ReverseListDemo1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
ArrayList l=new ArrayList();
l.add(15);
l.add(0);
l.add(20);

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

public class Collectionsorting


{
public static void main(String[] args)
{
// Create a list of Integers
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(30);
al.add(20);
al.add(10);
al.add(40);
al.add(50);

/* Collections.sort method is sorting the


elements of ArrayList in descending order. */
Collections.sort(al, Collections.reverseOrder());

// Let us print the sorted list


System.out.println("List after the use of Collection.reverseOrder()"+
" and Collections.sort() :\n" + al);
}
}

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

public class ArraySortDemo1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
int[] a={10,5,20,11,6};
System.out.println("premitive array before sorting");
for(int a1:a)
{
System.out.print(a1+"\t");
}
Arrays.sort(a);
System.out.println("\n premitive array after sorting");
for(int a1:a)
{
System.out.print(a1+"\t");
}
//-------------------------------------------------
String[] s={"A","Z","B"};
System.out.println("\n object array before sorting");
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");
}
Arrays.sort(s,new MyComparator33());
System.out.println("\n Object array after sorting by comparator");
for(String s1:s)
{
System.out.print(s1+"\t");
}
}

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

premitive array before sorting


10 5 20 11 6
premitive array after sorting
5 6 10 11 20
object array before sorting
A Z B
object array after sorting
A B Z
Object array after sorting by comparator
Z B A

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.

2. Searching element of array


Arrays class define the following binary search method
a) public static int binarySearch(primitive[] p, primitive target)
b) public static int binarySearch(Object[] a, Object target)
c) public static int binarySearch(Object[] a, Object target, Comparator c)
note- all rules of array class binary search method are exactly same as collection class
binary search method.
package com.java.ppteSst;

import static java.util.Arrays.*;


import java.util.Arrays;
import java.util.Comparator;

public class ArraySearchDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a={10,5,20,11,6};
System.out.println("before sorting");
for(int a1:a)
{
System.out.print(a1+"\t");
}
Arrays.sort(a);
System.out.print("\nafter sorting \n");
for(int a1:a)
{
System.out.print(a1+"\t");
}
System.out.print("\nSearch(a, 6):");
System.out.println(Arrays.binarySearch(a, 6));
System.out.print("\nSearch(a, 14):");
System.out.println(Arrays.binarySearch(a, 14));
//------------------------------------------------
String[] s={"A","Z","B"};
System.out.println("\n object array before sorting");

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

class MyComparator111 implements Comparator


{
public int compare(Object o1, Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s2.compareTo(s1);
}
}

Output-

before sorting
10 5 20 11 6
after sorting
5 6 10 11 20
Search(a, 6):1

Search(a, 14):-5

object array before sorting


A Z B
object array after sorting
A B Z
Search(s, Z):2

Search(s, S):-3
0
-2
-2

Page 293
https://gits-sln.blogspot.com Durga sir Java Notes

3. Conversion of Array to list


public static list asList(Object[] a)
this method won’t create an independent list object for the existing array we are getting
list view.

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;

public class ArraySearchDemo {


public static void main(String[] args) {
String[] s={"A","Z","B"};
List l=Arrays.asList(s);
System.out.println(l);
s[0]="K";
System.out.println(l);
l.set(1, "L");
for(String s1:s)
{
System.out.print(s1+"\t");
}

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

Process based multitasking


Executing several tasks simultaneously where each task is separate independent
program (process) is called process based multitasking.
Example- while typing a java program in the editor we can listen audio song form same
system at the same time we can download a file from net all these task will be executed
simultaneously and independent of each other hence it is process based multitasking.
Process based multitasking is best suitable at OS level.

Thread based multitasking


Executing several tasks simultaneously where each task is separate independent part of
the same program is called thread based multitasking and each independent part is
called a thread.

Page 295
https://gits-sln.blogspot.com Durga sir Java Notes

Thread based multitasking is best suitable at programmatic level.


Whether it is process based of thread based the main objective of multitasking is to
reduce response time of the system and to improve performance.
The main important application area of multi-threading are
a) To develop multimedia graphic
b) To develop animation
c) To develop video games
d) To develop web server and application server etc.
When compared with old language developing multithreaded application in java is very
easy because java provide in build support for multithreading with rich API[thread(API
class),Runnable(I),thread group……)]

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

This program not given same result always.


Case-1: Thread scheduler
It is the part of JVM .
It is responsible to schedule threads that is if multiple thread are waiting to get the
chance of execution then in which order thread will be executed is decided by thread
scheduler.
We cannot except exact algorithm followed by thread scheduler it is varied from JVM to
JVM we cannot except thread execution order and exact output.
Hence whenever come the situation of multithreading there is no guarantee for exact
output but we can provide several possible output.
The following are various possible outputs for the above program

Page 298
https://gits-sln.blogspot.com Durga sir Java Notes

Case-2 difference between t.start() and t.run()


In the case of t.start() a new thread will be created which is responsible for the
execution of run() method.
But in the case of t.run() a new thread won’t be created and run() will be executed just
like a normal method will be
Hence in the above program if we replace t.start() with t.run() then the output is

Case-3: Importance of Thread class start() method


Thread class start() method is responsible to register the thread with the thread
scheduler and all other mandatory activity hence without execution thread class start()
method there is no chance of starting new thread in java due to this thread class start()
method is consider as heart of multithreading.
start()

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

Case-4: overloading of the run() method


Overloading of the run() is always possible but thread class start() method can invoke
no-arg run() method the other overloaded method we have to call explicitily like a
normal method call.

Case-5: if we are not overriding the run() method


If we are not overriding run() method then thread class run() method executed which
has empty implementation and hence we won’t get any output

Page 300
https://gits-sln.blogspot.com Durga sir Java Notes

Note- it is highly recommended to override run() method otherwise dot’s go for


multithreading concept.
Case-6: overriding of start() method
If we override start() method then our start() method will be executed just like a normal
method call and new thread won’t be created.
class MyThread extends Thread
{
public void start()
{
System.out.println("start method");
}

public void run()


{
System.out.println("run method");
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread t=new MyThread();
t.start();
System.out.println("main method");
}
}

Output-
start method
main method
these output is produced by main thread
372

Note- it is not recommended to override start() method otherwise don’t go for


multithreading concept.
Case-7:
class MyThread extends Thread
{
public void start()
{
super.start();//it is used to call thread class start() method
System.out.println("start method");
}
public void run()
{
System.out.println("run method");
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread t=new MyThread();
t.start();
System.out.println("main method");

Page 301
https://gits-sln.blogspot.com Durga sir Java Notes

}
}

Case-8: Life cycle of Thread

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

b) By implementing runnable interface


we can define a thread by implementing runnable interface.
Runnable interface present in java.lang package and contain only one method
public void run() method.

class MyRunnable implements Runnable//defining a thread


{
public void run()
{
for(int i=0;i<10;i++)//job of thread execute by child thread
{
System.out.println("child thread");
}
}
}
public class ThreadDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);//r is target runnable
t.start();
for(int i=0;i<10;i++)//execute by main thread
{
System.out.println("main thread");
}
}

We will get mixed output and we cannot tell exact output.


Case study
MyRunnable r=new MyRunnable();

Thread t1=new Thread();

Thread t2=new Thread(r);

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.

Which approach is best to define a thread ?


Among two base of defining a thread implements runnable approach is recommended.
In the first approach our class always extends thread class there is no chance of
extending any other class hence we are missing inheritance benefit.
But in the second approach while implementing runnable interface we can extends any
other class hence we won’t miss any inheritance benefit.
Because of above reason implementing runnable interface is recommended then
extending thread class.

Thread class constructor


Sr.No. Constructor & Description
Thread()
1
This allocates a new Thread object.
Thread(Runnable r)
2
This allocates a new Thread object.
Thread(Runnable r, String name)
3
This allocates a new Thread object.

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.

Druga’s approach to define a thread (not recommended to use)


class MyThread extends Thread
{ public void run()
{
System.out.println("run method");
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread t=new MyThread();
Thread t1=new Thread(t);
t1.start();
System.out.println("main method");
}
}

Output-

main run
method method
run main
method method

Getting and setting a name of Thread


Every thread in java has some name it may be default name generated by JVM or
customized name provided by programmer.
We can get and set name of a thread by using the following two method of thread class
1. public final String getName();
2. public final void setName(String name);
Example-
class MyThread extends Thread
{ public void run()
{
System.out.println("run 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

We can get current executing thread object by Thread.currentThread()


class MyThread extends Thread
{ public void run()
{
System.out.println("run method executed by the
thread:"+Thread.currentThread().getName());
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread t=new MyThread();
t.start();
System.out.println("main method executed by the
thread:"+Thread.currentThread().getName());
}
}

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.

Get and Set Thread Priority:


1. public final int getPriority(): java.lang.Thread.getPriority() method returns priority
of given thread.
2. public final void setPriority(int newPriority): java.lang.Thread.setPriority()
method changes the priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond minimum(1)
and maximum(10) limit.

class MyThread extends Thread


{ public void run()
{
System.out.println("run method executed by the
thread:"+Thread.currentThread().getName());
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getPriority());//given default priority
of main thread
//Thread.currentThread().setPriority(15);//RE:java.lang.IllegalArgumentException
Thread.currentThread().setPriority(7);//set the priority of main thread
MyThread t=new MyThread();
System.out.println(t.getPriority());//inherit the priority of main thread in
child thread
}
}

Output-

5
7

If we comment setPriority(7) line then child thread priority will be become 5.

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.

Method to prevent thread execution


1. yield()
Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and starts
its execution and thread t2 and t3 are in Ready/Runnable state. Completion time for
thread t1 is 5 hour and completion time for t2 is 5 minutes. Since t1 will complete its
execution after 5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such
scenarios where one thread is taking too much time to complete its execution, we need a
way to prevent execution of a thread in between if something important is pending.
yeild() helps us in doing so.
 This method causes to pause current executing thread to give the chance for waiting
thread of same 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

class MyThread extends Thread


{ public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("child thread");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class ThreadDemo1 {
public static void main(String[] args) throws InterruptedException {
MyThread t=new MyThread();
t.start();
//t.join();
t.join(5000);
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}

Case-1: waiting of child thread until completing main thread


If we using only t.join(5000); then output-
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
child thread
child thread
Case-2: waiting of main thread until completing of child thread
but if we are using only t.join(); then output-
child thread
child thread

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

//sleep for the specified number of milliseconds plus nano seconds


public static void sleep(long millis, int nanos)
throws InterruptedException
every sleep() throws interruptedexception, which is checked exception hence whenever
we are using sleep() method compulsory we should handle interruptedexception either
by try catch or by throws keyword otherwise we will get compile time error.

Page 313
https://gits-sln.blogspot.com Durga sir Java Notes

public class ThreadDemo2 {


public static void main(String[] args) throws InterruptedException {
for(int i=0;i<5;i++)
{
System.out.println("Slide-"+i);
Thread.sleep(2000);
}
}
}

How a Thread can interrupt another Thread


A thread can interrupt a sleeping thread or waiting thread by using interrupt method of
thread class.
public void interrupt();
class MyThread1 extends Thread
{
public void run()
{
try{
for(int i=0;i<100;i++)
{
System.out.println("I am lazy Thread");
Thread.sleep(2000);
}
}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");
}
}

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.

Comparison of yield(), join() and sleep()

property yield() join() sleep()

Page 315
https://gits-sln.blogspot.com Durga sir Java Notes

If a thread wants to If a thread wants to If a thread does not


pass its execution to wait until want to perform any
give chance to completing of some operation for a
purpose
remaining threads of other thread then particular amount of
same priority then we we should go for time, then it goes for
should go for yield() join() sleep()
Is it
NO YES YES
overloaded?
Is it final? NO YES NO
Is it throws? NO YES YES
sleep(long ms)-
>native & sleep (long
Is it native? YES NO
ms, int ns)-> non
native
Is it static? YES NO YES

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

So lock concept is implementing based on object but not based on method.


Every java object showing two type of area
1) Synchronized area
This area can be accessed by only one thread at a time.
2) Non-synchronized area
This area can be accessed by any no of thread at a time simultaneously.
class X
{
Synchronized area
{
Wherever we are performing update operation (add/remove/delete/replace)
i.e. state of object is changing.
}
Non-synchronized area
{
Wherever object state won’t be changed like read operation.
}
}

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

 If multiple threads are operating on multiple java objects then synchronization is


not required.
Class level lock
 Every class in java has a unique lock which is also known as class level lock.
 If a thread wants to execute a static synchronized method then thread required
class level lock.
 Once thread got class level lock then it is allowed to execute any static
synchronized method of that class
 Once method execution complete automatically thread releases lock
While a thread executing static synchronized method the remaining thread are not
allowed to execute any static synchronized method of that class simultaneously but
reaming thread are allowed to execute the following method simultaneously
1. Normal static method
2. Synchronized instance method
3. Normal instance method

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

Object level lock vs class level lock


Object level lock

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

System.out.println("Synchronized block " + Thread.currentThread().getName() + "


end");
}
}
public static void main(String[] args) {
ClassLevelLockTest test1 = new ClassLevelLockTest();
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test1);
ClassLevelLockTest test2 = new ClassLevelLockTest();
Thread t3 = new Thread(test2);
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
}
Output
t3
t2
t1
Synchronized block t3
Synchronized block t3 end
Synchronized block t2
Synchronized block t2 end
Synchronized block t1
Synchronized block t1 end

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
}

2. To get lock of particular object ‘b’

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

Which of thefollowing is valid?


 If a threads calls wait method immediately it will enter into waiting state without
releasing any lock ---------------------------------------invalid
 If a thread calls wait method it released the lock of that object but may not
immeditaly ----------------------------------------------------------invalid
 If a thread wait mentod on any object it releasesall lock acquired by thethread and
the immediately enter into waiting state------------------------------------invalid
 If a thread call wait mentod on any objedct it immediately realeases thelock of
particular object and enter into waiting state-----------------------------valid
 If a thread call notify() method on any object it immediately releases the lock of
particular object-------------------------------------------------invalid
 If threadcall notify() method on any objct it immediately releases the lock of that
object but may not immediately--------------------------------------
 Public final void wait() throws InterruptedException
 Public final native void wait(long ms) throws InterruptedException
 Public final void wait(long ms, int ns) throws InterruptedException
 Public final native void notify()
 Public final native void notifyAll()
Note-
Every wait() method throws interrupted Exception which is checked exception hence
whenever we are using wait() method compulsory handle this interrupt exception either
by try catch or by throws keyword otherwise we will get compile time error.

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

main thread trying to call wait method


child thread start calculation
child thread trying to giving notification
main thread got notification call
5050

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();
b.sleep(10000);
//System.out.println(b);
synchronized(b)
{
System.out.println("main thread trying to call wait method");//step-1
b.wait(10000);
System.out.println("main thread got notification call");//step-4
System.out.println(b.total);//step-5
}
}

}
Output- first check by using only b.sleep(10000); then add b.wait(10000); and check

Producer and consumer problem


Producer thread is responsible to produce item to the queue and consumer thread is
responsible to consume items from the queue.
If queue is empty then consumer thread will call wait method and enter into waiting
state.
After producing items to the queue producer thread is responsible to call notify() method
then waiting consumer will get that notification and continue its execution with updated
items.

Page 328
https://gits-sln.blogspot.com Durga sir Java Notes

Difference between notify() and notifyAll()


We can use notify() method to give the notification for only one waiting thread. If
multiple thread are waiting then only one thread will be notify and remaining thread
have to wait for further notification. Which thread will be notify we cannot expect its
depends on JVM.
We can use notifyAll() method to give the notification for all waiting thread of a
particular object . even though multiple thread notified but execution will be performed
one by one because thread required lock and only one lock is available.
Note-
On which object we are calling wait method thread required lock of that particular object
for example if we are calling wait method on s1 then we have to get lock of s1 object but
nots3 object.

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

public class DeadlockDemo {


A a=new A();
B b=new B();
DeadlockDemo d1=new DeadlockDemo();
public void m1()
{
this.start();
a.d1(b);//this line executed by main thread
}
public void run()

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.

Default nature of a thread


By default the main thread is always non-daemon and for all remaining thread daemon
nature will be inherited form parent to child that is the parent thread is daemon then
automatically child thread is also daemon and it parent thread is non-daemon then
automatically child thread is also non-daemon.
Note- it is impossible to change daemon nature of main thread because it is already
started by JVM at beginning.
package com.java.ppteSst;
class MyThreadA extends Thread

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 {

public static void main(String[] args) {


// TODO Auto-generated method stub
System.out.println(Thread.currentThread().isDaemon());//false
//Thread.currentThread().setDaemon(true);
MyThreadA t=new MyThreadA();
System.out.println(t.isDaemon());//false
t.setDaemon(true);
System.out.println(t.isDaemon());//true

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 {

public static void main(String[] args) {


MyThreadA t=new MyThreadA();
t.setDaemon(true);
t.start();
System.out.println("end of main thread");

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

end of main thread end of main thread child thread


child thread end of main thread

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.

How to stop a thread?


We can stop a thread execution by using stop() method of thread class.
public void stop();
if we call stop method then immediately the thread will enter into death state. Any
where stop method is deprecated and not recommended to use.

How to suspend and resume of a thread?


 We can suspend a thread by using suspend() method of thread class then
immediately the thread will be enter into suspended state.
 We can resume a suspended thread by using resume method of thread class then
suspend thread can continue its execution.
 public void suspend();
 public void resume();
Anywhere these methods are deprecated and not recommended to use.

Life cycle of a threads


The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

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

New :- MyThread t=new MyThread();


Ready :- t.start()
Running state:- If thread scheduler allocates CPU for particular thread. Thread goes
to running state
The Thread is running state means the run() is executed.
Blocked State:-
If the running thread got interrupted of goes to sleeping state at that moment it goes
to the blocked 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
}

Runtime stack mechanism


1. For every thread JVM will create a runtime stack.
2. Each and every method call performed by that thread will be store in the
corresponding stack.
3. Each entry in the stack is called stack frame or activation record.
4. After completing every method call the corresponding entry from the stack will be
removed.
5. After completing all method calls the stack will become empty and that empty stack
will be destroyed by JVM just before terminating the thread.

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-

1) In a program at least one method terminate abnormally then the program


termination is abnormal termination.
2) If all method terminated normally then only program termination is normal
termination.

Exception Handling Tree Structure:-


Page 341
https://gits-sln.blogspot.com Durga sir Java Notes

 The root class of exception handling is Throwable class.


 Throwable class define two class Exception and Error.
Exception

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

Checked Exception vs Unchecked Exception


The exceptions which are checked by compiler for smooth execution of the program are
called checked exception. Example- HallTicketMissingException,
PenNotWorkingException, FileNotFoundException etc.
In our program if there is a chance of rising checked exception then compulsory we
should handle that checked exception (either by try catch or by throws keywords)
otherwise we will get compile time error.
The exceptions which are not checked by compiler whether programmer handling or not
such type of exception are called unchecked exception. Example- ArithmeticException,
BombBlastException, NullPointerException etc.
Note-
Whether it is checked or unchecked every exception occurs at runtime only there is no
chance of occurring any exception at compile time.
RuntimeException and its child classes, Error and its child classes are unchecked except
these remaining are checked.

Fully checked vs partially checked


A checked exception is said to be fully checked if and only if all its child classes also
checked example- IOException, InterruptedException.
A checked exception is said to be partially checked if and only if some of its child classes
are unchecked. Example- Exception, Throwable.
Note-
The only possible partially checked exceptions in java are
1) Exception
2) throwable
Describe the behavior of following exception
 IOExceptionException checked(fully)
 RuntimeException unchecked

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)

Customized exception handling by using try catch


It is highly recommended to handle exception.
The code which may rise an exception is called risky code and we have to define that
code inside try block and corresponding handling code we have to define inside catch
block.
try
{ risky code;
}
catch (Exception obj)
{ handling code;
}

Without using try catch example-


public class Exception_test {
public static void main(String[] args) {
System.out.println("Start-1");
System.out.println(10/0);
System.out.println("Start-3");
}
}

Output(Provide a abnormal termination)-

Start-1
Exception in thread "main" java.lang.ArithmeticException: / by zero

With using try catch example-


public class Exception_test {
public static void main(String[] args) {
System.out.println("Start-1");
try{
System.out.println(10/0);
}catch(Exception e)
{
System.out.println(e.toString());
}
System.out.println("Start-3");
}
}
Output(Provide a normal termination)-
Start-1
java.lang.ArithmeticException: / by zero

Page 344
https://gits-sln.blogspot.com Durga sir Java Notes

Start-3

Case study of try catch block execution


try
{ statement-1;
statement-2;
statement-3;
}
catch (Exception obj)
{ statement-4;
}
statement-5;

case-1: if there is no exception


1,2,3,5, normal termination
Case-2:if an exception rise at statement 2 and corresponding catch block match
1,4,5, normal termination
Case-3: if an exception rise at statement 2 and corresponding catch block not match
1, abnormal termination
Case-4: if an exception rise at statement 4 or statement 5
Then it is always abnormal termination
Note-
1) Within the try block if anywhere an exception raised then rest of try block won’t be
executed even though we handle that exception hence within the try block we have to
take only risky code and length of try block should be as less as possible.
2) In addition to try block there may be a chance of rising an exception inside catch and
finally blocks.
3) If any statement which are not parts of try block and rises an exception then it is
always abnormal termination.

Method to print exception information-


public class Exception_test {
public static void main(String[] args) {
System.out.println("Start-1");
try{
System.out.println(10/0);
}catch(Exception e)
{
//e.printStackTrace();
//System.out.println(e);
//System.out.println(e.toString());
System.out.println(e.getMessage());
}
System.out.println("Start-3");
}
}

1. If we are using e.printStackTrace(); then we get (internally default exception handler


will use printStackTrace() to print stack information to the console )

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

Throwable class define the following method to print exception information

Method Print format


printStackTrace() Name of exception: Description
Stack Trace
toString() Name of exception: Description
getMessage() Description

Try with the multiple catch blocks


The way of handling an exception is varied from exception to exception hence for every
exception type it is highly recommended to take separate catch block that is try with
multiple catch block is always possible and recommended to use.
try
{
Risky code
}
catch (Exception e)
{

The above syntax provide Worst programming practices


try
{
Risky code
}
catch (ArithmeticException e)
{
Perform alternative arithmetic operation
}
catch (SQLException e)
{
Use mysql db instants of oracle db
}
catch (FileNotFoundException e)
{
Use local file instants of remote file
}
catch (Exception e)
{

Page 346
https://gits-sln.blogspot.com Durga sir Java Notes

Default exception handler


}

The above syntax provides Best programming practices.


So try with multiple catch block provide a best programming practices.
If try with multiple catch block presents then the order of catch block is very important
we have to take child first then parent otherwise we will get compile time error saying
Exception XXX has already been caught.
Example-
public class Exception_test {
public static void main(String[] args) {
try{
System.out.println(10/0);
}catch(Exception e)
{
}
catch(ArithmeticException e)
{
}
}
}

Output-

Unresolved compilation problem:


Unreachable catch block for ArithmeticException. It is already handled by the catch
block for Exception

But when we taken in child first then parent order


public class Exception_test {
public static void main(String[] args) {
try{
System.out.println(10/0);
}
catch(ArithmeticException e)
{
}
catch(Exception e)
{
}
}
}

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

Unresolved compilation problem:


Unreachable catch block for ArithmeticException. It is already handled by the catch
block for ArithmeticException

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

2) the specialty of finally bock is it will executed always irrespective of whether


exception is raised or not raised and whether handle or not handle.

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

Various possible combination of try catch finally


1) In try catch finally order is important.
2) Whenever we are writing try compulsory we should write either catch or finally
otherwise we will get compile time error that is try without catch or finally is invalid.
3) Whenever we are writing catch block compulsory try block must be required that is
catch without try is invalid.
4) Whenever we are writing finally block compulsory we should write try block that is
finally without try is invalid.
5) Inside try catch finally block we can declare try catch and finally blocks that is nesting
of try catch finally is allowed.
6) For try catch and finally block curly braces are mandatory.

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

Case-1: if e refers null then we will get NullPointerException


public class Exception_test {
static ArithmeticException e=new ArithmeticException();
public static void main(String[] args) {
throw e;
}
}

RE:Exception in thread "main" java.lang.ArithmeticException

But if
public class Exception_test {
static ArithmeticException e;
public static void main(String[] args) {
throw e;
}
}

RE:Exception in thread "main" java.lang.NullPointerException

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

CE:Exception in thread "main" java.lang.Error: Unresolved compilation problem:


Unreachable code

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

public class Exception_test {


public static void main(String[] args) {
throw new Exception_test();
}
}

CE:Exception in thread "main" java.lang.Error: Unresolved compilation problem:


No exception of type Exception_test can be thrown; an exception type must be a subclass
of Throwable

But if
public class Exception_test extends RuntimeException {
public static void main(String[] args) {
throw new Exception_test();
}
}

RE:Exception in thread "main" 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");
}
}

CE:Exception in thread "main" java.lang.Error: Unresolved compilation problem:


Unhandled exception type FileNotFoundException
at Exception_test.main(Exception_test.java:6)

Example-2

public class Exception_test {


public static void main(String[] args) {
Thread.sleep(1000);
}
}

CE:Exception in thread "main" java.lang.Error: Unresolved compilation problem:


Unhandled exception type InterruptedException
at Exception_test.main(Exception_test.java:5)

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.

public class Exception_test {


public static void main(String[] args) throws InterruptedException {
doStuff();
}
public static void doStuff() throws InterruptedException
{
domoreStuff();
}
public static void domoreStuff() throws InterruptedException
{
Thread.sleep(10000);
}
}

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

Exception handling keyword summaries


1) try: to maintain risky code.
2) catch : to maintain exception handling code.
3) finally : to maintain cleanup code.
4) throw : to handover our created exception object to the JVM manually.
5) throws : to delegate responsibility of exception handling to the caller.
Various possible compile time error in exception handling
1) Unreported exception XXX; must to caught or declare to be thrown
2) Exception XXX has already been caught.
3) Exception XXX is never thrown in body of corresponding try statement.
4) Unreachable statement.
5) Incompatible type
Found: Test
Required : java.lang.throwable
6) Try without catch or finally.
7) Catch without try.
8) Finally without try.
Customized or user defined exception
Some times to meet programmer requirement we can define our own exception such
type of exception are called customized or user defined exception.
Example- TooYoungException, TooOldException, InsuffientFundException etc.
package com.java.ppteSst;
class TooYoungException extends RuntimeException
{
TooYoungException(String s)
{

Page 357
https://gits-sln.blogspot.com Durga sir Java Notes

super(s);//to make description available to default exception handler


}
}
class TooOldException extends RuntimeException
{
TooOldException(String s)
{
super(s); //to make description available to default exception handler
}
}
public class CustException {
public static void main(String[] args) {
int age=Integer.parseInt(args[0]);//run by using command line argument mode
if(age>60)
{
throw new TooYoungException("please wait some more time ... you will get
best match soon");
}
else if(age<18)
{
throw new TooOldException("your age is already crossed marrige age ... no
chnace of getting marriage.");
}
else
{
System.out.println("you will get match details soon by email..");
}

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

Top ten exceptions


Based on the person who is rising an exception all exception are divided into two
categories
1. JVM exception
2. Programmatic exception
1. JVM exception
The exceptions which are rise automatically by JVM whenever a particular event occur
are called JVM exception.
Example- ArithmenticException, NullPointerException etc.
2. Programmatic exception
The exceptions which are rised explicitly either by programmer or by API developer to
indicate that something goes wrong or called programmatic exception.
Example- TooOldException, IllegalArgumentException etc.

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

Object o = new String("ratan");


String s=(string)o;
 StackOverflowError
 It is the child class of error and hence it is unchecked rised automatically by JVM
whenever we are trying to perform recursive method call
class Test
{ void m1()
{ m2();
System.out.println("this is Rattaiah");
}
void m2()
{ m1();
System.out.println("from Sravyasoft");
}
public static void main(String[] args)
{ new Test().m1();
}
}

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.

Different types of Exceptions in Description


java:- Checked Exception
ClassNotFoundException If the loaded class is not available
CloneNotSupportedException Attempt to clone an object that
does not implement the Cloneable
interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an
abstract class or interface.
InterruptedException One thread has been interrupted by
another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException If the requested method is not
available.
UncheckedException Description
ArithmeticException Arithmetic error, such as divide-by-
zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.(out
of range)
InputMismatchException If we are giving input is not
matched for storing input.
ClassCastException If the conversion is Invalid.
IllegalArgumentException Illegal argument used to invoke a
method.
IllegalThreadStateException Requested operation not
compatible with current thread
state.
IndexOutOfBoundsException Some type of index is out-of-
bounds.

Page 361
https://gits-sln.blogspot.com Durga sir Java Notes

NegativeArraySizeException Array created with a negative size.


NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a
numeric format.
StringIndexOutOfBoundsException Attempt to index outside the
bounds of a string.

1.7 version enhancement with respect to exception handling


As a part of 1.7 versions in exception handling the following two concept introduced
1. Try with resources
2. Multi catch block
Until 1.6 version it is highly recommended to write finally block to close resources which
are open as a part of try block

Page 362
https://gits-sln.blogspot.com Durga sir Java Notes

The problems in this approach are


1. Compulsory programmer is required to close resources inside finally block it
increases complexity of programming
2. We have to write finally block compulsory and hence it increases length of code
and reduces readability
To overcome above problem sun people introduced try with resources in 1.7 versions
1. The main advantage of try with resources is whatever resources we open as a part
of try block will be closed automatically once control reach eases end of try block
either normally or abnormally and hence we are not required to close explicitly so
that complexity of programming will be reduced.
2. We are not required to write finally block so that length of the code will be reduced
and readability will be improved.

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.

CE: auto closable resources br may not be assigned


Note - Until 1.6 v try should be associated with either or finally but from 1.7 v onwards
we can take only
try with resources without catch or finally.
try(Resources)
{

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

Multi catch block


Until 1.6 version even though multiple different exception having same handling code for
every exception type we have to write a separate catch block it increases length of code
and reduces readability.

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.

In the above example whether rised exception is either NullPointerException or


ArithmenticException the same catch block can respond.
In multi catch block there should not be any relation between exception types (either
child to parent or parent to child or same type) otherwise we will get error

Page 367
https://gits-sln.blogspot.com Durga sir Java Notes

CE: alternatives in a multi catch statement cannot be related by sub classing

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

The Ways to Make an Object Eligible for GC:


• Even though Programmer is Not Responsible to Destroy Useless Objects but it is
Highly Recommended to Make an Object Eligible for GC if it is No Longer required.

• 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

2) Reassigning the Reference Variable:


If an Object is No Longer required, then re Assign its Reference Variable to any other
object then old project is automatically eligible for GC.

3) Objects Created Inside a Method:


Objects Created inside a Method are by Default Eligible for Garbage Collection Once
Method Completes (Because the Reference Variables are Local Variables of that
Method and once method completes all local variables will be destroyed).

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

The Ways for requesting JVM to Run Garbage Collector:


• Once we Made an Object Eligible for GC, it May Not Destroy Immediately by the
Garbage Collector. Whenever JVM Runs Garbage Collector then Only Object will be
Destroyed. But when exactly JVM runs GC, We can't Expect. It Depends on JVM and
varied from JVM to JVM.
• Instead of waiting until JVM Runs GC, we can Request JVM to Run Garbage Collector.
But there is No Guarantee whether JVM Accept Our Request OR Not. But Most of the
Times JVM Accepts Our Request.
The following are Various Ways for requesting JVM to Run Garbage Collector:
1) By Using System Class:
System Class contains a Static Method gc() for this Purpose.
System.gc();
2) By Using Runtime Class:
• A Java Application can communicate with JVM by using Runtime Object.
• Runtime Class Present in java.lang Package and it is a Singleton Class.
• We can Create a Runtime Object by using getRuntime().
Runtime r = Runtime.getRuntime();
Once we got Runtime Object we can Call the following Methods on that Object.

Page 372
https://gits-sln.blogspot.com Durga sir Java Notes

1) freeMemory() : Returns Number of Bytes of Free Memory Present in the Heap.


2) totalMemory(): Returns Total Number of Bytes of Heap (i.e. Heap Size).
3) gc(): Requesting JVM to Run Garbage Collector.

Note-1 : Singleton class:


For any Java class if we are allowed to create only one objet, such type of class is called
Singleton class. Eg: Runtime, BusinessDelegate, ServiceLocator
Note-2 : Factor Method:
By using class name if we are calling a method and if that method returns same class
object, such type of methods are called factory methods(static factory methods).
Eg:
Runtime r = Runime.getRuntime();
DateFormat df = DateFormat.getInstance();

public class Exception_test {


public static void main(String[] args) {
Runtime r =Runtime.getRuntime();
System.out.println(r.totalMemory()); //16252928
System.out.println(r.freeMemory()); //15956808
for(int i=0; i<10000; i++)
{
Date d= new Date();
d = null;
}
System.out.println(r.freeMemory()); //115772752
//r.gc();
System.out.println(r.freeMemory()); //16074976
}
}

Output- when we are using comment in r.gc(); line


5177344
4967032//initial free momory
4728784//beginning time free memory
4710400//memory is reduce by using to run a program

when we are not using comment in r.gc(); line


5177344
4967032//initial free memory
4728760//beginning time free memory
5060304//memory is increased

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.

public class Test {

Page 377
https://gits-sln.blogspot.com Durga sir Java Notes

static int count=0;


public static void main(String[] args){
for(int i=0;i<10;i++)
{
Test t=new Test ();
t=null;
}
}
public void finalize()
{
count++;
System.out.println("finalize() call:"+count);//no of object destroyed by GC
}
}

In the above program if we keep on increasing i value at certain point memory problem
will be raised and JVM run automatically GC.

Case 6: Memory Leaks


• The Objects which are Not using in Our Program and which are Not Eligible for Garbage
Collection, Such Type of Useless Objects are Called Memory Leaks.
• In Our Program if Memory Leaks Present then at certain point our program fails by
raising RE: OutOfMemoryError.
• To Overcome this Problem if an Object is No Longer required, then it is Highly
Recommended to Make that Object Eligible for GC.
• In Our Program if Memory Leaks Present, then it is Purely Programmer's Mistake.
• The following are Various Memory Management Tools to Identify Memory Leaks in our
Application
• HP-J-METER
• HP-OVO
• J-PROBE
• HP-PATROL
• IBM-TIVOLI

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

Annotations in Java are used to provide additional information, so it is an alternative


option for XML and Java marker interfaces

Page 378
https://gits-sln.blogspot.com Durga sir Java Notes

There are the various phases of compiler:

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.

XML based tech Annotation based tech


Upto JDK 1.4 version Upto JDK 5.0 version to onwards
JDBC 3.X onwards XML based JDBC 4.0 onwards is annotation based
Servelet upto 2.5 version xml based Servelet 3.X version onwards annotation

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

Built-In Java Annotations


There are several built-in annotations in Java. Some annotations are applied to Java
code and some to other annotations.

Built-In Java Annotations used in Java code

o @Override
o @SuppressWarnings
o @Deprecated

Built-In Java Annotations used in other annotations

o @Target
o @Retention
o @Inherited
o @Documented

Understanding Built-In Annotations


Let's understand the built-in annotations first.

@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 Dog extends Animal{


@Override
void eatsomething(){System.out.println("eating foods");}//should be eatSomething
}

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.

Note: Recompile with -Xlint:deprecation for details.


At Runtime:
hello n

Java Custom Annotations


Java Custom annotations or Java User-defined annotations are easy to create and
use. The @interface element is used to declare an annotation. For example:
@interface MyAnnotation{}

Here, MyAnnotation is the custom annotation name.

Points to remember for java custom annotation signature


There are few points that should be remembered by the programmer.

1. Method should not have any throws clauses


2. Method should return one of the following: primitive data types, String, Class,
enum or array of these data types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to define annotation.
5. It may assign a default value to the method.

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

An annotation that has no method, is called marker annotation. For example:

@interface MyAnnotation{}

The @Override and @Deprecated are marker annotations.

2) Single-Value Annotation

An annotation that has one method, is called single-value annotation. For example:

@interface MyAnnotation{
int value();
}

We can provide the default value also. For example:

@interface MyAnnotation{
int value() default 0;
}

How to apply Single-Value Annotation


Let's see the code to apply the single value annotation.
@MyAnnotation(value=10)

The value can be anything.

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

We can provide the default value also. For example:

@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}

How to apply Multi-Value Annotation

Let's see the code to apply the multi-value annotation.

@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

Example-1:create and use of annotation with member value

@interface SmartPhone //create a annotation with member


{
String os();
int version();
}
@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[]){

}
}

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.

@interface SmartPhone //create a annotation with member

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

}
}

Example-3: using of annotation

@interface SmartPhone //create a annotation with member


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

}
}

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

Built-in Annotations used in custom annotations in java


o @Target
o @Retention
o @Inherited
o @Documented

@Target

@Target tag is used to specify at which type, the annotation is used.

The java.lang.annotation.ElementType enum declares many constants to specify the


type of element where annotation is to be applied such as TYPE, METHOD, FIELD etc.
Let's see the constants of ElementType enum:

Element Types Where the annotation can be applied

TYPE class, interface or enumeration

FIELD fields

METHOD Methods

CONSTRUCTOR Constructors

LOCAL_VARIABLE local variables

ANNOTATION_TYPE annotation type

PARAMETER Parameter

Page 386
https://gits-sln.blogspot.com Durga sir Java Notes

Example to specify annoation for a class

@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
Example to specify annotation for a class, methods or fields

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})


@interface MyAnnotation{
int value1();
String value2();
}

@Retention

@Retention annotation is used to specify to what level annotation will be available.

RetentionPolicy Availability

RetentionPolicy.SOURCE refers to the source code, discarded during


compilation. It will not be available in the compiled
class.

RetentionPolicy.CLASS refers to the .class file, available to java compiler


but not to JVM . It is included in the class file.

RetentionPolicy.RUNTIME refers to the runtime, available to java compiler


and JVM .

Example to specify the RetentionPolicy

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}

Example of custom annotation: creating, applying and accessing annotation

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{

Hello h=new Hello();


Method m=h.getClass().getMethod("sayHello");

MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
System.out.println("value is: "+manno.value());
}}
Test it Now
Output:value is: 10

How built-in annotaions are used in real scenario?


In real scenario, java programmer only need to apply annotation. He/She doesn't need
to create and access annotation. Creating and Accessing annotation is performed by the
implementation provider. On behalf of the annotation, java compiler or JVM performs
some additional operations.

@Inherited

By default, annotations are not inherited to subclasses. The @Inherited annotation


marks the annotation to be inherited to subclasses.

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

class Subclass extends Superclass{}

@Documented

The @Documented Marks the annotation for inclusion in the documentation.

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.

Internal implementation of enum


 Every enum Internally implemented by using Class Concept.
 Every enum Constant is Always public static final.
 Every enum Constant Represents an Object of the Type enum

Enum declaration and usage


Every enum constant is static hence we can access by using enum name.
enum Beer{
KF,KO,RC,FO;
}
public class EnumTest {
public static void main(String[] args) {
Beer b=Beer.KF;
System.out.println(b);//KF
System.out.println(b.toString());//KF
}
}

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

enum Vs switch Statement:


• Until 1.4 Version the only allowed Argument Types for the switch Statements are byte,
short, char, and int.
• From 1.5 Version onwards the Corresponding Wrapper Classes and enum Type Also
Allowed.
• From 1.7 Version onwards String Type is Also Allowed.

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

 But enum can implements any number of interfaces simultaneously.

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

Specialty of Java enum:


• In Old Languages enum we can declare Only Constants.
• But in Java enum in Addition to Constants we can Also declare Methods, Constructors,
and Normal Variables, Etc..,
• Hence Java enum is More Powerful than Old Languages enum.
• Even we can declare main() method inside enum. Hence we can Invoke enum Directly
from the Command Prompt.
enum EnumTest{
KF,KO,RC,FO;
public static void main(String[] args) {
System.out.println("enum main");
}
}

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.

assert as keyword and identifiers


assert keyword introduced in 1.4 version hence from1.4 version onwards we can’t use
assert as identifiers otherwise we will get compile time error.

public class AssertDemo1 {


public static void main(String[] args) {
int assert=10;
System.out.println(asert);
}
}

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.

Types of assert statements


1) Simple version
2) Augmented version

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.

public class AssertDemo1 {


public static void main(String[] args) {
int x=10;
:
:
assert(x>10);
System.out.println(x);
}
}
javac AssertDemo1.java
java AssertDemo1
10
Java –ea AssertDemo1
RE: AssertionError

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

public class AssertDemo1 {


public static void main(String[] args) {
int x=10;
:
:
assert(x>10):"here x value should be > 10 but it is not";

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

Various possible runtime flags


1. –ea or –enableassertions
To enable assertions in every non-system class( our own classes)
2. –da or –disableassertions
To disable assertions in every non-system class
3. –esa or -enablesystemassertions
To enable assertions to every system class (predefined classes)
4. –dsa or -disablesystemassertions
To disable assertions in every system class
Note-
We can use above flag simultaneously then JVM will consider these flag from left to right
Eg:
Java –ea -esa -ea -dsa -da -esa -ea -dsa Test
Non- System
system
Y Y
Y N
N Y
Y N
At the end assertion will be enable in every non-system class and disable in every
system class
Case Study

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

Appropriate and inappropriate use of assertions


1. It is always inappropriate to mix programming logic with assert statements because
there is no guarantee for the execution of assert statement always at runtime.
Eg:
Appropriate way:
public void withdraw(double amount)
{
if(amount < 100)
throw new IllegalRequestException();
else
process Request;
}

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

3. It is always inappropriate for validating public method argument by using assertions


because outside person doesn’t aware whether enable or disable in our system.
4. It is always appropriate for validating private method argument by using assertions
because local person can aware whether assertion are unable or disable in our
system.

Page 401
https://gits-sln.blogspot.com Durga sir Java Notes

5. It is always inappropriate for validating command line argument by using assertion


because these are argument to main method, which is public.

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

4) Character Classes 5) Pre - Defined Character Classes 6) Quantifiers


7) Pattern Class split() 8) String Class split() 9)
StringTokenizer

If we want to Represent a Group of Strings according to a Particular Pattern, then we


should go for Regular Expression.

Eg 1: We can write a Regular Expression to Represent All Mobile Numbers.


Eg 2: We can write a Regular Expression to Represent All Mail ID's.

The Main Important Application Areas of Regular Expressions are


• To Develop Validation Frameworks
• To Develop Pattern Matching Applications (Ctrl + F in Windows, grep in UNIX)
• To Develop Translators Like Compilers, Interpreters, and Assemblers Etc...
• To Develop Digital Circuits Like Moore and Melay Machines
• To Develop Communication Protocols Like TCP/IP, UDP Etc
Page 405
https://gits-sln.blogspot.com Durga sir Java Notes

public class RegExDemo1 {


public static void main(String[] args) {
int count=0;
Pattern p=Pattern.compile("ab");//this is pattern or regular expression
Matcher m=p.matcher("ababbaba");//target string
while(m.find())
{
count++;
System.out.println(m.start()+":"+m.end()+":"+m.group());
}
System.out.println("the number of occurances:"+count);
}

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

How to Create a Pattern Object?


eg: Pattern p = Pattern.compile("ab");

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

How to Create Matcher Object?


eg: Matcher m = p.matcher("ababbaba");

Methods of Matcher Class:


1) public boolean find();
It Attempts to find Next Match and Returns true if it is Available. Otherwise Returns
false.
2) public int start();
Returns Start Index of the Match.
3) public int end();
Returns end + 1 Index of the Match.
4) public String group();

Page 406
https://gits-sln.blogspot.com Durga sir Java Notes

Returns the Matched Pattern.


Note: Pattern and Matcher Classes Present in java.util.regex Package and Introduced in
1.4 Version of java.
Character classes

public class RegExDemo1 {


public static void main(String[] args) {
Pattern p=Pattern.compile("[^a-zA-Z0-9]");//this is pattern or regular
expression
Matcher m=p.matcher("a7b@z#9");//target string
while(m.find())
{
System.out.println(m.start()+":"+m.group());
}
}
}
Output-
3:@
5:#
If we suppose the value of compile() method is X and on the basis of different X value
the result will be

Pre-defined character classes

Page 407
https://gits-sln.blogspot.com Durga sir Java Notes

public class RegExDemo1 {


public static void main(String[] args) {
Pattern p=Pattern.compile("\\s");//this is pattern or regular expression
Matcher m=p.matcher("a7b k@9");//target string
while(m.find())
{
System.out.println(m.start()+":"+m.group());
}
}

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

public class RegExDemo1 {

Page 408
https://gits-sln.blogspot.com Durga sir Java Notes

public static void main(String[] args) {


Pattern p=Pattern.compile("a");//this is pattern or regular expression
Matcher m=p.matcher("abaabaaab");//target string
while(m.find())
{
System.out.println(m.start()+":"+m.group());
}
}
}
Output-
0:a
2:a
3:a
5:a
6:a
7:a

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:

Pattern class split()


We can use Pattern class split() to split the given target string according to the given
string

public class RegExDemo1 {


public static void main(String[] args) {
Pattern p=Pattern.compile("\\s");//this is pattern or regular expression
String[] s=p.split("Garima Infotech Solutions");//target string as an argument
for(String s1:s)
{

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 class split()


String class also contain split() to split given target string according to particular pattern.
public static void main(String[] args) {
String s="Garima Infotech Solutions";
String[] s1=s.split("\\s");//regular expression as an argument
for(String s2:s1)
{
System.out.println(s2);
}
}
}
Output-
Garima
Infotech
Solutions
Note-
Pattern class split() can take target string as an argument whereas string class split()
can take regular expression as an argument.

String Tokenizer
It is a specially designed class for tokenization activity.
This class present in java.util package.

public class RegExDemo1 {


public static void main(String[] args) {
StringTokenizer st=new StringTokenizer("Garima Infotech Solutions");
while(st.hasMoreTokens())

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.

public class RegExDemo1 {


public static void main(String[] args) {
StringTokenizer st=new StringTokenizer("03-06-1982","-");
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output-
03
06
1982

Write a Regular Expression to Represent All 10-digit Mobile Numbers:


Rules:
• Every Number should contain Exactly 10 Digits.
• The 1st Digit should be 7 OR 8 OR 9.
Answer:
[7-9][0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9]
OR
[7-9][0-9](9}
OR
[789][0-9]{9}

10 Digit OR 11 Digit:
If the number contains 11 digits then the first digit should be 0
0?[7-9][0-9]{9}

10 Digit OR 11 Digit OR 12 Digit:


If the number contains 12 digits then the first two digits should be 91
(0|91)?[7-9][0-9]{9}

Write a regular expression to represent all valid mail ID’s

Page 411
https://gits-sln.blogspot.com Durga sir Java Notes

[a-zA-Z0-9][ a-zA-Z0-9_.]*@ [a-zA-Z0-9] + ([.][a-zA-Z]+)+

Only for Gmail ID

[a-zA-Z0-9][ a-zA-Z0-9_.]*@ gmail[.]com

Write a Regular Expression to Represent All Valid Yava Language


Identifiers:
Rules:
• The Allowed Characters are a-z, A-Z, 0-9, #, and $.
• The Length of Identifier should be at least 2.
• The 1st Character should be Lower Case Alphabetical Symbol from a To k.
• The 2nd Character should be Digit Divisible by 3 (0, 3, 6, 9)

[a-k][0369][a-zA-Z0-9#$]*

Regular Expression to represent all Names starts with a | A


[aA][a-zA-Z]*

Regular Expression to represent all Names ends with l or L


[a-zA-Z]*[lL]

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

Write a program to check whether a number is a valid mobile


number or not?
public class RegExDemo1 {
public static void main(String[] args) {
Pattern p=Pattern.compile("(0|91)?[7-9][0-9]{9}");//this is pattern or
regular expression
Matcher m=p.matcher(args[0]);//target string
if(m.find()&& m.group().equals(args[0]))
{
System.out.println("valid mobile number:"+args[0]);
}
else
{
System.out.println("Invalid mobile number:"+args[0]);
}
}
}

Run by using command line mode

Q:Write a Program to Check whether the given Mail Id is Valid OR


Not?
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]+)+

Write a program to extract all valid mobile number present in the


given text file where number are mixed with normal text data?
public class RegExDemo1 {
public static void main(String[] args) throws IOException {
PrintWriter pw=new PrintWriter("D:/output.txt");
Pattern p=Pattern.compile("(0|91)?[7-9][0-9]{9}");//this is pattern or
regular expression
BufferedReader br=new BufferedReader(new FileReader("D:/input.txt"));
String line=br.readLine();
while(line!=null)
{
Matcher m=p.matcher(line);
while(m.find())
{
pw.println(m.group());
}
line=br.readLine();
}
pw.flush();
}
}

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]+)+

Q:Write a Program to display all .txt file name present in D:\\PP


public class RegExDemo1 {
public static void main(String[] args) throws IOException {
int count=0;
Pattern p=Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9_$.]*[.]txt");
File f=new File("D:\\PP");
String[] s=f.list();
for(String s1:s)
{
Matcher m=p.matcher(s1);
if(m.find()&&m.group().equals(s1))
{
count++;
System.out.println(s1);
}
}
System.out.println("the total number of files:"+count);
}
}

JVM Architecture
1) Virtual Machine
2) Types of Virtual Machines

Page 414
https://gits-sln.blogspot.com Durga sir Java Notes

i) Hard-ware based VM (Eg: kernel based VM,Xen)


ii) Application Based VM (Eg: JVM)
3) Basic Architecture Diagram of JVM.
4) ClassLoader Sub Systm
• Loading
• Linking
• Initialization
5) Types of ClassLoaders
• Boot Strap ClassLoader
• Extension ClassLoader
• Application ClassLoader
6) How Java ClassLoader Works?
7) Need of Customized ClassLoader
8) Pseudo Code to Define Customized ClassLoader
9) Various Memory Areas of JVM
• Method Area
• Heap Area
• Stack Memory
• PC Registers Area
• Native Method Stacks Area
10) Importance of Runtime Class
11) Program to Display Statistics of Heap Memory.
a. MaxMemory
b. TotalMemory
c. FreeMemory
12) How to Set Maximum and Minimum Heap Size
13) Execution Engine
• Interpreter
• JIT Compiler
14) Java Native Interface (JNI)
15) Class File Structure
i) Magic Number
ii) Minor Version
iii) Major Version

Page 415
https://gits-sln.blogspot.com Durga sir Java Notes

Virtual Machine:

It is a Software Simulation of a Machine which can Perform Operations Like a Physical


Machine. This is not having a physical existence.

Types of Virtual Machines:


There are 2 Types of Virtual Machines
1) Hardware Based OR System Based Virtual Machines
2) Software Based OR Application Based OR Process Based Virtual Machines
1) Hardware Based OR System Based Virtual Machines

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)

 System admin related terminology but not programmer.

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.

2) Software Based OR Application Based OR Process Based Virtual Machines

These Virtual Machines Acts as Runtime Engines to Run Particular Programming


Language Applications.

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

There are three important component of JVM


1. Class loader(to load .class file)
2. Memory area
I. Method area(.class file will be saved)
II. Heap area (Object will be saved)
III. Stack area
IV. PC registers(current executing instruction address hold)
V. Native method stacks
3. Execution engine(responsible to run loaded class file line by line)

JNI provide native method libraries information to Execution engine

ClassLoader Sub System:


ClassLoader Sub System is Responsible for the following 3 Activities.
1) Loading
2) Linking
• Verification
• Preparation
• Resolution
3) Initialization
1) Loading:
• Loading Means Reading Class Files and Store Corresponding Binary Data in Method
Area. • For Each Class File JVM will Store the following Information in Method Area.
1) Fully Qualified Name of the Loaded Class OR Interface OR enum.
2) Fully Qualified Name of its Immediate Parent Class.

Page 417
https://gits-sln.blogspot.com Durga sir Java Notes

3) Whether .class File is related to Class OR Interface OR enum.


4) The Modifiers Information
5) Variables OR Fields Information
6) Methods Information
7) Constant Pool Information and so on.
• After loading .class File Immediately JVM will Creates an Object of the Type class Class
to Represent Class Level Binary Information on the Heap Memory.

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.

Program to print method and variable information by using class object

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

 Internally Byte Code Verifier which is Part of ClassLoader Sub System is


Responsible for this Activity.
 If Verification Fails then we will get Runtime Exception Saying
java.lang.VerifyError.

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.

Types of Class Loaders

Every Class Loader Sub System contains the following 3 Class Loaders.

1. Bootstrap Class Loader/ Primordial Class Loader

2. Extension Class Loader

3. Application Class Loader/ System Class Loader

1) Bootstrap Class Loader/ Primordial Class Loader:

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

3) Application class loader or system class loader


It is the child of extension class loader. This class loader is responsible to load classes
form application class path. It internally uses environment variable class path.
Application class loader is implemented in java and the corresponding .class file name is
sun.misc.Launcher$AppClassLoader.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.

How class loader work

Class loader sub system follow delegation hierarchy algorithm.

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.

Principles of functionality of a Java ClassLoader


Principles of functionality are the set of rules or features on which a Java ClassLoader
works. There are three principles of functionality, they are:

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

What is the Need of Customized ClassLoader?


• Sometimes we may not satisfy with default class loaders and with default class loading
mechanism.
Use-Case :
• Default ClassLoader will load .class File Only Once Even though we are using Multiple
Times that Class in Our Program. After loading .class File if it is modified Outside, then
Default ClassLoader won't Load Updated Version of Class File on fly, because .class File
already there in Method Area.
We can Resolve this Problem by defining Our Own Customized ClassLoader. For Example
whenever we are using a class first my class loader will whether updated version is
available or not. If it is available then load updated version otherwise use already loaded
existing .class file, so that Updated Version Available to our program.

The Main Advantage of Customized ClassLoader is we can customize Class loading


Mechanism Based on Our Requirement.

Page 427
https://gits-sln.blogspot.com Durga sir Java Notes

How to define our own ClassLoader?


We can define our own customized classLoader by extending java.lang.ClassLoader
class.

Page 428
https://gits-sln.blogspot.com Durga sir Java Notes

What is the Purpose of java.lang.ClassLoader Class?


 We can use ClassLoader class to define our own Customized Class Loaders.
 Every Customized ClassLoader in Java should extends java.lang.ClassLoader class
either Directly OR Indirectly.
 Hence this class acts as Base Class for developing Our Own Customized
ClassLoaders.
Where we can use customized class loader?
While developing our own web servers and application servers

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

Web Application Logic

1) Presentation logic-HTLML, CSS. (client side page or form)


2) Request Data Gathering Logic-servlet, jsp, spring.(server side request data come
from client side)
3) Validation Logic-jsp,js. (form contain different field validation logic)
4) Business Logic-servlet, jsp, struct, spring. (internally working main logic like
a=b+c)
5) Persistence Logic-JDBC, Hibernet. (provide a connection between client and server)
6) Session Management Logic-servlet, jsp. (to manage the session the code is it in
the term of maintain time duration)
7) Middle ware services (optional)-tool based term. (some optional term which can
provide extra services )
 JDBC is a part of J2SE and its contain a main() method which is executed by JVM
 Servlet, JSP is a web application part contain no main() method, it contain life cycle
method(init(),service(),destroy()) which is executed by server.

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.

2. Native-API driver (partially java driver)


 If type-4 and type-3 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

 If we are working with multiple database.


 It is useful in large scale web application and enterprise application.

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.

Java Database Connectivity with 5 Steps


1) Register the driver class

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

3) Create the Statement object


The object of statement is responsible to execute queries with the database.
Statement stmt=con.createStatement();

4) Execute the query


executeQuery() method is used to execute queries to the database. This method returns
the object of ResultSet that can be used to get all the records of a table.

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object

con.close();

Page 432
https://gits-sln.blogspot.com Durga sir Java Notes

Note: Since Java 7, JDBC has ability to use try-with-resources statement to


automatically close resources of type Connection, ResultSet, and Statement.
It avoids explicit connection closing step.

Java Database Connectivity with Oracle


1. Driver class: oracle.jdbc.driver.OracleDriver.
2. Connection URL: jdbc:oracle:thin:@localhost:1521:xe
1521 is the port number and XE is the Oracle service name. You may get all these
information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle
database.

To connect java application with the Oracle database ojdbc14.jar file is required to be
loaded.

Java Database Connectivity with MySQL

1. Driver class: com.mysql.jdbc.Driver.


2. Connection URL: jdbc:mysql://localhost:3306/sonoo
3306 is the port number and sonoo is the database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database.

To connect java application with the mysql database, mysqlconnector.jar file is


required to be loaded.

Package root right clickbuild pathconfigure build pathselect libraries tabadd


jar file option

Commonly used methods of Statement interface:

The important methods of Statement interface are as follows:


1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It
returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may
be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return
multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.

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

Commonly used methods of ResultSet interface

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

//getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

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.

String sql="insert into emp values(?,?,?)";


we are passing parameter (?) for the values. Its value will be set by calling the setter methods of
PreparedStatement.

Why use PreparedStatement?


Improves performance: The performance of the application will be faster if you use PreparedStatement
interface because query is compiled only once.

Methods of PreparedStatement interface


The important methods of PreparedStatement interface are given below:

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.

public ResultSet executeQuery() executes the select query. It returns an instance


of ResultSet.

Page 435
https://gits-sln.blogspot.com Durga sir Java Notes

Difference among statement, prepared statement and callable


statement.

Example of PreparedStatement interface that inserts the record


PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

Example of PreparedStatement interface that updates the record


PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");
stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
stmt.setInt(2,101);

int i=stmt.executeUpdate();
System.out.println(i+" records updated");

Example of PreparedStatement interface that deletes the record


PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");

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

Example of PreparedStatement interface that retrieve the records of a


table
PreparedStatement stmt=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

Example of PreparedStatement to insert records until user press n


import java.sql.*;
import java.io.*;
class RS{
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","oracle");

PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

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

System.out.println("Do you want to continue: y/n");


String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);

Page 437
https://gits-sln.blogspot.com Durga sir Java Notes

con.close();
}}

Java CallableStatement Interface


CallableStatement interface is used to call the stored procedures and functions.

Java ResultSetMetaData Interface


The metadata means data about data

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.

Commonly used methods of ResultSetMetaData interface

Method Description

public int getColumnCount()throws it returns the total number of


SQLException columns in the ResultSet
object.

public String getColumnName(int it returns the column name of


index)throws SQLException the specified column index.

public String getColumnTypeName(int it returns the column type


index)throws SQLException name for the specified index.

public String getTableName(int it returns the table name for


index)throws SQLException the specified column index.

PreparedStatement ps=con.prepareStatement("select * from emp");


ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
Java DatabaseMetaData interface
provides methods to get meta data of a database such as database product name,
database product version, driver name, name of total number of tables, name of total
number of views etc.

Page 438
https://gits-sln.blogspot.com Durga sir Java Notes

 Java is platform independent.


 JVM is platform dependent.
 Java is database independent
 Driver is database dependent
JDK API contain two package-
1. java.sql package
contain basic classes and interface which can be used for database communication.
2. javax.sql package
contain more advanced classes and interface which can be used for database
communication.
According to java developer point of view there are two type of sql query
1. Select queries(known as DQL)
2. Non select queries(known as DML)

Page 439
https://gits-sln.blogspot.com Durga sir Java Notes

Example:-Program to create a table


public class CreateTableDemo {
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
String driver="com.mysql.jdbc.Driver";
String jdbcurl="jdbc:mysql://localhost:3306/mydb";
String user="root";
String pwd="pp";
Class.forName(driver);
Connection con=DriverManager.getConnection(jdbcurl,user,pwd);
Statement st=con.createStatement();
String sqlQuery=String.format("create table student(stno integer,stname
varchar(10),stadd varchar(10))");//modern approach
st.executeUpdate(sqlQuery);
System.out.println("Table created successfully");
con.close();
}
}

Example:-Formatting sql query with dynamic input


Example-1:
import java.util.*;
public class Formatsql1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
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
System.out.println("Query with your dynamic input is:");
System.out.println(sqlQuery);
}

Example:-Insert multiple record by using Formatting sql query with


dynamic input
Example-1:
public class InsertMultipleRowDemo {
public static void main(String[] args) throws Exception{
String driver="com.mysql.jdbc.Driver";
String jdbcurl="jdbc:mysql://localhost:3306/mydb";
String user="root";
String pwd="pp";
Class.forName(driver);
Connection con=DriverManager.getConnection(jdbcurl,user,pwd);
Statement st=con.createStatement();
Scanner sc=new Scanner(System.in);
while(true)
{

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

Example:-Delete multiple row by using Formatting sql query

public class DeleteMultipleRowDemo {


public static void main(String[] args) throws Exception{
String driver="com.mysql.jdbc.Driver";
String jdbcurl="jdbc:mysql://localhost:3306/mydb";
String user="root";
String pwd="pp";
Class.forName(driver);
Connection con=DriverManager.getConnection(jdbcurl,user,pwd);
Statement st=con.createStatement();
Scanner sc=new Scanner(System.in);
System.out.println("Enter cutoff salery:");
double cutoff=sc.nextDouble();
String sqlQuery=String.format("delete from emp where emp_sal>=%f",
cutoff);//modern approach
int updateCount=st.executeUpdate(sqlQuery);
System.out.println("The number of row deleted:"+updateCount);
con.close();
}}

Example:-selecting particular column from table


Note-JDBC code is always based on resultset not based on database table
According to database table

Column- Emp_id Emp_name Emp_dept Emp_sal


name
Column- 1 2 3 4

Page 441
https://gits-sln.blogspot.com Durga sir Java Notes

index

But according to result set(on the based of query)

Column- Emp_name Emp_sal


name
Column- 1 2
index

public class SelectParticularColumnDemo {


public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
String driver="com.mysql.jdbc.Driver";
String jdbcurl="jdbc:mysql://localhost:3306/mydb";
String user="root";
String pwd="pp";
Class.forName(driver);
Connection con=DriverManager.getConnection(jdbcurl,user,pwd);
Statement st=con.createStatement();
String sqlQuery="select emp_name,emp_sal from emp";
ResultSet rs=st.executeQuery(sqlQuery);
boolean flag=false;
System.out.println("emp_name\t emp_sal");
System.out.println("-----------------------------------------");
while(rs.next())
{
flag=true;
System.out.println(rs.getString(1)+"\t"+rs.getDouble(2));
//table column order are different but here according to query always follow result set
order not column order
}
if(flag==false)
{
System.out.println("no record found");
}
con.close();
}

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

Basic Programs are written Programs employed


in the native OS. using Java.

Platform Platform dependent Does not rely on the


dependency platform

Creation of Each client request Processes are created


process creates its own depending on the type
process. of the client request.

Conversion of the Present in the form of Compiled to Java


script executables (native to Bytecode.
the server OS).

Runs on Separate process JVM

Security More vulnerable to Can resist attacks.


attacks.

Speed Slower Faster

Processing of Direct Before running the


script scripts it is translated
and compiled.

Portability Can not be ported Portable

Get vs. Post


There are many differences between the Get and Post request. Let's see these
differences:

GET POST

1) In case of Get request, only limited In case of post request, large


amount of data can be sent because amount of data can be sent

Page 443
https://gits-sln.blogspot.com Durga sir Java Notes

data is sent in header. because data is sent in body.

2) Get request is not secured because Post request is secured because


data is exposed in URL bar. data is not exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be


bookmarked.

4) Get request is idempotent . It Post request is non-idempotent.


means second request will be ignored
until response of first request is
delivered

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.

Webserver vs application server


Webserver
 To run web application webserver required.
 Web server support only for web related technology (like servlet, jsp, html etc.).
 No any web server contain in build application server.
 Examples of Web Servers are: Apache Tomcat and Resin.
Application Server
 To run enterprises application, application server required.
 Application server support any related j2ee technology (like all web related
technology + EJB, JMS etc).
 Every application server contain in build web server.
 The Example of Application Servers are:
o JBoss: Open-source server from JBoss community.
o Glassfish: Provided by Sun Microsystem. Now acquired by Oracle.
o Weblogic: Provided by Oracle. It more secured.
o Websphere: Provided by IBM.

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.

Life Cycle of a Servlet (Servlet Life Cycle)


The web container maintains the life cycle of a servlet instance. Let's see the life cycle of
the servlet:
1. Servlet class is loaded.:- when the first request for the servlet is received by the
web container.
2. Servlet instance is created.:- The web container creates the instance of a
servlet
3. init method is invoked.:- used to initialize the servlet.
4. service method is invoked.:- The web container calls the service method each
time when request for the servlet is received.
5. destroy method is invoked.:- The web container calls the destroy method before
removing the servlet instance from the service. It gives the servlet an opportunity
to clean up any resource for example memory, thread etc.

There are three states of a servlet: new, ready and end.


1) The servlet is in new state if servlet instance is created.
2) After invoking the init() method, Servlet comes in the ready state. In the ready state,
servlet performs all the tasks.
3) When the web container invokes the destroy() method, it shifts to the end state.

Steps to create a servlet example


There are given 6 steps to create a servlet example.
1. Create a directory structure
2. Create a Servlet

Page 445
https://gits-sln.blogspot.com Durga sir Java Notes

There are three ways to create the servlet.


I. By implementing the Servlet interface
II. By inheriting the GenericServlet class
III. By inheriting the HttpServlet class

3. Compile the Servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide
different jar files:
Jar file Server

1) servlet-api.jar Apache Tomcat

2) weblogic.jar Weblogic

3) javaee.jar Glassfish

4) javaee.jar JBoss

4. Create a deployment descriptor(web.xml)

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.

5. Start the server and deploy the project


6. Access the servlet
How Servlet works?
The server checks if the servlet is requested for the first time.
If yes, web container does the following tasks:
o loads the servlet class.
o instantiates the servlet class.
o calls the init method passing the ServletConfig object
else
o calls the service method passing request and response objects

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

Session Tracking Techniques

Why use Session Tracking?


To recognize the user It is used to recognize the particular user.

There are four techniques used in Session tracking:


1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
A cookie is a small piece of information(A cookie has a name, a single value, and optional
attributes and a version number.) that is persisted between the multiple client requests
 cookie is stored in the cache of the browser
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie

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

A filter is an object that is invoked at the preprocessing and postprocessing of a request.

It is mainly used to perform filtering tasks such as conversion, logging, compression,


encryption and decryption, input validation etc.

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.

Servlet with Annotation (feature of servlet3):


Annotation represents the metadata. If you use annotation, deployment descriptor
(web.xml file) is not required. But you should have tomcat7 as it will not run in the previous
versions of tomcat. @WebServlet annotation is used to map the servlet with the specified
name.

Interview question on servlet

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.

Advantages of JSP over Servlet


1) JSP technology is the extension to Servlet technology.
2) Easy to maintain
we can easily separate our business logic with presentation logic. In Servlet technology, we
mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and redeploy project
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code
The Lifecycle of a JSP Page
JSP Lifecycle is exactly same as the Servlet Lifecycle, with one additional first step, which
is, translation of JSP code to Servlet code. Following are the JSP Lifecycle steps:
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method

Page 449
https://gits-sln.blogspot.com Durga sir Java Notes

The JSP API


The JSP API consists of two packages:
1. javax.servlet.jsp
2. javax.servlet.jsp.tagext

JSP Scripting elements


provides the ability to insert java code inside the jsp.
1. scriptlet tag
used to execute java source code in JSP
Syntex: <% java source code %>
Example:1
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

Example:2
File: index.html
<html>
<body>
<form action="welcome.jsp">

Page 450
https://gits-sln.blogspot.com Durga sir Java Notes

<input type="text" name="uname">


<input type="submit" value="go"><br/>
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</body>
</html>

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.

<%! field or method declaration %>

Example-1: field declaration

<html>
<body>
<%! int data=50; %>

Page 451
https://gits-sln.blogspot.com Durga sir Java Notes

<%= "Value of the variable is:"+data %>


</body>
</html>

Example-2: method declaration

<html>
<body>
<%!
int cube(int n){
return n*n*n;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

JSP Implicit Objects


A list of the 9 implicit objects is given below:

Object Type Description

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

session HttpSession to set,get or remove attribute or to get session information.Eg:


session.setAttribute("user",name);

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

 <%-- JSP code to demonstrate how to use page


directive to import a package --%>

<%@page import = "java.util.Date"%>


<%Date d = new Date();%>
<%=d%>
 <%-- JSP code to demonstrate how to use
page directive to set the type of content --%>

<%@page contentType = "text" %>


This should be rendered in plain text,
<B> not </B> as HTML.

 <%-- provide a description of the JSP This information is not forward to client as
container ignores the information given in info attribute. --%>

<%@ page info="composed by Sonoo Jaiswal" %>

 <%-- 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. --%>

<%@ page buffer="16kb" %>

 <%-- 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

 <%-- We can deactivate EL evaluation in a single JSP page by specifying the


attribute isELIgnored=”true” --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
isELIgnored="false"
%>
EL expression result is: ${2 * 4 + 3 * 4}

 <%-- 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.

Syntax of include directive


<%@ include file="resourceName" %>
Code of the home.jsp page:
<%@include file="header.html" %>
<hr/>
<h2>This is main content</h2>
<hr/>
<%@include file="footer.html" %>

Code of the header.html page:


<h1>This is header</h1>

Code of the footer.html page:


<h5>This is footer</h5>

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.

Syntax of Taglib Directive

<@ taglib uri="uri" prefix="value">


<html>
<head>
<title>Tutorial and Example</title>
</head>
<body>
<h2 align="center">

Page 454
https://gits-sln.blogspot.com Durga sir Java Notes

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<c:out value="Welcome to JSP Taglib Directive"/>
</h2>
</body>
</html>
Exception Handling in JSP
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No2:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>

If we input No1 field value as 12 and No2 field value as 0 then we can find error by
error.jsp page

JSP Action Tags


JSP action tag is used to perform some specific tasks.
The action tags are used to control the flow between pages

JSP Action Tags Description

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

Page 455
https://gits-sln.blogspot.com Durga sir Java Notes

jsp:plugin embeds another components such as applet.

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.

Difference between jsp include directive and include action


JSP include directive JSP include action

includes resource at translation time. includes resource at request time.

better for static pages. better for dynamic pages.

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

Expression Language (EL) in JSP


 The Expression Language (EL) simplifies the accessibility of data stored in the Java
Bean component, and other objects like request, session, application etc.
 There are many implicit objects, operators and reserve words in EL.

Syntax for Expression Language (EL)


${ expression }
There are many implicit objects in the Expression Language. They are as follows:

Implicit Objects Usage

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

param it maps the request parameter to the single value

paramValues it maps the request parameter to an array of values

header it maps the request header name to the single value

headerValues it maps the request header name to an array of values

cookie it maps the given cookie name to the cookie value

initParam it maps the initialization parameter

pageContext it provides access to many objects request, session etc.

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 }

Arithmetic Operations available in EL


Following are the arithmetic operators avilable in EL:

Arithmetic Operation Operator

Addition +

Substraction -

Page 458
https://gits-sln.blogspot.com Durga sir Java Notes

Multiplication *

Division / and div

Remainder % and mod

Logical and Relational Operators available in EL


Following are the logical operator and comparators avilable in EL:

Logical and Relational Operator Operator

Equals == and eq

Not equals != and ne

Less Than < and lt

Greater Than > and gt

Greater Than or Equal >= and ge

Less Than or Equal <= and le

And && and and

Or || and or

Not ! and not

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

JSTL (JSP Standard Tag Library)


It represents a set of tags to simplify the JSP development.
Note: for JSTL we should add JSTL jar library file.
Advantage of JSTL

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

There JSTL mainly provides five types of tags:

Tag Name Description

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

JSTL Core Tags List

The syntax used for including JSTL core library in your JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

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:set It sets the result of an expression under evaluation in a 'scope' variable.

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:forTokens It iterates over tokens which is separated by the supplied delimeters.

c:param It adds a parameter in a containing 'import' tag's URL.

c:redirect It redirects the browser to a new URL and supports the context-relative
URLs.

c:url It creates a URL with optional query parameters.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<html>
<head>

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>

JSTL Function Tags


The syntax used for including JSTL function library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
JSTL Function Tags List

JSTL Functions Description

fn:contains() It is used to test if an input string containing the specified substring in


a program.

fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a


case insensitive way.

fn:endsWith() It is used to test if an input string ends with the specified suffix.

fn:escapeXml() It escapes the characters that would be interpreted as XML markup.

fn:indexOf() It returns an index within a string of first occurrence of a specified


substring.

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:split() It splits the string into an array of substrings.

fn:toLowerCase() It converts all the characters of a string to lower case.

fn:toUpperCase() It converts all the characters of a string to upper case.

fn:substring() It returns the subset of a string according to the given start and end
position.

fn:substringAfter() It returns the subset of string after a specific substring.

fn:substringBefore() It returns the subset of string before a specific substring.

fn:length() It returns the number of characters inside a string, or the number of

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.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>Using JSTL Functions</title>
</head>
<body>

<c:set var="String" value="Welcome to javatpoint"/>

<c:if test="${fn:contains(String, 'javatpoint')}">


<p>Found javatpoint string</p>
</c:if>

<c:if test="${fn:contains(String, 'JAVATPOINT')}">


<p>Found JAVATPOINT string</p>
</c:if>

</body>
</html>

JSTL Formatting tags


syntax used for including JSTL formatting library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

Formatting Tags Descriptions

fmt:parseNumber It is used to Parses the string representation of a currency, percentage or


number.

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:parseDate It parses the string representation of a time and date.

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.

fmt:message It display an internationalized message.

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

Custom Tags in JSP


Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and
separates the business logic from the JSP page.
The same business logic can be used many times by the use of custom tag.
Syntax to use custom tag

There are two ways to use the custom tag. They are given below:

<prefix:tagname attr1=value1....attrn=valuen />

<prefix:tagname attr1=value1....attrn=valuen >


body code
</prefix:tagname>

For creating any custom tag, we need to follow following steps:


1. Create the Tag handler class and perform action at the start or at the end of the
tag.
2. Create the Tag Library Descriptor (TLD) file and define tags
3. Create the JSP file that uses the Custom tag defined in the TLD file
Understanding flow of custom tag in jsp

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

1. Persistence store- Eg: file, data base s/w


2. Persistence store- Eg: file data, Db table record
3. Persistence operation- Eg: CURD operation means C(create)->insert, U(update)->update,
R(read)->select, D(delete)->delete
4. Persistence logic- Eg: I/O streams code, jdbc code, hibernate code
5. Persistence technology/ framework- Eg: jdbc, hibernate

 I/O stream
It is used for only small scale application.

Java application---------------------------------------------------flat file(simple text file)


(Serialization and deserialization)

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

 JDBC or O-R Mapping


it is used for medium scale or large scale application.

Java application--------------------------------------------DB s/w(RDBMS-eg: oracle, mysql etc.)

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

Draw Backs of JDBC:

 JDBC code data base software dependent persistence logic.


 Changing database software is complex process.
 JDBC code is not portable code across the multiple database software.
 We need to convert object notation data to simple value to use them in persistence logic.
 Exception handling is mandatory.
 There is no support of version and time stamping.
 There is no proper transition management support.
 It doesn’t support object level relationship.
 Boiler code plate problem- ->common logic –-> the logic comes to repeated in multiple
application
Eg: in a JDBC connection contain process
1. Register JDBC driver
2. Establish the connection
3. Create statement object

In order to overcome above problems, Hibernate came into picture..!

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

Advantages of Hibernate Framework


Following are the advantages of hibernate framework:

1) Open Source and Lightweight


Hibernate framework is open source under the LGPL license and lightweight.

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.

3) Database Independent Query


HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries. Before
Hibernate, if database is changed for the project, we need to change the SQL query as well that
leads to the maintenance problem.

4) Automatic Table Creation


Hibernate framework provides the facility to create the tables of the database automatically. So
there is no need to create tables in the database manually.

5) Simplifies Complex Join


Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status


Hibernate supports Query cache and provide statistics about query and database status.

Advantage of O-R Mapping persistence logic (Like


hibernate code)
1. Database software independent persistence logic.

2. Changing database software is quiet easy.

Page 467
https://gits-sln.blogspot.com Durga sir Java Notes

3. Persistence logic is portable across the multiple database software.

4. Persistence operation can be done directly on the object without converting them into the
simple value.

5. Boiler plate code problem can be minimize.

6. Exception handling is optional.

7. Gives built in middle ware services.

8. Allow to develop object based relationship.

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

Let's see the diagram of hibernate architecture:

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

Elements of Hiberdnate Architecture


SessionFactory
Configuration object is used to create a SessionFactory object. it is usually created during
application start up and kept for later use. You would need one SessionFactory object per
database using a separate configuration file.

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.

Hibernate Example using XML in Eclipse


in Eclipse IDE, we need to follow the following steps:
1. Create the java project
2. Add jar files for hibernate
3. Create the Persistent class
4. Create the mapping file for Persistent class
5. Create the Configuration file
6. Create the class that retrieves or stores the persistent object

Page 469
https://gits-sln.blogspot.com Durga sir Java Notes

7. Run the application


1) Create the java project
Create the java project by File Menu - New - project - java project . Now specify the project
name e.g. firsthb then next - finish .

2) Add jar files for hibernate


To add the jar files Right click on your project - Build path - Add external archives.
Note- at this time we must add database jar files for appropriate data like mysql jar or
oracle jar etc.

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>

<!-- database username -->


<property name = "hibernate.connection.username">root</property>

<!-- database password -->


<property name = "hibernate.connection.password">pp</property>

<!-- database dialect, different for different databases -->


<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- true value shows SQL query that is generated by hibrnate -->
<property name="show_sql">true</property>

<!-- path of hibernate mapping file -->


<mapping resource="customerm.hbm.xml"></mapping>

Page 471
https://gits-sln.blogspot.com Durga sir Java Notes

</session-factory>
</hibernate-configuration>

6) Create the class that retrieves or stores the persistent object


This class must be present inside of com.java.myfirsthb package

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;

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {


try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {


return sessionFactory;
}

public static void shutdown() {


// Close caches and connection pools
getSessionFactory().close();
}

Page 472
https://gits-sln.blogspot.com Durga sir Java Notes

7) Run the application


Before running the application, determine that directory structure is like this.

To run the hibernate application, right click on the Demo.java class - Run As - Java
Application.

Hibernate Example using Annotation in Eclipse


Hibernate Annotations are based on the JPA 2 specification and supports all the features. The
core advantage of using hibernate annotation is that you don't need to create mapping (hbm)
file. Here, hibernate annotations are used to provide the meta data.

SQL Dialects in Hibernate


 To connect to any database with hibernate, we need to specify the SQL dialect class in
hibernate.cfg.xml
Ex: To connect to oracle database we need to specify oracle dialect class in configuration xml as
below.

<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

Oracle (any version) org.hibernate.dialect.OracleDialect

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

You might also like