Core Java PDF
Core Java PDF
1|Page
JAVA Means DURGA SOFT
2|Page
JAVA Means DURGA SOFT
Index Page
1) Introduction 1-18
a. Flow control statements 19
b. Variables 32
c. Methods 41
d. Constructors 57
2) Oops 74
a. Inheritance
b. Polymorphism 97
c. Garbage Collector 112
d. Abstraction 114
e. Main method 121
f. Encapsulation
3) Packages 126-137
4) Interfaces 138-148
5) String mnipultions 149-161
6) Wrapper classes 162-169
7) Java.io 170-175
8) Exception handling 176-199
9) Multi Threading 200 – 217
10) Nested classes 218 – 228
11) Enumeration 229- 231
12) Collections & generics 232–279
13) Networking 280 – 285
14) Java.awt 286-311
15) Swings 312-318
16) i18n 319-333
17) Arrays 334-336
18) Java interview questions 337-341
19) Core java classroom schedule 357
3|Page
JAVA Means DURGA SOFT
JAVA introduction:-
Author : James Gosling
Vendor : Sun Micro System(which has since merged into Oracle Corporation)
Project name : Green Project
Type : open source & free software
Initial Name : OAK language
Present Name : java
Extensions : .java & .class & .jar
Initial version : jdk 1.0 (java development kit)
Present version : java 8 2014
Operating System : multi Operating System
Implementation Lang : c, cpp……
Symbol : coffee cup with saucer
Objective : To develop web applications
SUN : Stanford Universally Network
Slogan/Motto : WORA(write once run anywhere)
Hadoop Magic
Adv java Selenium
structs
Android
webservices
Salesforse
spring MDM ADF
4|Page
JAVA Means DURGA SOFT
Learning process:-
Corejava
Adv java
Hibernate structs
Web services,tools(ant,maven,svn…..)
Spring
Java keywords:-
Data Types
byte
short
int method-level:-
long void
float return
double (2) Exception handling:-
char try
boolean Object-level:- catch
(8) new finally
this throw Modifiers:-
Flow-Control:- super throws public
if instanceof (5) private
else (4) protected
switch 1.5 version:- abstract
case source-file: enum final
default class assert static
break extends (2) strictfp
for interface native
while implements unused:- transient
do package goto volatile
continue import const synchronized
(10) (6) (2) (11)
5|Page
JAVA Means DURGA SOFT
JAVA VERSIONS:-
VERSION YEAR
Java Alpha & beta : 1995
JDK 1.0 : 1996
JDK1.1 : 1997
J2SE 1.2 : 1998
J2SE 1.3 : 2000
J2SE 1.4 : 2002
J2SE 1.5 : 2004
JAVA SE 6 : 2006
JAVA SE 7 : 2011
JAVA SE 8 : 2014
applications use #include 4)cpp language the
statement. predefined is maintained in
Ex:- #include<stdio.h> the form of header files.
Differences:- 7) To print some statements Ex:- iostream.h
into output console use
C-lang
“printf” function. 5) The header files contains
1) Author: Dennis Ritchie Printf(“hi ratan ”); predefined functions.
Ex:- cout,cin….
2) Implementation
8)extensions used :-.c ,.obj ,
languages: BCPL, B…
.h 6) To make available
3) In C lang program predefined support into our
executionstarts frommain application use
methodcalled by Operating #include statement.
system. Ex:- #include<iostream>
6|Page
JAVA Means DURGA SOFT
functions printf,scanf…..
cpp-language:-
functions cout,cin….
7|Page
JAVA Means DURGA SOFT
java-language:-
java-language james gosling public static void main(String[] args)
(execution startsfrom main)
packages java.lang System.out.println(“ratan”);
(used to print the output)
classes & interfaces System,String……..
JAVA Features:-
1. Simple 2. Object Oriented 3. Platform Independent4.Architectural Neutral
5. Portable 6. Robust 7.Secure 8.Dynamic
9. Distributed 10.Multithread 11.Interpretive 12.High Performance
1. Simple:-
Java is a simple programming language because:
Java technology has eliminated all the difficult and confusion oriented concepts
like pointers, multiple inheritance in the java language.
The c,cpp syntaxes easy to understand and easy to write. Java maintains C and
CPP syntax mainly hence java is simple language.
Java tech takes less time to compile and execute the program.
2. Object Oriented:-
Java is object oriented technology because to represent total data in the form of object.
By using object reference we are calling all the methods, variables which is present in
that class.
Class data
Class Test
{logics } Test t=new Test();
t
3. Platform Independent :-
Compile the Java program on one OS (operating system)that compiled file can
execute in any OS(operating system) is called Platform Independent Nature.
8|Page
JAVA Means DURGA SOFT
The java is platform independent language. The java applications allow its
applications compilation one operating system that compiled (.class) files can be
executed in any operating system.
exe
Test.class JVM windows
Test.java
exe
JVM linux
Javac
JVM
exe
JVM macos
exe solaris
source file compilation JVM understandable file output console
4. Architectural Neutral:-
Java tech applications compiled in one Architecture (hardware----RAM, Hard
Disk) and that Compiled program runs on any hardware architecture(hardware) is called
Architectural Neutral.
5. Portable:-
In Java tech the applications are compiled and executed in any OS(operating
system) and any Architecture(hardware) hence we can say java is a portable language.
6. Robust:-
Any technology if it is good at two main areas it is said to be ROBUST
1. Exception Handling
2. Memory Allocation
JAVA is Robust because
JAVA is having very good predefined Exception Handling mechanism whenever
we are getting exception we are having meaning full information.
JAVA is having very good memory management system that is Dynamic Memory
(at runtime the memory is allocated) Allocation which allocates and deallocates
memory for objects at runtime.
7. Secure:-
To provide implicit security Java provide one component inside JVM called
Security Manager.
To provide explicit security for the Java applications we are having very good
predefined library in the form of java.Security.package.
9|Page
JAVA Means DURGA SOFT
8. Dynamic:-
Java is dynamic technology it follows dynamic memory allocation(at runtime the
memory is allocated) and dynamic loading to perform the operations.
9. Distributed:-
By using JAVA technology we are preparing standalone applications and Distributed
applications.
Standalone applications are java applications it doesn’t need client server architecture.
web applications are java applications it need client server architecture.
Distributed applications are the applications the project code is distributed in multiple
number of jvm’s.
10. Multithreaded: -
Thread is a light weight process and a small task in large program.
If any tech allows executing single thread at a time such type of technologies is
called single threaded technology.
If any technology allows creating and executing more than one thread called as
multithreaded technology called JAVA.
11. Interpretive:-
JAVA tech is both Interpretive and Completive by using Interpretator we are
converting source code into byte code and the interpretator is a part of JVM.
12. High Performance:-
If any technology having features like Robust, Security, Platform Independent, Dynamic
and so on then that technology is high performance.
Download the software from internet based on your operating system. The software is different
from 32-bit operating and 64-bit operating system.
10 | P a g e
JAVA Means DURGA SOFT
After installing the software the java folder is available in the fallowing location
Local Disk c: ------program Files--------java----jdk(java development kit),jre(java
runtime environment)
To check whether the java is installed in your system or not go to the command prompt. To
open the command prompt
Start ----------run------open: cmd-----ok
Command prompt is opened.
In the command prompt type :- javac
‘javac’ is not recognized is an internal or external command, operable program or batch
file.
Whenever we are getting above information at that moment the java is installed but the java is
not working properly.
C:/>javac
Whenever we are typing javac command on the command prompt
1) Operating system will pickup javac command search it in the internal operating system
calls. The javac not available in the internal command list .
2) Then operating system goes to environmental variables and check is there any path is
sets or not. up to now we are not setting any path. So operating system don’t know
anything about javac command Because of this reason we are getting error message.
Hence we have to environmental variables. The main aim of the setting environmental
variable is to make available the fallowing commands javac,java,javap (softwares) to the
operating system.
To set the environmental variable:-
My Computer (right click on that) ---->properties----->Advanced--->Environment Variables---->
11 | P a g e
JAVA Means DURGA SOFT
In above example String & System classes are present predefined java.lang package hence must import
that package by using import statement.
To import the classes into our application we are having two approaches,
1) Import all class of particular package.
a. Import java.lang.*; //it is importing all classes of java.lang package.
2) Import required classes
12 | P a g e
JAVA Means DURGA SOFT
a. Import java.lang.System;
b. Import java.lang.String;
In above two approaches second approach is best approach because we are importing application
required classes.
Note: - The source file allowed only one public class, if we are trying to declare multiple public classes
then compiler generate error message.
13 | P a g e
JAVA Means DURGA SOFT
Note:- in java .class file files generated by compiler at compilation time and .class file generation based
on number of classes present in source file.
If the source file contains 100 classes after compilation compiler generates 100 .class files
The compiler generate .class file and .class file contains byte code instructions it is intermediate code.
Note 1:- compiler is translator it is translating .java file to .class where as JVM is also a translator
it istranslating .class file to machine code.
Note 2:- compiler understandable file format is .java file but JVM understandable file format is .class
Executing all generated .class files:-
14 | P a g e
JAVA Means DURGA SOFT
D:\ratan>java Test
Hi Ratan
D:\ratan>java A
Error: Main method not found in class A, please define the main method as:
public static void main(String[] args)
D:\ratan>java B
Error: Main method not found in class B, please define the main method as:
public static void main(String[] args)
D:\ratan>java XXX
Error: Could not find or load main class XXX
Bytecode
15 | P a g e
Source Code
JAVA Means DURGA SOFT
Example application :-
The default package in java is java.lang package it means if we are importing or not by default
that package is imported.
In below example importing classes are optional.
class Test
{ public static void main(String[] args)
{ System.out.println("hi ratan");
}
}
Example Application:-
The class contains main method is called Mainclass and java allowes to declare multiple main
class in a single source file.
class Test1
{ public static void main(String[] args)
{ System.out.println("Test1 World!");
}
}
class Test2
{ public static void main(String[] args)
{ System.out.println("Test2 World!");
}
}
class Test3
{ public static void main(String[] args)
{ System.out.println("Test3 World!");
}
16 | P a g e
JAVA Means DURGA SOFT
}
D:\morn11>java Test1 D:\morn11>java Test2 D:\morn11>java Test3
Test1 World! Test2 World! Test3 World!
Class Elements:-
Class Test
{
1. variables int a = 10;
2. methods void add() {business logic }
3. constructors Test() {business logic }
4. instance blocks {business logic }
5. static blocks static {business logic }
}
17 | P a g e
JAVA Means DURGA SOFT
NOTE:-The coding standards are applicable for predefined library not for user defined library .But it is
recommended to fallow the coding standards for user defined library also.
Java Tokens:-
Smallest individual part of a java program is called Token. It is possible to provide any number of
spaces in between two tokens.
Example:-
Class Test
{
Public static void main
( String[] args )
{ int a = 10 ;
System . out . println (
“java tokens”);
}
}
Tokens are---------class,test,{,”,* …………….etc
Java Comments :-
Comments are used to provide detailed description about application.
comments are non executable code.
There are 3 types of comments.
1) Single line Comments:-
By using single line comments we are providing description about our program within a
single line.
Starts with…………….>// (double slash)
Syntax:- //description
2) Multi line Comments:-
This comment is used to provide description about our program in more than one line.
Syntax: - /*…………….line-1
……………..line-2
*/
3) Documentation Comments:-
al we are using document comment to prepare API(Application programming interface)
documents.. We will discuss later chapter.
Syntax: - /**……………..line-1
*………………line-2
*/
Example:-
/*project name:-green project
team size:- 6
team lead:- ratan
*/
class Test//class declaration
{ //class starts
18 | P a g e
JAVA Means DURGA SOFT
Java Identifiers:-
any name in the java program like variable name, classname, methodname, interface name is
called identifier.
class Test Test-------identifier
{ void add() add-------identifier
{ int a=10; a----------identifiers
int b=20; b----------identifiers
}
};
19 | P a g e
JAVA Means DURGA SOFT
}
};
4. In the java applications it is possible to declare all the predefined class names and predefined
interfaces names as a identifier. But it is not recommended to use.
class Test
{ public static void main(String[] args)
{ int String=10; //predefind String class
int Serializable=20; //predified Seriaiable Interface
float Exception=10.2f; //predefined Exception class
System.out.println(String);
System.out.println(Serializable);
System.out.println(Exception);
}
};
If is taking condition that condition must be Boolean condition otherwise compiler will raise
compilation error.
The curly brasses are optional whenever we are taking single statements and the curly
brasses are mandatory whenever we are taking multiple statements.
Ex-1:-
class Test
{ public static void main(String[] args)
{ int a=10; int b=20;
if (a<b)
{ System.out.println("if body / true body"); }
else
{ System.out.println("else body/false body "); }
}
}
Ex -2:- For the if the condition it is possible to provide Boolean values.
20 | P a g e
JAVA Means DURGA SOFT
class Test
{ public static void main(String[] args)
{ if (true)
{ System.out.println("true body"); }
else
{ System.out.println("false body"); }
}
}
Ex-3:-in c-language 0-false & 1-true but these convensions are not allowed in java.
class Test
{ public static void main(String[] args)
{ if (0)
{ System.out.println("true body"); }
else
{ System.out.println("false body"); }
}
}
Switch statement:-
1) Switch statement is used to declare multiple selections.
2) Inside the switch It is possible to declare any number of cases but is possible to declare only
one default.
3) Switch is taking the argument the allowed arguments are
a. Byte b. Short c. Int d.Char e.String(allowed in 1.7 version)
4) Float and double and long is not allowed for a switch argument because these are having
more number of possibilities (float and double is having infinity number of possibilities)
hence inside the switch statement it is not possible to provide float and double and long as a
argument.
5) Based on the provided argument the matched case will be executed if the cases are not
matched default will be executed.
Syntax:-
switch(argument)
{
case label1 : sop(“ “);break;
case label2 : sop(“ “);break;
| |
default : sop(“ “); break;
}
Eg-1:Normal input and normal output.
class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{
case 10:System.out.println("anushka"); break;
case 20:System.out.println("nazriya"); break;
21 | P a g e
JAVA Means DURGA SOFT
22 | P a g e
JAVA Means DURGA SOFT
class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{ case 10:System.out.println("10"); break;
}
}
};
Ex 6:-Inside the switch cases are optional part.
class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{ default: System.out.println("default"); break;
}
}
};
Ex 7:-inside the switch both cases and default Is optional.
public class Test
{ public static void main(String[] args)
{ int a=10;
switch(a)
{ }
}
}
Ex -8:-inside the switch independent statements are not allowed. If we are declaring the statements
that statement must be inside the case or default.
public class Test
{ public static void main(String[] args)
{ int x=10;
switch(x)
{ System.out.println("Hello World");
}
}
}
Ex-9:-internal conversion of char to integer.
Unicode values a-97 A-65
class Test
{ public static void main(String[] args)
{ int a=65;
switch (a)
{
case 66:System.out.println("10"); break;
case 'A':System.out.println("20"); break;
case 30:System.out.println("30"); break;
23 | P a g e
JAVA Means DURGA SOFT
24 | P a g e
JAVA Means DURGA SOFT
}
Ex-13 :-inside the switch we are able to declare the default statement starting or middle or end of
the switch.
class Test
{ public static void main(String[] args)
{ int a=100;
switch (a)
{
default: System.out.println("default");
case 10:System.out.println("10");
case 20:System.out.println("20");
}
}
};
Ex -14:-The below example compiled and executed only in above 1.7 version because switch is taking
String argument from 1.7 version.
class Sravya
{ public static void main(String[] args)
{ String str = “aaa”;
switch (str)
{ case "aaa" : System.out.println("Hai"); break;
case "bbb" : System.out.println("Hello"); break;
case "ccc" : System.out.println("how"); break;
default : System.out.println("what"); break;
}
}
}
Ex-15:-inside switch the case labels must be within the range of provided argument data type
otherwise compiler will raise compilation error “possible loss of precision”.
class Test
{ public static void main(String[] args)
{ byte b=125;
switch (b)
{
case 125:System.out.println("10");
case 126:System.out.println("20");
case 127:System.out.println("30");
case 128:System.out.println("40");
default:System.out.println("default");
}
}
};
25 | P a g e
JAVA Means DURGA SOFT
Iteration Statements:-
By using iteration statements we are able to execute group of statements repeatedly or more number of
times.
1) For 2) while 3) do-while
for syntax:-
for (initialization ;condition ;increment/decrement )
{ Body;
}
Flow of execution in for loop:-
1 2 5 4 7
f
for (initialization f
;condition 5 ;increment/decrement f f )
{ o o f o o
r Body; r3 o
6 r r
} (i (i
o r
6 (i (i
n n
r f(i n n
The above processi is repeated i(i n
until
o the i
condition i false. If the condition is false the loop is stopped.
is
t
Initialization part:- t
n i
r t t
i
1) Initialization part itii is possible t
(i to takei the singe
i initialization it is not possible to take the more
than onea initialization.
at in a a
With out for loopli ili ia li li By using for loop
class Test z za lit z z class Test
{ a a
li z
i a a {
t
public static tz
void main(String[] aa args) t t public static void main(String[] args)
{ i System.out.println("ratan");
ia tli i i {
oSystem.out.println("ratan");
o
t i
z o o for (int i=0;i<5;i++)
nSystem.out.println("ratan");
n
i o
a n n {
; System.out.println("ratan");
;o n
t ; ; System.out.println("Rattaiah");
cSystem.out.println("ratan");
cn ;i c c }
} o o
; c
o o o }
}; n n
c o
n n n }
d d
o n
; d d
Initialization:- i in cd i i
Ex1: Inside the tfor loop initialization td io part is optional.
t t
class Test i ii t
n i i
{ o
public static void main(String[]o
t i
d args) o o
{ n int i=0; i n o
i n n
;ifor (;i<10;i++) ;i
o tn ;i ;i
n{ n
System.out.println("Rattaiah");
n ;i
i n n
c} c;i n
o c c
} r rn c
n r r
} e ec r;i e e
m
Ex 2:- Instead of initialization m
r it isn possible to take m
e m any number of System.out.println(“ratna”)
statements and e each andeeeverycm statement ise separated
e by camas(,) .
class Test n n
m e
r n n
t te n
e t t
/ /n t
m / /
d d
t /
e d d
e /e d
n e e
26 | P a g e c cd et c c
r re c/ r r
e ec r
d e e
m m
r e
e m m
JAVA Means DURGA SOFT
Conditional part:-
Ex 1:-inside for loop conditional part is optional if we are not providing condition at the time of
compilation compiler will provide true value.
class Test
{ public static void main(String[] args)
{ for (int i=0;;i++)
{ System.out.println("Rattaiah");
}
}
}
Increment/decrement:-
Ex1:- Inside the for loop increment/decrement part is optional.
class Test
{ public static void main(String[] args)
{ for (int i=0;i<10;)
27 | P a g e
JAVA Means DURGA SOFT
{ System.out.println("Rattaiah");
}
}
}
Ex 2:- Instead of increment/decrement it is possible to take the any number of SOP() that and each
and every statement is separated by camas(,).
class Test
{ public static void main(String[] args)
{ for (int i=0;i<10;System.out.println("aruna"),System.out.println("nagalakshmi"))
{ System.out.println("Rattaiah");
i++;
}
}
}
Note : Inside the for loop each and every part is optional.
for(;;)------------represent infinite loop because the condition is always true.
Example :-
class Test
{ static boolean foo(char ch)
{ System.out.println(ch);
return true;
}
public static void main(String[] args)
{ int i=0;
for (foo('A');foo('B')&&(i<2);foo('C'))
{ i++;
foo('D');
}
}
};
Ex:- compiler is unable to identify the ex:- compiler able to identify the unreachable
unreachable statement. Statement.
class Test class Test
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
for (int i=1;i>0;i++) for (int i=1;true;i++)
{ {
System.out.println("infinite times ratan");
} System.out.println("ratan");
System.out.println("rest of the code"); }
} System.out.println("rest of the code");
} }
}
28 | P a g e
JAVA Means DURGA SOFT
While loop:-
Syntax:- while (condition) //condition must be Boolean & mandatory.
{ body;
}
Ex :-
class Test
{ public static void main(String[] args)
{ int i=0;
while (i<10)
{ System.out.println("rattaiah");
i++;
}
}
}
29 | P a g e
JAVA Means DURGA SOFT
i++;
}while (i<10);
}
}
30 | P a g e
JAVA Means DURGA SOFT
class Test
{ public static void main(String[] args)
{ if (true)
{ System.out.println("ratan");
break;
System.out.println("nandu");
}
}};
Continue:-(skip the current iteration and it is continue the rest of the iterations normally)
class Test
{ public static void main(String[] args)
{ for (int i=0;i<10;i++)
{ if (i==5)
continue;
System.out.println(i);
}}}
Java primitive Data Types:-
1. Data types are used to represent type of the variable & expressions.
2. Representing how much memory is allocated for variable.
3. Specifies range value of the variable.
There are 8 primitive data types in java
Data Type size(in bytes) Range default values
byte 1 -128 to 127 0
short 2 -32768 to 32767 0
int 4 -2147483648 to 2147483647 0
long 8–9,223,372,036,854,775,808 to 9 ,223,372,036,854,775,8070
float 4 -3.4e38 to 3.4e 0.0
double 8 0.0
char 2 0 to 6553 single space
Boolean no-size no-range false
31 | P a g e
JAVA Means DURGA SOFT
Note :-
To represent numeric values (10,20,30…etc) use byte,short,int,long.
To represent point values(floating point values 10.5,30.6…etc) use float,double.
To represent character use char and take the character within single quotes.
To represent true ,false use Boolean.
Example :-//Test.java
class Test
{ public static void main(String[] args)
{ float f=10.5;
System.out.println(f);
double d=20.5;
System.out.println(d);
}
}
D:\ratan>javac Test.java
Test.java:3: error: possible loss of precision
float f=10.5;
required: float
found: double
in above example decimal value(10.5) by default double value hence compiler generating error
message so to represent float value use f constant.
32 | P a g e
JAVA Means DURGA SOFT
Example :-
class Test
{ public static void main(String[] args)
{ System.out.println("information about byte data type");
System.out.println("byte size="+Byte.SIZE);
System.out.println("byte min value="+Byte.MIN_VALUE);
System.out.println("byte max value="+Byte.MAX_VALUE);
Java Variables:-
Variables are used to hold the constant values by using these values we are achieving project
requirements/functionality.
While declaring variable must specify the type of the variable by using data types.
Variables are also known as fields of a class or properties of a class.
Note :- All variables must have a type. You can use primitive types such as int, float, boolean, etc. Or
you can use reference types, such as strings, arrays, or objects.
Variable declaration is composed of three components in order,
1) Zero or more modifiers. 2) The variable type. 3) The variable name.
public int a=10;
public ----> modifier (specify permission)
int ----> data type (represent type of the variable)
a ----> variable name
10 ----> constant value or literal;
; ----> statement terminator
There are three types of variables in java
1. Local variables.
2. Instance variables.
3. Static variables.
Local variables:-
The variables which are declare inside a method or constructor or blocks those variables are
called local variables.
class Test
{ public static void main(String[] args) //execution starts from main method
{ int a=10; //local variables
int b=20;
System.out.println(a);
System.out.println(b);
}
33 | P a g e
JAVA Means DURGA SOFT
}
We are able to access local variable only inside the method or constructor or blocks only, it is
not possible to access outside of method or constructor or blocks.
void add()
{ int a=10; //local variable
System.out.println(a); //possible
}
void mul()
{ System.out.println(a); //not-possible
}
For the local variables memory allocated when method starts and memory released when
method completed.
void m1() //memory allocated when method starts
{ //local variable
int a=10;
int b=20;
}//memory released when method completed
Instance variables (non-static variables):-
The variables which are declare inside a class and outside of methods those variables are called
instance variables.
Instance variables are visible inall methods and constructorsof a particular class.
Instance variables are also known as non-static fields. And it is having global visibility.
For instance variables memory allocated during object creation time and memory released
when object is destroyed.
Instance variables are stored in heap memory.
34 | P a g e
JAVA Means DURGA SOFT
{ //instance variables
int a=10; int b=20;
//static method
public static void main(String[] args)
{ //Static Area
Test t=new Test();
System.out.println(t.a);
System.out.println(t.b);
t.m1(); //instance method calling
}
//instance method
void m1()//user defined method must called by user in main method
{ //instance area
System.out.println(a);
System.out.println(b);
}//main ends
};//class ends
Static variables (class variables):-
The variables which are declared inside the class and outside of the methods with static
modifier is called static variables.
Static variables are visible all methods and constructors of a particular class.
Static variables memory allocated at the time of .class file loading and memory released at .class
file unloading time.
Static variables are stored in non-heap memory.
Static variables & methods accessing:-
(Static variables& static methods)
35 | P a g e
JAVA Means DURGA SOFT
System.out.println(Test.b);
}
};
Calling of static variables:-
We are able to access the static members inside the static area in three ways.
Directly possible.
By using class name.
By using reference variable.
In above three approaches second approach is best approach .
class Test
{ static int x=100; //static variable
public static void main(String[] args)
{ System.out.println(a); //1-way(directly possible)
System.out.println(Test.a); //2-way(By using class name)
Test t=new Test(); System.out.println(t.a); //3-way(By using reference variable)
}
};
Example: - When we create object inside method that object is destroyed when method
completed if any other method required object then create the object inside that method.
class Test
{ //instance variable
int a=10; int b=20;
static void m1()
{ Test t = new Test();
System.out.println(t.a);
System.out.println(t.b);
}
static void m2()
{ Test t = new Test();
System.out.println(t.a);
System.out.println(t.b);
}
public static void main(String[] args)
{ Test.m1(); //static method calling
Test.m2(); //static method calling
}
};
Example:-
class Test
{ // instance variables
int a=10;
int b=20;
static int c=30; //static variables
static int d=40;
void m1() //instance method
36 | P a g e
JAVA Means DURGA SOFT
{ System.out.println(a);
System.out.println(b);
System.out.println(Test.c);
System.out.println(Test.d);
}
static void m2() //static method
{ Test t = new Test();
System.out.println(t.a);
System.out.println(t.b);
System.out.println(Test.c);
System.out.println(Test.d);
}
public static void main(String[] args)
{ Test t = new Test(); t.m1(); //instance method calling
Test.m2(); //static method calling
}
};
Variables VS default values:-
Case 1:-for the instance variables JVM will assign default values.
class Test
{ int a;
boolean b;
public static void main(String[] args)
{ //access the instance variables by using object
Test t=new Test();
System.out.println(t.a);
System.out.println(t.b);
}
};
Case 2:-for the static variables JVM will assign default values.
class Test
{ static int a;
static float b;
public static void main(String[] args)
{ //access the static variable by using class Names
System.out.println(Test.a);
System.out.println(Test.b);
}
};
Case 3:-
For the instance and static variables JVM will assign default values butfor the local variables the
JVM won’t provide default values.
37 | P a g e
JAVA Means DURGA SOFT
In java before using localvariables must initialize some values to the variables otherwise compiler
will raise compilation error “variable a might not have been initialized”.
class Test
{ public static void main(String[] args)
{ //local variables (access directly)
int a;
int b;
System.out.println(a);
System.out.println(b);
}
};
D:\>javac Test.java
Test.java:6: variable a might not have been initialized
System.out.println(a);
Class Vs Object:-
Class is a logical entity it contains logics where as object is physical entity it is representing
memory.
Class is blue print it decides object creation without class we are unable to create object.
Based on single class (blue print) it is possible to create multiple objects but every object
occupies memory.
Civil engineer based on blue print of house it is possible to create multiple houses in different
places but every house required some area.
We are declaring the class by using class keyword but we are creating object by using new
keyword.
We are able to create object in different ways like
o By using new operator
o By using clone() method
o By using new Instance()
o By using factory method.
o By using deserialization….etc
But we are able to declare the class by using class keyword.
We will discuss object creation in detailed in constructor concept.
Example :-
class Test
{ int a=10; //instance variable
38 | P a g e
JAVA Means DURGA SOFT
Note 1 :- The variables which are declared inside the method or constructor or blocks those variables
are called local variables and we are able to access(usage) local variables only inside the method or
constructor or blocks , for the local variables memory is allocated when method starts and memory id
destroyed when method ends and these variables are stored in stack memory & call the local variables
directly .
Note 2:-The variables which are declared inside the class and outside of the method those variables are
called instance variables and we are able to access (usage) instance members inside the class,for the
instance variables memory is allocated duringobject creation and memory destroyed when object is
destroyed & these variables are stored in heap memory & call the instance members (variables &
methods) by using object.
Note 3 :- The variables which are declared inside the class and outside of the method with static modifier
those variables are called static variables & we are able to access (usage) static members inside the
class& for the static variables memory is allocated during .class loading and memory destroyed .class
file unloading & access the static members(variables & methods) by using class Name.
39 | P a g e
JAVA Means DURGA SOFT
Summary of variables:-
Characteristic Local variable instance variable static variables
where declared inside method or inside the classoutside inside the class outside
Constructor or block. Of methods of methods.
Use within the method inside the class all the inside the class all
methods and constructors. Methods& constructors.
Initial values none, must initialize the value default values are default values are
before first use. Assigned by JVM.Assigned by JVM.
Relation with Object no way related to object. for every object one copy for all objects one
Of instance variable created copy is created.
It means memory. Single memory.
+ operator:-
One operator with multiple behaviors is called operator over loading but java is not supporting
operator overloading concept and only one overloaded operator in java is +
o If two operands are integers then + perform addition.
40 | P a g e
JAVA Means DURGA SOFT
Java.util.Scanner(Dynamic Input):-
1. Scanner class present in java.util package and it is introduced in 1.5 version.
2. Scanner class is used to take dynamic input from the keyboard.
Scanner s = new Scanner(System.in);
to get int value ----> s.nextInt()
to get float value ---> s.nextFloat()
to get byte value ---> s.nextbyte()
to get String value ---> s.next()
to get single line ---> s.nextLine()
to close the input stream ---> s.close()
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in); //used to take dynamic input from keyboard
System.out.println("enter emp hobbies");
String ehobbies = s.nextLine();
System.out.println("enter emp no");
int eno=s.nextInt();
System.out.println("enter emp name");
String ename=s.next();
System.out.println("enter emp salary");
float esal=s.nextFloat();
System.out.println("*****emp details*****");
System.out.println("emp no----->"+eno);
System.out.println("emp name---->"+ename);
System.out.println("emp sal------>"+esal);
System.out.println("emp hobbies------>"+ehobbies);
41 | P a g e
JAVA Means DURGA SOFT
Inside the class it is possible to declare any number of instance methods &static methods based on
the developer requirement.
It will improve the reusability of the code and we can optimize the code.
Note :- Whether it is an instance method or static method the methods are used to provide
business logics of the project.
Instance method :-
void m1() //instance method
{ //body instance area
}
Note: - for the instance members memory is allocated during object creation hence access the
instance members by using object(reference-variable).
Syntax:-
Void m1() { } //instance method
Test t = new Test();
42 | P a g e
JAVA Means DURGA SOFT
static method:-
static void m1() //instance method
{ //body static method
}
Note: - for the static member’s memory allocated during .class file loading hence access the
static members by using class-name.
Syntax:-
Static void m2() { } //static method
Classname.staticmethod( ); // call static method by using class name
Test.m2( );
Syntax:-
[modifiers-list] return-Type Method-name (parameters list) throws Exception
Modifiers-list ------ represent access permissions.---- [optional]
Return-type ------ functionality return value---- [mandatory]
Method name ------ functionality name ----- [mandatory]
Parameter-list ------ input to functionality ---- [optional]
Throws Exception ------ representing exception handling--- [optional]
Method Signature:-
Method Signature is nothing but name of the method and parameters list. Return type and
modifiers list not part of a method signature.
Syntax:- Method-name(parameter-list)
Ex:- m1(int a)
m1(int a,int b)
43 | P a g e
JAVA Means DURGA SOFT
class Test
{ //instance methods
void Sravya() { System.out.println("Sravya"); }
void soft() { System.out.println("software solutions"); }
public static void main(String[] args)
{ Test t=new Test();
t.Sravya(); //calling of instance method by using object name [ t ]
t.soft(); //calling of instance method by using object name [ t ]
}
}
class Test
{ //instance methods
void m1(int i,char ch) //local variables
{ System.out.println(i+"-------"+ch); }
void m2(double d ,String str) //local variables
{ System.out.println(d+"------"+str); }
public static void main(String[] args)
{ Test t=new Test();
t.m1(10,'a'); //m1() method calling
t.m2(10.2,"ratna"); //m2() method calling
}
}
44 | P a g e
JAVA Means DURGA SOFT
Example 6:-For java methods it is possible to provide Objects as a parameters(in real time project
level).
Case 1:- project code at student level.
class X{}
class Emp{}
class Y{}
class Test
{ void m1(X x ,Emp e)
{ System.out.println("m1 method");
}
static void m2(int a,Y y)
{ System.out.println("m2 method");
}
public static void main(String[] args)
{ Test t = new Test();
X x = new X();
Emp e = new Emp();
t.m1(x,e); //calling of instance method by using object
Y y = new Y();
Test.m2(10,y); //calling of static method by using class-name
}
}
45 | P a g e
JAVA Means DURGA SOFT
46 | P a g e
JAVA Means DURGA SOFT
}
}
Example-8:-method calling
m1()--calling --m2()----calling------ m3()
m1()<-------after completion-m2()<------after completion m3()
class Test
{ void m1()
{ m2(); //m2() method calling
System.out.println("m1");
m2(); //m2() method calling
}
void m2()
{ m3(100); //m3() method calling
System.out.println("m2 ");
m3(200); //m3() method calling
}
void m3(int a) { System.out.println("m3 "); }
public static void main(String[] args)
{ Test t=new Test();
t.m1(); //m1() method calling
}
}
Example-9:-
For java methods return type is mandatory otherwise the compilation will generate
error message “invalid method declaration; return type required“.
class Test
{ void m1() { System.out.println("hi m1-method"); }
m2() { System.out.println("hi m2-method"); }//return type is mandatory
public static void main(String[] args)
{
Test t=new Test();
t.m1();
t.m2();
}
}
Example-10 :-
Inside the java class it is not possible to declare two methods with same signature , if we are
trying to declare two methods with same signature compiler will raise compilation error “m1()
is already defined in Test ”
Java class not allowed Duplicate methods.
It is possible to write,
void m1()
Void m1(int a)
47 | P a g e
JAVA Means DURGA SOFT
But the above method signatures are different it is method overloading concept.
class Test
{ void m1() { System.out.println("rattaiah"); }
void m1() { System.out.println("Sravya"); }
public static void main(String[] args)
{ Test t=new Test();
t.m1();
}
}
Example-11 :-
Declaring the class inside another class is called inner classes, java supports inner classes.
Declaring the methods inside another methods is called inner methods but java not supporting
inner methods concept if we are trying to declare inner methods compiler generate error
message “illegal start of expression”.
class Test
{ void m1()
{ void m2() //inner method
{ System.out.println(“m2() inner method"); }
System.out.println("m1() outer method");
}
public static void main(String[] args)
{ Test t1=new Test();
t.m1();
}
};
Ex :- the below example is valid because it is returning int value by using return statement.
int m1()
{ System.out.println("Anushka");
return 100;
}
48 | P a g e
JAVA Means DURGA SOFT
4. Inside the method we are able to use only one return statement(except flow control statement)
that must be last statement of the method otherwise compiler will generate error message
“unreachable statement”.
Ex : the below example is invalid because return statement is must be last statement.
int m1()
{ return 100;
System.out.println("Anushka");
}
Ex :the below example valid because return statement is last statement .
int m1()
{ System.out.println("Anushka");
return 100;
}
5. Every method is able to return value but holding (storing) that return value is optional ,but it is
recommended to hold the value.
class Test
{ int m1(int a,char ch) //local variables
{ System.out.println("***m1 method***");
System.out.println(a+"---"+ch);
return 100; //method return value
}
boolean m2(String str1,String str2) //local variables
{ System.out.println("****m2 method****");
System.out.println(str1+"---"+str2);
return true; //method return value
}
String m3()
{ return "ratan"; } //method return value
public static void main(String[] args)
{ Test t=new Test();
int x = t.m1(10,'a'); //m1(int,char) method calling
System.out.println("m1() return value-->"+x); //printing m1() method return value
boolean b = t.m2("ratan","anu"); //m2(String,String) method calling
System.out.println("m2() return value-->"+b); //printing m2() method return value
String str = t.m3(); //m3() method calling
System.out.println("m3() return value-->"+str); //printing m3() method return value
}//end main
}//end class
49 | P a g e
JAVA Means DURGA SOFT
Returns local variable as a return value Returns instance variable as a return value(no
class Test local variable)
{ int a=10; class Test
int m1(int a) { int a=10;
{ int m1()
System.out.println("m1() method"); {
return a; //return local variable System.out.println("m1() method");
} return a; //returns instance value
public static void main(String[] args) }
{ Test t = new Test(); public static void main(String[] args)
int x = t.m1(100); { Test t = new Test();
System.out.println(x); int x = t.m1();
} System.out.println(x);
} }
D:\>java Test }
m1() method D:\>java Test
100 m1() method
10
If the application contains both local & instance variables with same name then first priority goes to
local variables but to return instance value use this keyword.
class Test
50 | P a g e
JAVA Means DURGA SOFT
{ int a=10;
int m1(int a)
{ System.out.println("m1() method");
return this.a;//return instance variable as a return value.
}
public static void main(String[] args)
{ Test t = new Test();
int x = t.m1(100);
System.out.println(“m1() return value is ”+x);//printing return value
}
}
Example 14:- The java class is able to return user defined class as a return value.
class Person
{ void eat(){System.out.println("person takes 4-idles");}
}
class Ratan
{ void eat(){System.out.println("ratan takes 10-idles");}
}
class RatanKid
{ void eat(){System.out.println("person takes 2-idles");}
}
class Test
{ Person m1()
{ System.out.println("m1 method");
Person p = new Person();
return p;
}
Ratan m2()
{ System.out.println("m2 method");
Ratan r = new Ratan();
return r;
}
RatanKid m3()
{ System.out.println("m3 method");
RatanKid k = new RatanKid();
return k;
}
public static void main(String[] args)
{ Test t =new Test();
Person p = t.m1();
p.eat();
Ratan r = t.m2();
r.eat();
RatanKid k = t.m3();
k.eat();
}
};
51 | P a g e
JAVA Means DURGA SOFT
Example 15:
Note :- This keyword representing current class objects.
In java method is able to return current class object return value in two ways.
1) By creation of object.
2) Return this keyword because it is representing current class object.
In above two approaches 2nd approach is recommended to return the current class object.
class Test
{ Test m1() //first approach to return same class(Test) object
{ return new Test();
}
Test m2() //second approach to return same class(Test) object
{ return this; }
public static void main(String[] args)
{ Test t = new Test(); //it creates object of Test class
System.out.println(t.getClass());
Test t1 = t.m1(); //m1() method return Object of Test class
System.out.println(t1.getClass());
Test t2 = t.m2(); //m2() method return Object of Test class
System.out.println(t1.getClass());
}
};
Example 16 :- Template method:-
Let Assume to complete your task you must call four methods at that situation you must
remember number of methods and order of calling.
52 | P a g e
JAVA Means DURGA SOFT
To overcome above limitation take one x( ) method it is calling four methods internally to
complete our task then instead of calling four methods every time call x( ) method that perform
our task that x( ) method is called template method.
class Test
{ void customer() { System.out.println("customer part");}
void product() { System.out.println("product part"); }
void selection() { System.out.println("selection part"); }
void billing() { System.out.println("billing part"); }
void deliveryManager() //template method
{ System.out.println("****Template method***");
//template method is calling four methods in order to complete our task.
customer(); product(); selection(); billing();
}
public static void main(String[] args)
{ //normal approach
Test t = new Test();
t.customer(); t.product(); t.selection(); t.billing();
//by using template method
Test t1 = new Test();
t1.deliveryManager(); //this method is calling four methods to complete our task.
}
};
Example 17:- Method recursionA method is calling itself during execution is called recursion.
Example 1:- (normal output)
class RecursiveMethod
{ static void recursive(int a)
{ System.out.println("number is :- "+a);
if (a==0)
{return; }
recursive(--a); //same method is calling [recursion]
}
public static void main(String[] args)
{ RecursiveMethod.recursive(10);
}
};
Example 2:- (StackOverFlowError)
class RecursiveMethod
{ static void recursive(int a)
{ System.out.println("number is :- "+a);
if (a==0)
{return;
}
recursive(++a);
}
public static void main(String[] args)
{ RecursiveMethod.recursive(10);
53 | P a g e
JAVA Means DURGA SOFT
}
};
Example 18 :- Stack Mechanism:-
In java program execution starts from main method, just before program execution JVM creates
one empty stack for that application.
Whenever JVM calling particular method then that method entry and local variables of that
method stored in stack memory.
When the method exists, that particular method entry and local variables of that method are
deleted from memory that memorybecomes available to other called methods.
Based on 2 & 3 the local variables are stored in stack memory and for these variables memory is
allocated when method starts and memory is deleted when program ends.
The intermediate calculations are stored in stack memory at final if all methods are completed
that stack will become empty then that empty stack is destroyed by JVM just before program
completes.
The empty stack is created by JVM and at final empty stack is destroyed by JVM.
class Test
{ void add(int a,int b)
{ System.out.println(a+b); }
void mul(int a,int b)
{ System.out.println(a+b); }
public static void main(String[] args)
{ Test t = new Test();
t.add(5,8); t.mul(10,20);
}
};
54 | P a g e
JAVA Means DURGA SOFT
this keyword:-
this keyword is holding current class reference variable and it is used to represent,
a. Current class variables.
b. Current class methods.
c. Current class constructors.
t.add(10,20);
}
}
In bove exmple instance variables and local variables having different names so this keyword
not required.
56 | P a g e
JAVA Means DURGA SOFT
57 | P a g e
JAVA Means DURGA SOFT
CONSTRUCTORS:-
Object creation syntax:-
Test t = new Test();
Test --- class Name
t ---- Reference variables
= ---- assignment operator
New ---- keyword used to create object
Test () ---- constructor
; ---- statement terminator
1. When we create new instance (Object) of a class using new keyword, a constructor for that
class is called.
2. Constructors are used to initialize the instance variables of a class
58 | P a g e
JAVA Means DURGA SOFT
New :-
new keyword is used to create object in java.
Different approaches are there create objects like
o By usinginstance factory method.
o By using stati factory method
o By using pattern factory method
o By using new operator.
o By using Deserialization .
o By using newInstance() method.
o By using clone() method…….etc
When we create object by using new operator after new keyword that part is constructor then
constructor execution will be done.
Default Constructor:-
1) If we are not write constructor for a class then compiler generates one constructor for you that
constructor is called default constructor. And it is not visible in code.
2) Compiler generates Default constructor inside the class when we are not providing any type of
constructor (0-arg or parameterized).
3) The compiler generated default constructor is always 0-argumnetconstructor with empty
implementation (empty body).
59 | P a g e
JAVA Means DURGA SOFT
60 | P a g e
JAVA Means DURGA SOFT
61 | P a g e
JAVA Means DURGA SOFT
D:\morn11>javac Employee.java
D:\morn11>java Employee
****Employee details****
Employee name :-->ratan
Employee name :-->111
Employee name :-->60000.0
Note: - in above example during object creation user provided 0-arg constructor executed
used to initialize some values to instance variables.
To overcome above limitation just use parameterized constructor to initialize different values.
62 | P a g e
JAVA Means DURGA SOFT
{ //instance variables
int eid;
String ename;
double esal;
Employee(int eid,String ename,double esal) //local variables
{//conversion (passing local values to instance values)
this.eid = eid;
this.ename = ename;
this.esal = esal;
}
void display()
{ //printing instance variables values
System.out.println("****Employee details****");
System.out.println("Employee name :-->"+ename);
System.out.println("Employee name :-->"+eid);
System.out.println("Employee name :-->"+esal);
}
public static void main(String[] args)
{ // during object creation parameterized constructor executed
Employee e1 = new Employee(111,"ratan",60000);
e1.display();
Employee e2 = new Employee(222,"anu",70000);
e2.display();
Employee e3 = new Employee(333,"Sravya",80000);
e3.display();
}
}
Note: - by using parameterized constructor we are able to initialize values to instance variables during
object creation and it is possible to initialize different values to different objects during object creation
time.
Note :- the main objective of constructor is initialize some values to instance variables during object
creation time.
Example :-
Constructor s are performing fallowing operations
o Constructors are useful to initialize some user provided values to instance variables
during object creation.
o Constructors are used to write the functionality of project that functionality is
executed during object creation.
Inside the class it is possible to declare multiple constructors.
class Test
{ Test() //user defined 0-arg constructor
{
System.out.println("0-arg cons logics");
}
Test(int a,int b) //user defined parameterized constructor
63 | P a g e
JAVA Means DURGA SOFT
{
System.out.println("2-arg cons logics");
}
void m1() { System.out.println("m1 method"); }
public static void main(String[] args)
{ Test t1 = new Test(); t1.m1();
Test t2 = new Test(10,20); t2.m1();
}
}
Example-4:- constructors vs all data-types
class Test
{ Test(byte a) { System.out.println("Byte value-->"+a); }
Test(short a) { System.out.println("short value-->"+a); }
Test(int a) { System.out.println("int value-->"+a); }
Test(long a) { System.out.println("long value is-->"+a); }
Test(float f) { System.out.println("float value is-->"+f); }
Test(double d) { System.out.println("double value is-->"+d); }
Test(char ch) { System.out.println("character value is-->"+ch); }
Test(boolean b) { System.out.println("boolean value is-->"+b); }
public static void main(String[] args)
{ Test t1=new Test((byte)10);
Test t2=new Test((short)20);
Test t3=new Test(30);
Test t4=new Test(40);
Test t5=new Test(10.5);
Test t6=new Test(20.5f);
Test t7=new Test('a');
Test t8=new Test(true);
}
}
Example :-
a is variable of primitive type such as int,char,double,boolean…etc
tisreference variable &it is the memory address of object.
Reference variable used to hold particular object & class decides object creation.
class Test
{ Test(String str){}
public static void main(String[] args)
{ //a is primitive variable
int a=10;
64 | P a g e
JAVA Means DURGA SOFT
System.out.println(a);
//t is reference variable
Test t = new Test("hi ratan");
System.out.println(t);
}
}
This keyword :-
To call Current class constructoruse this keyword
this(); ---- current class 0-arg constructor calling
this(10); ---- current class 1-arg constructor calling
this(10 , true); ---- current class 2-arg constructor calling
this(10 , ”ratan” , ’a’) ---- current class 3-arg constructor calling
Example-1:-
To call the current class contructor use this keyword.
class Test
{ Test()
{ this(100); //current class 1-arg constructor calling
System.out.println("0-arg constructor logics");
}
Test(int a)
{ this('g',10); //current class 2-arg constructor calling
System.out.println("1-arg constructor logics");
System.out.println(a);
}
Test(char ch,int a)
{ System.out.println("2-arg constructor logics");
System.out.println(ch+"----"+a);
}
public static void main(String[] args)
{ Test t = new Test(); //at object creation time 0-arg costructor executed
}
}
Example 2:-
Inside the constructor this keyword must be first statement otherwise compiler generate error
message “call to this must be first statement in constructor”.
Constructor calling must be first statement in constructor.
No compilation error:-(this keyword first statement)
Test()
{ this(10); //current class 1-argument constructor calling
System.out.println("0 arg");
}
Test(int a)
{ this(10,20); //current class 2-argument constructor calling
System.out.println(a);
}
Compilation error:-(this keyword not a first statement)
Test()
{ System.out.println("0 arg");
65 | P a g e
JAVA Means DURGA SOFT
Note :-
Every object creation having three parts.
1) Declaration:-
Test t; //t is Test type
Student s; //s is Student type
A a; //a is A type
2) Instantiation:-(just object creation)
new Test(); //Test object
new Student(); //student object
new A(); //A object
3) initialization:-(during object creation perform initialization)
new Test(10,20); //during object creation 10,20 values initialized
new Student("ratan",111); //during object creation values are initialized
new A('a',true) //during object creation values are initialized
66 | P a g e
JAVA Means DURGA SOFT
67 | P a g e
JAVA Means DURGA SOFT
3)Return type Return type not allowed It allows all valid return
Even void. Types(void,int,Boolean…etc)
68 | P a g e
JAVA Means DURGA SOFT
4)Name Method name starts with lower Class name and constructor
Case & every inner word starts name must be matched.
With upper case.
Ex: charAt(),toUpperCase()….
7)how to call To call the methods use method to call the constructor use
Name. this keyword.
8)able to call how many one method is able to call one constructors able to
Methods or constructors multiple methods at a time. Call only one constructor
at a time.
9)this to call instance method use this To call constructor use this
Keyword but It is not possible to keyword but inside constructor
call static method. use only one this statement.
10)Super used to call super class methods. Used to call super class constructor
69 | P a g e
JAVA Means DURGA SOFT
System.out.println("1-arg cons");
}
Test(int i,int j)
{ System.out.println("2-arg cons");
}
public static void main(String[] args)
{ new Test();
}
}
Instance Blocks:-
Instance blocks are executed during object creation just before constructor execution.
Instance blocks execution depends on object creation it means if we are creating 10
objects 10 times instance blocks are executed.
Example 1:-
class Test
{ { System.out.println("instance block:logics"); }//instance block
Test()
{ System.out.println("constructor:logics");
}
public static void main(String[] args)
{ Test t = new Test();
}
}
Example 2:-
class Test
{ { System.out.println("instance block-1:logics"); }
Test() { System.out.println("0-arg constructor:logics"); }
{ System.out.println("instance block-2:logics"); }
Test(int a)
{ System.out.println("1-arg constructor:logics"); }
public static void main(String[] args)
{ Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test(10);
}
}
Example 3:-
class Test
{ { System.out.println("instance block-1:logics"); }
Test()
{ this(10);
70 | P a g e
JAVA Means DURGA SOFT
System.out.println("0-arg constructor:logics"); }
Test(int a)
{ System.out.println("1-arg constructor:logics");
}
public static void main(String[] args)
{ Test t1 = new Test();
}
}
Example 1:-
class Test
{ {System.out.println("instance block");} //instance block
int a=m1(); //instance variables
int m1()
{System.out.println("m1() method called by variable");
return 100;
}
public static void main(String[] args)
{ Test t = new Test();
}
}
D:\morn11>java Test
instance block
m1() method called by variable
example :-
class Test
{ int a=m1(); //instance varaibles
int m1()
{System.out.println("m1() method called by variable");
return 100;
}
{ System.out.println("instance block"); } //static blocks
public static void main(String[] args)
{ Test t = new Test();
}
}
D:\morn11>java Test
m1() method called by variable
instance block
71 | P a g e
JAVA Means DURGA SOFT
example :-
instance blocks are used to initialize instance variables during object creation but before
constructor execution.
class Emp
{ //instance blocks
int eid; //0
String ename; //null
double esal; //0.0
//instance block used to initialize instance varaibles
{ ename="ratan";
eid=111;
esal=20000;
}
void disp()
{System.out.println("emp name="+ename);
System.out.println("emp id="+eid);
System.out.println("emp sal="+esal);
}
public static void main(String[] args)
{ Emp e1 = new Emp(); //default constructor & instance block is executed
e1.disp();
}
};
static block:-
Static blocks are used to write functionality of project that functionality is executed
during .class file loading time.
In java .class file is loaded only one time hence static blocks are executed once per class.
Example :-
class Test
{ static{System.out.println("static block");}
public static void main(String[] args)
{
}
}
Example :-
class Test
{ static{System.out.println("static block-1");} //static block
static{System.out.println("static block-2");} //static block
{System.out.println("instance block-1");} //instance block
{System.out.println("instance block-2");} //instance block
Test(){ System.out.println("0-arg constructor"); } //0-arg constructor
Test(int a){ System.out.println("1-arg constructor"); }//1-arg constructor
72 | P a g e
JAVA Means DURGA SOFT
Example:-
class Test
{ //instance variables
int a=10,b=20;
//static variables
static int c=30,d=40;
//instance method
int m1(int a,int b)//local variables
{ System.out.println(a+”---”+b);
return 10;
}
//static method
static String m2(boolean b) //local variables
{ System.out.println(b);
return "ratan";
}
Test(int a) //constructor with 1-arg
{ System.out.println("1-arg constructor");
}
Test(int a,int b) //constructor with 2-arg
{ System.out.println("2-arg constructor");
}
{System.out.println("instance block-1");} //instance block
{System.out.println("instance block-2");} //instance block
static {System.out.println("static block-1");} //static block
static {System.out.println("static block-2");} //static block
public static void main(String[] args)
{ //Test object created with 1-arg constructor
Test t1 = new Test(10); //1-arg constructor & instance blocks executed
73 | P a g e
JAVA Means DURGA SOFT
Practical example:-
class A
{ };
class B
{ };
class Test
{ 2-instnce varaibles
2-static variables
2-instance methods
1-method --->2-arg(int,char) --->return-type-->String
2 method ---->1-arg(boolean) ---->Test
2-static methods
1static method--->2-arg(Aobj,Bobj) ---->A
2 static mentod --->1-arg(double)--->int
public static void main(String[] args)
{ print instance var
print static var
call instance methods
call static methods
}
};
class A
{};
class B
{};
class Test
74 | P a g e
JAVA Means DURGA SOFT
{ //instance vriables
int a=10;
int b=20;
//static variables
static int c=30;
static int d=40;
String m1(int a,int b)
{ System.out.println("m1 method");
return "ratan"; //returning String value
}
Test m2(int a)
{ System.out.println("m2 method");
return this; //returning current class object
}
static A m3(A a,B b) //method is taking objects as a input values
{ System.out.println("m3 method");
A a1 = new A();
return a1; //returning A class object
}
static int m4(int a)
{ System.out.println("m4 method");
return 100; //returning integer value
}
public static void main(String[] args)
{ Test t = new Test();
//printing instance variables by using object name
System.out.println(t.a);
System.out.println(t.b);
//printing static variables by using class name
System.out.println(Test.c);
System.out.println(Test.d);
String str=t.m1(1,2); //holding m1() method return value(String)
System.out.println(str); //printing return value
Test t1 = t.m2(3); //holding m2() method return value(Test)
A a = new A(); B b = new B();
//calling m3() method by pssing two objects (A,B)
A a1 = Test.m3(a,b);//holding m3() method return value(A)
int x = Test.m4(4);//holding m4() method return value(int)
System.out.println(x);//printing return value
}
};
75 | P a g e
JAVA Means DURGA SOFT
Oops concepts:-
1. Inheritance
2. Polymorphism
3. Abstraction
4. Encapsulation
Inheritance:-
1. The process of acquiring fields(variables) and methods(behaviors) from one class to another class
is called inheritance.
2. The main objective of inheritance is code extensibility whenever we are extending class
automatically the code is reused.
3. In inheritance one class giving the properties and behavior & another class is taking the
properties and behavior.
4. Inheritance is also known as is-a relationship. By using extends keyword we are achieving
inheritance concept.
5. extends keyword used to achieve inheritance & it is providing relationship between two classes
when you make relationship then able to reuse the code.
6. In java parent class is giving properties to child class and Child is acquiring properties from
Parent.
7. To reduce length of the code and redundancy of the code sun people introduced inheritance
concept.
76 | P a g e
Durgasoft Mr. Ratan
Note 1:-In java it is possible to create objects forboth parent and child classes.
1. If we are creating object for parent class it is possible to call only parent specific methods.
A a=new A();
a.m1();a.m2();
2. if we are creating object for child class it is possible to call parent specific and child specific.
B b=new B();
b.m1();b.m2(); b.m3();b.m4();
C c=new C();
c.m1(); c.m2(); c.m3();c.m4();c.m5();c.m6();
Types of inheritance :-
There are five types of inheritance in java
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid Inheritance
Single inheritance:-
One class has one and only one direct super class is called single inheritance.
In the absence of any other explicit super class, every class is implicitly a subclass of Object class.
77 | P a g e
Durgasoft Mr. Ratan
Multilevel inheritance:-
One Sub class is extending Parent class then that sub class will become Parent class of next
extended class this flow is called multilevel inheritance.
78 | P a g e
Durgasoft Mr. Ratan
Example:-
class A
{ void m1(){System.out.println("A class");}
};
class B extends A
{ void m2(){System.out.println("B class");}
};
class C extends A
{ void m2(){System.out.println("C class");}
};
class Test
{ public static void main(String[] args)
{ B b= new B();
b.m1(); b.m2();
C c = new C();
c.m1(); c.m2();
}
};
Multiple inheritance:-
One sub class is extending more than one super class is called Multiple inheritance and java not
supporting multiple inheritance because it is creating ambiguity problems (confusion state) .
Java not supporting multiple inheritance hence in java one class able to extends only one class at
a time but it is not possible to extends more than one class.
Class A extends B ===>valid
Class A extends B ,C ===>invalid
Example:-
class A
{ void money(){System.out.println("A class money");}
};
class B
{ void money(){System.out.println("B class money");}
};
class C extends A,B
{ public static void main(String[] args)
{ C c = new C();
c.money(); //which method executed A--->money() or B--->money
79 | P a g e
Durgasoft Mr. Ratan
}
};
Hybrid inheritance:-
Hybrid is combination of hierarchical & multiple inheritance .
Java is not supporting hybrid inheritance because multiple inheritance(not supported by
java) is included in hybrid inheritance.
Preventing inheritance:-
You can prevent sub class creation by using final keyword in the parent class declaration.
final class Parent //for this class child class creation not possible because it is final.
{
};
class Child extends Parent
{
};
compilation error:- cannot inherit from final Parent
Note:-
1. Except for the Object class , a class has one direct super class.
2. a class inherit fields and methods from all its super classes whether directly or indirectly.
3. an abstract class can only be sub classed but cannot be instantiated.
4. In parent and child it is recommended to create object of Child class.
Java.lang.Object class methods :-
public class java.lang.Object {
1) public final native java/lang/Class<?> getClass();
2) public native int hashCode();
3) public boolean equals(java.lang.Object);
4) protected native java.lang.Object clone() throws java.lang.CloneNotSupportedException;
5) public java.lang.String toString();
6) public final native void notify();
7) public final native void notifyAll();
8) public final native void wait(long) throws java.lang.InterruptedException;
9) public final void wait(long, int) throws java.lang.InterruptedException;
10) public final void wait() throws java.lang.InterruptedException;
11. protected void finalize() throws java.lang.Throwable;}
80 | P a g e
Durgasoft Mr. Ratan
Example :-
In java if we are extending java class that extended class will become Parent class , if we are not
extending Object class will become Parent class.
In below example
A class Parent is ----> Object
B class Parent is ---->A
C class Parent is ---->B
class A
{ void m1(){} };
class B extends A
{ void m2(){} };
class C extends B
{ void m3(){} };
In above example A class Parent is Object class
Object class contains ---->11 methods
A class contains ---->12 methods
B class contains ---->13 methods
C class contains ---->14 methods
Instanceof operator:-
It is used check the type of the object and return Boolean value as a return value.
Syntax:- reference-variable instanceof class-name;
Example:- Test t=new Test();
t instanceof Test
Whenever we are using instanceof operator the reference variable and class-name must have
some relationship either [parent to child] or [child-parent] otherwise compiler generates error
message “inconvertible types”
If the relationship is
o Child – parent returns true
o Parent - child returns false
Example :-
class Animal{ };
class Dog extends Animal{ };
class Test
{ public static void main(String[] args)
{ //syntax: (ref-ver instanceof class-name);
String str="ratan";
Animal a = new Animal();
Dog d = new Dog();
Object o = new Object();
System.out.println(a instanceof Object); //true [child-parent]
System.out.println(d instanceof Animal); //true [child-parent]
System.out.println(str instanceof Object); //true [child-parent]
System.out.println(o instanceof Animal); //false [parent-child]
System.out.println(a instanceof Dog); //false [parent-child]
//no relationship compilation error :inconvertible types
//System.out.println(str instanceof Animal);
81 | P a g e
Durgasoft Mr. Ratan
}
}
Association:-
Class A uses class B
When one object wants another object to perform services for it.
Relationship between teacher and student, number of students associated with one teacher or
one student can associate with number of teachers. But there is no ownership and both objects
have their own life cycles.
Example-1:-
class Student
{ int sid;
String sname;
Student(int sid,String sname) //local variables
{ //conversion
this.sid =sid;
this.sname=sname;
}
void disp()
{ System.out.println("***student details***");
System.out.println("student name--->"+sname);
System.out.println("student name--->"+sid);
}
};
Class RatanTeacher //teacher uses Student class "association"
{ public static void main(String[] args)
{ Student s1 = new Student(111,"ratan");
Student s2 = new Student(222,"anu");
s1.disp(); s2.disp();
}
};
Example-2:-
class Ratan
{ void disp(){System.out.println("ratan : corejava");}
};
class Anu
{ void disp(){System.out.println("anu : advjava");}
};
class Sravya
{ void disp(){System.out.println("Sravya : ocjp");}
};
class Student //student uses different teachers "association"
{ public static void main(String[] args)
{ Ratan r = new Ratan(); r.disp();
Anu a = new Anu(); a.disp();
Sravya d = new Sravya(); d.disp();
}
};
Aggregation:-
82 | P a g e
Durgasoft Mr. Ratan
83 | P a g e
Durgasoft Mr. Ratan
Heroin.java:
class Heroin
{ //instance varaibles
String hname; int hage;
Address addr;//reference of address class [address class can exists without Heroin class]
Heroin(String hname,int hage,Address addr)//localvariables
{ //conversion of local variables to instance variables
this.hname = hname; this.hage = hage; this.addr = addr;
}
void display()
{ System.out.println("*********heroin details******");
System.out.println("heroin name-->"+hname);
System.out.println("heroin age-->"+hage);
//printing address values
System.out.println("heroin address-->"+addr.country+" "+addr.state+" "+addr.hno)
}
public static void main(String[] args)
{ //object creation of Address class
Address a1 = new Address("india","banglore",111);
Address a2 = new Address("india","mumbai",222);
Address a3 = new Address("US","california",333);
//Object creation of Heroin class by passing address object name
Heroin h1 = new Heroin("anushka",30,a1);
Heroin h2 = new Heroin("KF",30,a2);
Heroin h3 = new Heroin("AJ",40,a3);
h1.display(); h2.display(); h3.display();
}
}
Example-3:-
Test1.java:- Test2.java:- Test3.java:-
class Test1 class Test2 class Test3
{ //instance variables {//instance variables { //instance variables
int a; boolean b1; char ch1;
int b; boolean b2; char ch2;
Test1(int a,int b) Test2(boolean b1,boolean b2) Test3(char ch1,char ch2)
{ this.a=a; { this.b1=b1; { this.ch1=ch1;
this.b=b; this.b2=b2; this.ch2=ch2;
} } }
}; }; };
84 | P a g e
Durgasoft Mr. Ratan
MainTest.java:-
class Test
{ //instance variables
Test1 t1;
Test2 t2;
Test3 t3;
Test(Test1 t1 ,Test2 t2,Test3 t3)//constructor [local variables]
{ //conversion of local-instance
this.t1 = t1;
this.t2 = t2;
this.t3 = t3;
}
void display()
{ System.out.println(“Test1 object values:-”+t1.a+"----- "+t1.b);
System.out.println(“Test2 object values:-”+t2.b1+"----- "+t2.b2);
System.out.println(“Test3 object values:-”+t3.ch1+"----- "+t3.ch2);
}
public static void main(String[] args)
{ Test1 t = new Test1(10,20);
Test2 tt = new Test2(true,true);
Test3 ttt = new Test3('a','b');
Test main = new Test(t,tt,ttt);
main.display();
}
};
Composition :-
Class A owns class B , it is a strong type of aggregation. There is no meaning of child without
parent.
Order consists of list of items without order no meaning of items. or bank account consists of
transaction history without bank account no meaning of transaction history or without student
class no meaning of marks class.
Let’s take Example house contains multiple rooms, if we delete house object no meaning of room
object hence the room object cannot exists without house object.
Relationship between question and answer, if there is no meaning of answer without question
object hence the answer object cannot exist without question objects.
Relationship between student and marks, there is no meaning of marks object without student
object.
Example :-
//Marks.java
class Marks
{ int m1,m2,m3;
Marks(int m1,int m2,int m3) //local variables
{ //conversions
this.m1=m1;
this.m2=m2;
this.m3=m3;
}
85 | P a g e
Durgasoft Mr. Ratan
};
//student.java
class Student
{ //instance variables
Marks mk; //without student class no meaning of marks is called "composition"
String sname;
int sid;
Student(Marks mk,String sname,int sid) //local variables
{ this.mk = mk;
this.sname = sname;
this.sid = sid;
}
void display()
{ System.out.println("student name:-->"+sname);
System.out.println("student id:-->"+sid);
System.out.println("student marks:-->"+mk.m1+"---"+mk.m2+"--"+mk.m3);
}
public static void main(String[] args)
{ Marks m1 = new Marks(10,20,30);
Marks m2 = new Marks(100,200,300);
Student s1 = new Student(m1,"ratan",111);
Student s2 = new Student(m2,"anu",222);
s1.display();
s2.display();
}
}
Object delegation:-
The process of sending request from one object to another object is called object delegation.
Example-1:-
class Test1
{ //instance variables
int a=10;
int b=20;
static void add()//static method
{ Test1 t = new Test1();
System.out.println(t.a+t.b);
}
static void mul()//static method
{ Test1 t = new Test1();
System.out.println(t.a*t.b);
}
public static void main(String[] args)
{ Test1.add(); //calling static method add()
Test1.mul(); //calling static method mul()
}
};
86 | P a g e
Durgasoft Mr. Ratan
Example-2 :-
class Test1
{ //instance variables
int a=10; int b=20;
static Test1 t = new Test1(); // t is a variable of Test1 type (instance variable)
static void add() //static method
{ System.out.println(t.a+t.b); }
static void mul() //static method
{ System.out.println(t.a*t.b); }
public static void main(String[] args)
{ Test1.add(); //calling static method add()
Test1.mul(); //calling static method mul()
}
};
Example-3:-
class Developer
{ void task1(){System.out.println("task-1");}
void task2(){System.out.println("task-2");}
};
class TeamLead
{ Developer d = new Developer();//instance variable
void display1()
{ d.task1(); d.task2(); }
void display2()
{ d.task1(); d.task2(); }
public static void main(String[] args)
{ TeamLead t = new TeamLead();
t.display1(); t.display2();
}
};
Example -4:-
class RealPerson //delegate class
{ void book(){System.out.println("real java book");}
};
class DummyPerson //delegator class
{ RealPerson r = new RealPerson();
void book(){r.book();} //delegation
};
class Student
{ public static void main(String[] args)
{ //outside world thinking dummy Person doing work but not.
DummyPerson d = new DummyPerson();
d.book();
}
87 | P a g e
Durgasoft Mr. Ratan
};
Super keyword:-
Super keyword is holding super class object. And it is representing
1. Super class variables
2. Super class methods
3. Super class constructors
super class variables calling:-
Super keyword not required:-
class Parent
{ int x=10, y=20;//instance variables
};
class Child extends Parent
{ int a=100,b=200;//instance variables
void m1(int i,int j)//local variables
{ System.out.println(i+j); //local variables addition
System.out.println(a+b); //current class variables addition
System.out.println(x+y); //super class variables addition
}
public static void main(String[] args)
{ Child c = new Child();
c.m1(1000,2000);
}//end main
};//end class
In above example current class and super class variables having different names so this keyword and
super keyword not required.
88 | P a g e
Durgasoft Mr. Ratan
Superkeyword requeired:-
class Parent
{ void m1(int a){ System.out.println("parent m1()-->"+a); }
};
class Child extends Parent
{ void m1(int a){ System.out.println("child m1()-->"+a); }
void m2()
{ this.m1(10); //child class m1(int) method calling
System.out.println("child m2()");
super.m1(100); // parent class m1(int) method calling
}
public static void main(String[] args)
{ Child c = new Child();
c.m2();
}
};
class Parent
{ void m1(){System.out.println("parent m1() method");}
};
class Child extends Parent
{ void m1() {System.out.println("child class m1() method");}
void m3()
{ this.m1(); //current class method is executed
super.m1(); //super class method will be executed
}
public static void main(String[] args)
{ new Child().m3();
89 | P a g e
Durgasoft Mr. Ratan
}
};
In above exmple super class and sub class contains methods with same names( m1() ) at that situation
to represent.
a. Super class methods use super keyword.
b. Sub clss methods use this keyword.
Example-2:-
nIside the constructor super keyword must be first statement otherwise compiler generate error
message “call to super must be first line in constructor”.
No compilation error:-
Child()
{ this(10);//current class 1-arg constructor calling(must be first line)
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ super();//super class 0-arg constructor calling(must be first line)
System.out.println("child 1-arg constructor--->"+a);
}
90 | P a g e
Durgasoft Mr. Ratan
Compilation Error:-
Child()
{ System.out.println("Child 0-arg constructor");
this(10);//current class 1-arg constructor calling
}
Child(int a)
{ System.out.println("child 1-arg constructor--->"+a);
super();//super class 0-arg constructor calling (compiltion Error)
}
Example-3:-
Inside the constructor this keyword must be first statement and super keyword must be first statement
hence inside the constructor it is possible to use either this keyword or super keyword but both at a time
not possible.
No compilation Error:-
Child()
{ this(10);//current class 1-arg constructor calling(must be first line)
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ super();//super class 0-arg constructor calling(must be first line)
System.out.println("child 1-arg constructor--->"+a);
}
Compilation Error:-
Child()
{ this(10);//current class 1-arg constructor calling
super();//super class 0-arg constructor calling
System.out.println("Child 0-arg constructor");
}
Example-4:-
1. Inside the constructor (weather it is default or parameterized) if we are not declaring super or
this keyword at that situation compiler generate super() keyword at first line of the constructor.
2. If we are declaring t lest one constructor compiler is not responsible to generate super()
keyword.
3. The compiler generated super keyword is always 0-argument constructor calling.
class Parent
{ Parent() { System.out.println("parent 0-arg constructor"); }
};
class Child extends Parent
91 | P a g e
Durgasoft Mr. Ratan
{
Child()
{ //super(); generated by compiler at compilation time
System.out.println("Child 0-arg constructor");
}
public static void main(String[] args)
{ Child c = new Child();
}
};
D:\>java Child
parent 0-arg constructor
Child 0-arg constructor
Example-5:-
In below example parent class default constructor is executed that is provided by compiler.
class Parent
{ //default constructor Parent() { } generated by compiler at compilation time
};
class Child extends Parent
{ Child()
{ //super(); generated by compiler at compilation time
System.out.println("Child 0-arg constructor");
}
public static void main(String[] args)
{ Child c = new Child();
}
};
Example-6:-
By using below example we are assigning values to instance variable at the time of object creation eith
the help of parameterized constructor.
class Parent
{ int a; //instance variable
Parent(int a)//local variable
{ //conversion of local variable to instance variable
this.a=a;
}
};
class Child extends Parent
{ boolean x; //instance variable
Child(boolean x) //local variable
{ super(10); //super class constructor calling
this.x =x ; //conversion of local variable to instance variable
(passing local variable value to instance variable)
92 | P a g e
Durgasoft Mr. Ratan
}
void display()
{ System.out.println(a);
System.out.println(x);
}
public static void main(String[] args)
{ Child c = new Child(true);
c.display();
}
};
Example-7:-
In below example child class is calling parent class 0-argument constructor since not there so
compiler generate error message
.
class Parent
{ Parent(int a) { System.out.println("parent 1-arg cons-->"+a); }
};
class Child extends Parent
{ Child()
{ //super(); generated by compiler t compilation time
System.out.println("Child 0-arg constructor");
}
public static void main(String[] args)
{ Child c = new Child();
}
};
Example-8:-
In below example in child class 1-argument constructor compiler generate super keyword hence
parent class 0-argument constructor is executed.
class Parent
{ Parent(){System.out.println("parent 0-arg cons"); }
};
class Child extends Parent
{ Child()
{ this(10); //current class 1-argument constructor calling
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ //super(); generated by compiler
System.out.println("child 1-arg cons");
}
93 | P a g e
Durgasoft Mr. Ratan
Example-9:-
Inside the constructor either it is zero argument or parameterized if we are not providing super
or this keyword at that situation compiler generate super keyword at first line of constructor.
class Parent
{ Parent() { System.out.println("parent 0-arg cons"); }
};
class Child extends Parent
{ Child()
{ //super(); generated by compiler
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ //super(); generated by compiler
System.out.println("child 1-arg cons");
}
public static void main(String[] args)
{
Child c = new Child();
Child c1 = new Child(10);
}
};
D:\>java Child
parent 0-arg cons
Child 0-arg constructor
parent 0-arg cons
child 1-arg cons
94 | P a g e
Durgasoft Mr. Ratan
Example-10:-
In below compiler generate default constructor and inside that default constructor super keyword is
generated by compiler.
Application code before compilation:- ( .java ) class Parent
class Parent { Parent(){System.out.println("parent 0-
{ Parent(){ arg cons"); }
System.out.println("parent 0-arg cons");} };
}; class Child extends Parent
class Child extends Parent { /* below code is generated by compiler
{ public static void main(String[] args) Child()
{ Child c = new Child(); { super();
} }*/
}; public static void main(String[] args)
{ Child c = new Child();
}
};
Application code after compilation:- ( .class )
Example-11:-
In below example inside the 1-argument constructor compiler generate super( ) keyword hence it is
executing super class(Object)0-argument constructor is executed.
Application code before compilation:- ( .java ) Application code after compilation:- ( .class )
class Test (Object class 0-arg constructor executed)
{ class Test extends Object
Test(int a){ { Test(int a)
System.out.println("Test 1-arg cons"); {
} super(); //generated by compiler
public static void main(String[] args) System.out.println("Test 1-arg cons");
{ }
Test t = new Test(10); public static void main(String[] args)
} { Test t = new Test(10);
}; }
};
Note 1:- in java if we are extending class that extended class will become super class
Ex :- class B{ }
class A extends B //B class is Parent of A class
{ }
Note 2 :- in java if we are not extending any class then Object class will become parent of that class.
Ex :- class A { } //in this Object class is Parent of A class
Note:-
1. Every class in the java programming either directly or indirectly child class of Object.
2. Root class for all java classes is Object class.
3. The object class present in java.lang package
95 | P a g e
Durgasoft Mr. Ratan
Example : assignment
class GrandParent
{ int c;
GrandParent(int c)
{ this.c=c;
}
};
class Parent extends GrandParent
{ int b;
Parent(int b,int c)
{ super(c);
this.b=b;
}
};
class Child extends Parent
{ int a;
Child(int a,int b,int c)
{ super(b,c);
this.a=a;
}
void disp()
{ System.out.println("child class ="+a);
System.out.println("parent class ="+b);
System.out.println("grandparent class ="+c);
}
public static void main(String[] args)
{ new Child(10,20,30).disp();
}
};
96 | P a g e
Durgasoft Mr. Ratan
};
Example-2:-
In below example just before child class instance blocks first parent class instance blocks are executed.
class Parent
{ {System.out.println("parent instance block");}//instance block
Parent(){System.out.println("parent cons");}//constructor
};
class Child extends Parent
{ {System.out.println("Child instance block");}//instance block
Child()
{ //super(); generated by compiler
System.out.println("chld 0-arg cons");}
}
Child(int a)
{ //super(); generated by compiler
System.out.println("chld 1-arg cons");
}
public static void main(String[] args)
{ Child c = new Child();
Child c1 = new Child(10);
}
};
D:\>java Child
parent instance block
parent cons
Child instance block
chld 0-arg cons
parent instance block
parent cons
Child instance block
chld 1-arg cons
class Parent
{
{System.out.println("parent class ins block");}
Parent()
{ System.out.println("parent class 0-arg cons");
}
};
class Child extends Parent
{
{System.out.println("Child class ins block");}
Child()
{ //super(); generated by compiler
System.out.println("child class 0-arg cons");
97 | P a g e
Durgasoft Mr. Ratan
}
public static void main(String[] args)
{ new Child();
}
};
E:\>java Child
parent class static block
child class static block
parent class ins block
parent class 0-arg cons
Child class ins block
child class 0-arg cons
parent class ins block
parent class 0-arg cons
Child class ins block
child class 0-arg cons
Parent class static block:-
Example-1:-
In parent and child relationship first parent class static blocks are executed only one time then
child class static blocks are executed only one time because static blocks are executed with
respect to .class loading.
class Parent
{ static{System.out.println("parent static block");}//static block
};
class Child extends Parent
{
static{System.out.println("child static block");} //static block
public static void main(String[] args)
{
}
};
class Parent
{ Parent(){System.out.println("parent 0-arg cons");}
{System.out.println("parent class instance block");}
static{System.out.println("parent class static block");}
};
class Child extends Parent
{ {System.out.println("child class instance block");}
Child()
{ //super(); generated by compiler
System.out.println("child class 0-arg cons");
}
static {System.out.println("child class static block");}
public static void main(String[] args)
98 | P a g e
Durgasoft Mr. Ratan
{ new Child();
}
};
Example-2:-
Note 1:-instanceblocks execution depends on number of object creations but not number of
constructor executions. If we are creating 10 objects 10 times constructors are executed just
before constructor execution 10 times instance blocks are executed.
Note 2:-Static blocks execution depends on .class file loading hence the static blocks are
executed only one time for single class.
class Parent
{ static {System.out.println("parent static block");}//static block
{System.out.println("parent instance block");}//instance block
Parent(){System.out.println("parent 0-arg cons");}//constructor
};
class Child extends Parent
{ static {System.out.println("Child static block");}//static block
{System.out.println("child instance block");} //instance block
Child()
{ //super(); generated by compiler
System.out.println("Child 0-arg cons");}
Child(int a){
this(10,20);//current class 2-argument constructor calling
System.out.println("Child 1-arg cons");}
Child(int a,int b)
{ //super(); generated by compiler
System.out.println("Child 2-arg cons");
}
public static void main(String[] args)
{ Parent p = new Parent(); //creates object of Parent class
Child c = new Child(); //creates object of Child class
Child c1 = new Child(100);//creates object of child class
}
};
D:\>java Child
parent static block
Child static block
parent instance block
parent 0-arg cons
parent instance block
parent 0-arg cons
child instance block
Child 0-arg cons
parent instance block
parent 0-arg cons
99 | P a g e
Durgasoft Mr. Ratan
Polymorphism:-
One thing can exhibits more than one form is called polymorphism.
Polymorphism shows some functionality(method name same) with different logics execution.
The ability to appear in more forms is called polymorphism.
Polymorphism is a Greek word poly means many and morphism means forms.
There are two types of polymorphism in java
1) Compile time polymorphism / static binding / early binding
[method execution decided at compilation time]
Example :- method overloading.
2) Runtime polymorphism /dynamic binding /late binding.
[Method execution decided at runtime].
Example :- method overriding.
Method overloading:-
Example:-
100 | P a g e
Durgasoft Mr. Ratan
class Test
{ //below three methods are overloaded methods.
void m1(char ch) {System.out.println(" char-arg constructor "); }
void m1(int i) {System.out.println("int-arg constructor "); }
void m1(int i,int j) {System.out.println(i+j); }
public static void main(String[] args)
{Test t=new Test();
//three methods execution decided at compilation time
t.m1('a');t.m1(10);t.m1(10,20);
}
}
Example :- overloaded methods vs. all data types
class Test
{ void m1(byte a) { System.out.println("Byte value-->"+a); }
void m1(short a) { System.out.println("short value-->"+a); }
void m1(int a) { System.out.println("int value-->"+a); }
void m1(long a) { System.out.println("long value is-->"+a); }
void m1(float f) { System.out.println("float value is-->"+f); }
void m1(double d) { System.out.println("double value is-->"+d); }
void m1(char ch) { System.out.println("character value is-->"+ch); }
void m1(boolean b) { System.out.println("boolean value is-->"+b); }
void sum(int a,int b)
{ System.out.println("int arguments method");
System.out.println(a+b);
}
void sum(long a,long b)
{ System.out.println("long arguments method");
System.out.println(a+b);
}
public static void main(String[] args)
{
Test t=new Test();
t.m1((byte)10); t.m1((short)20); t.m1(30); t.m1(40);
t.m1(10.6f); t.m1(20.5); t.m1('a'); t.m1(true);
t.sum(10,20);
t.sum(100L,200L);
}
}
Constructor Overloading:-
The class contains more than one constructors with same name but different arguments is called
constructor overloading.
class Test
{ //overloaded constructors
Test() { System.out.println("0-arg constructor"); }
Test(int i) { System.out.println("int argument constructor"); }
Test(char ch,int i){ System.out.println(ch+"-----"+i); }
public static void main(String[] args)
{ Test t1=new Test(); //zero argument constructor executed.
101 | P a g e
Durgasoft Mr. Ratan
}
}
Runtime polymorphism [Method Overriding]:-
1) If we want to achieve method overriding we need two class with parent and child
relationship.
2) The parent class method contains some implementation (logics).
a. If child is satisfied use parent class method.
b. If the child class not satisfied (required own implementation) then override the
method in Child class.
3) A subclass has the same method as declared in the super class it is known as method
overriding.
The parent class method is called ===> overridden method
The child class method is called ===> overriding method
While overriding methods must fallow these rules:-
1) While overriding child class method signature & parent class method signatures must be same
otherwise we are getting compilation error.
2) The return types of overridden method & overriding method must be same.
3) While overriding the methods it is possible to maintains same level permission or increasing
order but not decreasing order, if you are trying to reduce the permission compiler generates
error message “attempting to assign weaker access privileges ”.
4) You are unable to override final methods. (Final methods are preventing overriding).
5) While overriding check the covariant-return types.
6) Static methods are bounded with class hence we are unable to override static methods.
7) It is not possible to override private methods because these methods are specific to class.
If a subclass defines a static method with the same signature as a static method in the superclass, then the
method in the subclass hides the one in the superclass.
class Animal
{ void instanceMethod(){System.out.println("instance method in Animal");}
static void staticMethod(){System.out.println("static method in Animal");}
};
102 | P a g e
Durgasoft Mr. Ratan
The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the
superclass or the subclass.
The Cat class overrides the instance method in Animal and hides the static method in Animal.
The main method in this class creates an instance of Cat and invokestestClassMethod() on the class
and testInstanceMethod() on the instance.
103 | P a g e
Durgasoft Mr. Ratan
2) From java5 versions onwardsjava supports support covariant return types it means while
overriding it is possible to change the return types of parent class method(overridden method)
&child class method(Overriding).
3) The return type of overriding method is must be sub-type of overridden method return type this
is called covariant return types.
class Animal
{ void m2(){System.out.println("Animal class m2() method");}
Animal m1()
{ return new Animal();
}
}
class Dog extends Animal
{ Dog m1()
{ return new Dog();
}
public static void main(String[] args)
{ Dog d = new Dog(); d.m2();
Dog d1 = d.m1(); //[d.m1() returns Dog object]
d1.m2();
Animal a = new Animal();
a.m2();
Animal a1 = a.m1(); // [a.m1() returns Animal object]
a1.m2();
}
};
Type-casting:-
The process of converting data one type to another type is called type casting.
There are two types of type casting
1. Implicit typecasting /widening/up casting
2. Explicit type-casting (narrowing)/do
Type casting chart:-
Up-casting :-
Byte short
Int float double
char
down-casting:-
Byte short
Int float double
char
When we assign higher value to lower data type range then compiler will rise compiler error “possible
loss of precision” but whenever we are type casting higher data type-lower data type compiler won’t
generate error message but we will loss the data.
104 | P a g e
Durgasoft Mr. Ratan
Note :- Parent class reference variable is able to hold child class object but Child class reference
variable is unable to hold parent class object.
class Parent
{ };
class Child extends Parent
{ };
Parent p = new Child(); //valid
Child c = new Parent(); //invalid
105 | P a g e
Durgasoft Mr. Ratan
float f=10.5f;
long l = f;
System.out.println(l); compilation error:possible loss of precision (memory
representation different) */
//explicit-typecasting (down-casting)
// converted-type-name var-name = (converted-type-name)conversion-var-type;
int a1=120;
byte b1 =(byte)a1;
System.out.println(b1);
int a2=130;
byte b2 =(byte)a2;
System.out.println(b2);
float ff=10.5f;
int x = (int)ff;
System.out.println(x);
Parent p = new Child();
//target-type variable-name=(target-type)source-type;
Child c1 =(Child)p;
Parent p = new Child();
Child c1 = (Child)p;
}
}
Example-2:-
In java parent class reference variable is able to hold Child class object but Child class reference
variable unable to hold Parent class object.
o Parent p = new Child(); ---->valid
o Child c = new Parent(); ---->invalid
class Parent
{ void m1(){System.out.println("parent m1 method");} //overridden method
}
class Child extends Parent
{ void m1(){System.out.println("child m1 method");} //override method
void m2(){System.out.println("child m2 method");} //direct method of child class
public static void main(String[] args)
{
//parent class is able to hold child class object
Parent p1 = new Child(); //creates object of Child class
p1.m1(); //child m1() will be executed
//p1.m2(); Compilation error we are unable to call m2() method
Child c1 =(Child)p1; //type casting parent reference variable to child object.
c1.m1();
c1.m2();
}
};
In above example parent class is able to hold child class object but when you call p.m1();
method compiler is checking m1() method in parent class at compilation time. But at runtime
child object is created hence Child method will be executed.
106 | P a g e
Durgasoft Mr. Ratan
Based on above point decide in above method execution decided at runtime hence it is a runtime
polymorphism.
When you call p.m2 (); compileris checking m2 () method in parent class since not there so
compiler generate error message. Finally it is not possible to call child class m2 () by using parent
reference variable even thought child object is created.
Based on above point we can say by using parent reference it is possible to call only overriding
methods (m1 () ) of child class but it is not possible to call direct method(m2() ) of child class.
To overcome above limitation to call child class method perform typecasting.
Example :- importance of converting parent class reference variable into child class object
//let assume predefined class
class ActionForm
{ void xxx(){} //predefined method
void yyy(){} //predefined method
};
class LoginForm extends ActionForm //assume to create LoginForm our class must extends ActonForm
{ void m1(){System.out.println("LoginForm m1 method");} //method of LoginFrom class
void m2(){System.out.println("LoginForm m2 method");} //method of LoginFrom class
107 | P a g e
Durgasoft Mr. Ratan
}
};
Example :-
class Animal
{void eat(){System.out.println("animal eat");}
};
108 | P a g e
Durgasoft Mr. Ratan
109 | P a g e
Durgasoft Mr. Ratan
toString():-
toString() method present in Object and it is printing String representation of Object.
toString() method return type is String object it means toString() method is returning
String object.
110 | P a g e
Durgasoft Mr. Ratan
The toString() method is overridden some classes check the below implementation.
o In String class toString() is overridden to return content of String object.
o In StingBuffer class toString() is overridden to returns content of StringBuffer
class.
o In Wrapper classes(Integer,Byte,Character…etc) toString is overridden to returns
content of Wrapper classes.
internal implementation:-
class Object
{ public String toString()
{ return getClass().getName() + '@' + Integer.toHexString(hashCode());
}
};
Example:-
Note :- whenever you are printing reference variable internally toString() method is called.
Test t = new Test(); //creates object of Test class reference variable is “t”
//the below two lines are same.
System.out.println(t);
System.out.println(t.toString());
class Test
{ public static void main(String[] args)
{ Test t = new Test();
System.out.println(t);
System.out.println(t.toString()); // [Object class toString() executed]
}
};
Example -2:-
toString() method present in Object class but in our Test class we are overriding toString()
method hence our class toString() method is executed.
class Test
{ //overriding toString() method
public String toString()
{ return "ratansoft";
}
public static void main(String[] args)
{ Test t = new Test();
//below two lines are same
System.out.println(t); //Test class toString() executed
System.out.println(t.toString()); //Test class toString() executed
}
};
111 | P a g e
Durgasoft Mr. Ratan
String sname;
int sid;
Student(String sname,int sid) //local variables
{ //conversion
this.sname = sname;
this.sid = sid;
}
public String toString() //overriding toString() method
{ return "student name:-->"+sname+" student id:-->"+sid;
}
};
class TestDemo
{ public static void main(String[] args)
{ Student s1 = new Student("ratan",111);
//below two lines are same
System.out.println(s1); //student class toString() executed
System.out.println(s1.toString()); //student class toString() executed
112 | P a g e
Durgasoft Mr. Ratan
int eid ;
double esal;
Employee(String ename,int eid,double esal) //local variables
{ //conversion of local variables to instance variables
this.ename = ename;
this.eid = eid;
this.esal = esal;
}
public static void main(String[] args)
{ Employee e1 = new Employee("ratan",111,60000);
//whenever we are printing reference variables internally it calls toString() method
System.out.println(e1); //e1.toString() [our class toString() executed output printed]
}
};
D:\morn11>java Employee
Employee@530daa
In above example Employee class is not overriding toString() method so parent class(Object)
toString() method will be executed it returns hash code of the object.
113 | P a g e
Durgasoft Mr. Ratan
In above example when you print reference variables it is executing toString() hence Employee
values will be printed.
Final modifier:-
1) Final is the modifier applicable for classes, methods and variables (for all instance,
Static and local variables).
Case 1:-
1) if a class is declared as final, then we cannot inherit that class it means we cannot create child
class for that final class.
2) Every method present inside a final class is always final but every variable present inside the
final class not be final variable.
Example :-
final class Parent //parent is final class child class creation not possible
{ };
class Child extends Parent //compilation error
{ };
Example :-
Note :- Every method present inside a final class is always final but every variable present inside the
final class not be final variable.
final class Test
{ int a=10; //not a final variable
void m1() //final method
{ System.out.println("m1 method is final");
a=a+100;
System.out.println(a); //110
}
public static void main(String[] args)
{ Test t=new Test();
t.m1();
}
}
Case 2:-
If a method declared as a final we can not override that method in child class.
Example :-
class Parent
{ final void marry(){} //overridden method is final
};
class Child extends Parent
{ void marry(){} //overriding method
};
Compilation Error:- marry() in Child cannot override marry() in Parent
overridden method is final
Case 3:-
1) If a variable declared as a final we can not reassign that variable if we are trying to reassign
compiler generate error message.
2) For the local variables only one modifier is applicable that is final.
114 | P a g e
Durgasoft Mr. Ratan
Example:-
class Test
{ public static void main(String[] args)
{ final int a=100;//local variables
a = a+100; // [compilation error because trying to reassignment]
System.out.println(a);
}
};
Compilation Error :- cannot assign a value to final variable a
Example :-
class Parent
{ void m1(){}
};
class Child extends Parent
{ int m1(){}
};
D:\morn11>javac Test.java
m1() in Child cannot override m1() in Parent
return type int is not compatible with void
Garbage Collector
Garbage collector is destroying the useless object and it is a part of the JVM.
To make eligible objects to the garbage collector
115 | P a g e
Durgasoft Mr. Ratan
Example-1 :-
Whenever we are assigning null constants to our objects then objects are eligible for
GC(garbage collector)
class Test
{ public static void main(String[] args)
{ Test t1=new Test();
Test t2=new Test();
System.out.println(t1);
System.out.println(t2);
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
t1=null; //t1 object is eligible for Garbage collector
t2=null; //t2 object is eligible for Garbage Collector
System.out.println(t1);
System.out.println(t2);
}
};
Example-2 :-
Whenever we reassign the reference variable the objects are automatically eligible for
garbage collector.
class Test
{ public static void main(String[] args)
{ Test t1=new Test();
Test t2=new Test();
System.out.println(t1);
System.out.println(t2);
t1=t2; //reassign reference variable then one object is destroyed.
System.out.println(t1);
System.out.println(t2);
}
};
Example -3:-
Whenever we are creating objects inside the methods one method is completed the objects
are eligible for garbage collector.
class Test
{ void m1()
{ Test t1=new Test();
Test t2=new Test();
}
public static void main(String[] args)
{ Test t=new Test();
t.m1();
System.gc();
}
};
class Test
{ //overriding finalize()
public void finalize()
{ System.out.println("ratan sir object is destroyed");
116 | P a g e
Durgasoft Mr. Ratan
System.out.println(10/0);
}
public static void main(String[] args)
{ Test t1 = new Test();
Test t2 = new Test();
;;;;;;;//usage of objects
t1=null; //this object is eligible to Gc
t2=null; //this object is eligible to Gc
System.gc(); //calling GarbageCollector
}
}
//import java.lang.System;
import static java.lang.System.*;
class Test extends Object
{ public void finalize()
{System.out.println("object destroyed");
}
public static void main(String[] args)
{ Test t1 = new Test();
Test t2 = new Test();
t1=null;
t2=null;
gc(); //static import
}
};
Ex:- if the garbage collector is calling finalize Ex:- If user is calling finalize() method explicitly
method at that situation exception is raised at that situation exception is raised.
such type of exception are ignored. class Test
class Test { public void finalize()
{ public void finalize() {
{ System.out.println("ratan sir destroyed");
System.out.println("ratan sir destroyed"); int a=10/0;
int a=10/0; }
} public static void main(String[] args)
public static void main(String[] args) { Test t1=new Test();
{ Test t1=new Test(); Test t2=new Test();
Test t2=new Test(); t1=t2;
t1=t2; t2.finalize();
System.gc(); }
} };
};
Abstraction:-
There are two types of methods in java
a. Normal methods
b. Abstract methods
117 | P a g e
Durgasoft Mr. Ratan
Based on above representation of methods the classes are divided into two types
1) Normal classes.
2) Abstract classes.
Normal classes:-
Normal class is a ordinary java class it contains only normal methods if we are trying to declare at least
one abstract method that class will become abstract class.
Example:-
class Test //normal class
{ void m1(){body;} //normal method
void m2(){body;} //normal method
void m3(){body;}//normal method
};
Abstract class:-
Abstract class is a javaclass which contains at least one abstract method(wrong definition).
If any abstract method inside the class that class must be abstract.
Example 1:- Example-2:-
class Test //abstract class class Test //abstract class
{ {
void m1(){}//normal method abstract void m1();//abstract method
void m2(){}//normal method abstract void m2();//abstract method
void m3();//abstract method abstractvoid m3();//abstract method
}; };
Abstract modifier:-
Abstract modifier is applicable for methods and classes but not for variables.
To represent particular class is abstract class and particular method is abstract method to the
compiler use abstract modifier.
The abstract class contains declaration of methods it says abstract class partially implement
class hence for partially implemented classes object creation is not possible. If we are trying to
create object of abstract class compiler generate error message “class is abstract con not be
instantiated”
118 | P a g e
Durgasoft Mr. Ratan
Example -1:-
Abstract classes are partially implemented classes hence object creation is not possible.
For the abstract classes object creation not possible, if you are trying to create object compiler will
generate error message.
Example-2 :-
Abstract class contains abstract methods for that abstract methods provide the
implementation in child classes.
Provide the implementations is nothing but override the methods in child classes.
The abstract class contains declarations but for that declarations implementation is present in
child classes.
Test t1 = new Test1(); //abstract class reference variable Child class object
t1.m1(); //compile : Test runtime : Test1
t1.m2(); //compile : Test runtime : Test1
t1.m3() ; //compile : Test runtime : Test1
t1.m4() ; //compile : Test runtime : Test1
119 | P a g e
Durgasoft Mr. Ratan
}
};
Example -3 :-
Abstract class contains abstract methods for that abstract methods provide the
implementation in child classes.
if the child class is unable to provide the implementation of all parent class abstract methods
at that situation declare that class with abstractmodifier then take one more child class to
complete the implementation of remaining abstract methods.
It is possible to declare multiple child classes but at final complete the implementation of all
methods.
120 | P a g e
Durgasoft Mr. Ratan
}
public static void main(String[] args)
{ Test1 t = new Test1();
t.disp1();
t.disp2();
}
};
Example-5:-
for the abstract methods it is possible to provide any return type(void, int, char,Boolean…..etc)
class Emp{};
abstract class Test1
{ abstract int m1(char ch);
abstract boolean m2(int a);
abstract Emp m3();
}
abstract class Test2 extends Test1
{ int m1(char ch)
{ System.out.println("char value is:-"+ch);
return 100;
}
};
class Test3 extends Test2
{ boolean m2(int a)
{ System.out.println("int value is:-"+a);
return true;
}
Emp m3()
{ System.out.println("m3 method");
return new Emp();
}
public static void main(String[] args)
{ Test3 t=new Test3();
int a=t.m1('a');
System.out.println("m1() return value is:-"+a);
boolean b=t.m2(111);
System.out.println("m2() return value is:-"+b);
Emp e = t.m3();
System.out.println("m3() return value is:-"+e);
}
};
Example-6:-
It is possible to override non-abstract as a abstract method in child class.
abstract class Test
{ abstract void m1(); //m1() abstract method
121 | P a g e
Durgasoft Mr. Ratan
Example:-
abstract class Test
{ public static void main(String[] args)
{ System.out.println("this is abstract class main");
}
};
Example-8:-
Constructor is used to create object (wrong definition).
Constructor is executed during object creation to initialize values to instance variables.
Constructors are used to write the write the functionality that functionality executed during
object creation.
There are multiple ways to crate object in java but if we are crating object by using “new” then
only constructor executed.
Note :- in below example abstract class constructor is executed but object is not created.
abstract class Test
{ Test()
{ System.out.println("abstrac calss con");
}
};
class Test1 extends Test
{ Test1()
{ super();
System.out.println("normal class con");
}
public static void main(String[] args)
{ new Test1();
}
};
D:\>java Test1
abstrac calss con
normal class con
122 | P a g e
Durgasoft Mr. Ratan
Abstraction definition :-
The process highlighting the set of services and hiding the internal implementation is called
abstraction.
Bank ATM Screens Hiding the internal implementation and highlighting set of services like ,
money transfer, mobile registration,…etc).
Syllabus copy of institute just highlighting the contents of java but implementation there in
classed rooms .
We are achieving abstraction concept by using Abstract classes &Interfaces.
Encapsulation:-
The process of binding the data and code as a single unit is called encapsulation.
We are able to provide more encapsulation by taking the private data(variables) members.
To get and set the values from private members use getters and setters to set the data and to
get the data.
Example:-
class Encapsulation
123 | P a g e
Durgasoft Mr. Ratan
Main Method:-
125 | P a g e
Durgasoft Mr. Ratan
class Parent
{ public static void main(String[] args) class Parent
{ { public static void main(String[] args)
System.out.println("parent class"); {
} System.out.println("parent class");
}; }
class Child extends Parent };
{ public static void main(String[] args) class Child extends Parent
{ {
System.out.println("child class"); };
}
};
In above two examples execute both Parent and Child [.class] files to check the output.
Example-4:-main method VS overloading
class Test
{ public static void main(String[] args)
{
System.out.println("String[] parameter main method start");
main(100);//1-argument ( int ) method calling
}
public static void main(int a)
{
main('r'); //1-argument ( char ) method calling
System.out.println("int main method-"+a);
}
public static void main(char ch)
{
System.out.println("char main method-"+ch);
}
}
Strictfp modifier:-
a. Strictfp is a modifier applicable for classes and methods.
b. If a method is declared as strictfp all floating point calculations in that method will
followIEEE754 standard. So that we will get platform independent results.
c. If a class is declared as stictfp then every method in that class will follow IEEE754standard so we
will get platform independent results.
Ex:- strictfp class Test{ //methods///} --->all methods fallows IEEE754
strictfp void m1(){} ---> m1() method fallows IEE754
Native modifier:-
a. Native is the modifier applicable only for methods.
b. Native method is used to represent particular method implementations there in non-java code
(other languages like C,CPP) .
c. Nativemethods are also known as “foreign methods”.
Examples:-
public final int getPriority();
public final void setName(java.lang.String);
public static native java.lang.Thread currentThread();
public static native void yield();
126 | P a g e
Durgasoft Mr. Ratan
127 | P a g e
Durgasoft Mr. Ratan
128 | P a g e
Durgasoft Mr. Ratan
t.m1(10,20.5,'s',"aaaa");
t.m1(10,20.5,'s',"aaaa","bbb");
}
};
Note :-inside the method it is possible to declare only one variable-argument and that must be last
argument otherwise the compiler will generate compilation error.
void m1(int... a) --->valid
void m2(int... a,char ch) --->invalid
void m3(int... a,boolean... b) --->invalid
void m4(double d,int... a) --->valid
void m5(char ch ,double d,int... a) --->valid
void m6(char ch ,int... a,boolean... b) --->invalid
Example-5 :- var-arg method vs overloading
class Test
{ void m1(int... a)
{ for (int a1:a)
{ System.out.println(a1); }
}
void m1(String... str)
{ for (String str1:str)
{ System.out.println(str1); }
}
public static void main(String[] args)
{ Test t=new Test();
t.m1(10,20,30); //int var-arg method calling
t.m1("ratan","Sravya");//String var-arg calling
t.m1();//var-arg method vs ambiguity [compilation error ambiguous]
}
}
129 | P a g e
Durgasoft Mr. Ratan
Packages
java-language:-
in java James Gosling is maintained predefined support in the form of packages and
these packages contains classes & interfaces, and these classes and interfaces contains
predefined methods & variables.
java-language james gosling
packages java.lang
130 | P a g e
Durgasoft Mr. Ratan
java is a open source software we are able to download it free of cost and we are able
to see the source code of the java.
The source code location C:\Program Files\Java\jdk1.7.0_75\src(zip file) extract the zip file.
Java contains 14 predefined packages but the default package in java if java.lang.
package.
Java.lang java.beans java.text java.sql
Java.io java.net java.nio java.math
Java.util java.applet java.rmi
Java.awt java.times java.security
Note : The default package in java is java.lang package.
Note : package is nothing but physical folder structure.
Types of packages:-
There are two types of packages in java
1) Predefined packages.
2) User defined packages.
Predefined packages:
The predefined packages are introduced by James Gosling and these packages contains
predefined classes & interfaces and these class & interfaces contains predefined variables and methods.
Example:- java.lang, java.io ,java.util…..etc
User defined packages:-
The packages which are defined by user, and these packages contains user defined classes and
interfaces.
Declare the package by using package keyword.
syntax : package package-name;
example : package com.sravya;
Inside the source file it is possible to declare only one package statement and that statement
must be first statement of the source file.
Example-1:valid Example-3:Invalid
package com.sravya; import java.io.*;
import java.io.*; import java.lang.*;
import java.lang.*; package com.sravya;
Example-2:Invalid Example-4:Invalid
import java.io.*; package com.sravya;
package com.sravya; package com.tcs;
import java.io.*;
131 | P a g e
Durgasoft Mr. Ratan
|--Runnable(interface)
|--Cloneable(interface)
Note:- the default package in the java programming is java.lang package.
Java.io package:-The classes which are used to perform the input output operations that are present
in the java.io packages.
java
|------io
|--FileInputStream(class)
|--FileOutputStream(class)
|--FileReader(class)
|--FileWriter(class)
|--Serializable(interface)
Java.net package:-The classes which are required for connection establishment in the network that
classes are present in the java.net package.
java
|------net
|--Socket(class)
|--ServerSocket(class)
|--URL(class)
|--SocketOption(interface)
132 | P a g e
Durgasoft Mr. Ratan
Advantages of packages:-
company name : tcs
project name : bank
module-1Deposit module-2withdraw
com com
|-->tcs |-->tcs
|-->bank |-->bank
|-->deposit |-->withdraw
|--->.class files |--->.class files
Note :- In real time the project is divided into number of modules that each and every
module is nothing but package statement.
Example-1:-
Step-1: write the application with package statement.
package com.sravya.java.corejava;
class Test
{ public static void main(String[] args)
{ System.out.println("package first example");
}
}
class A
{}
class B
{}
interface It
{}
133 | P a g e
Durgasoft Mr. Ratan
D:\>javac -d . Test.java
Step-4:-execution process.
Execute the .class file by using fully qualified name(class name with complete package structure)
java com.sravya.java.corejava.Test
output : package first example
Example-2:-
Error-1 :-
If it is a predefined package or user defined package Whenever we are using other package
classes then must import that package by using import statement.
If the application required two classes (System,String) then We are able to import the classes in
two ways
o Importing all classes.
Import java.lang.*;
o Importing application required classes
Import java.lang.System;
Import java.lang.String;
In above two approaches second approach is recommended because it is importing application
required classes.
Error-2:-
Whenever we are using other package classes then that classes must be public otherwise
compiler generate error message.
Error:class is not public we are unable to access outside package.
134 | P a g e
Durgasoft Mr. Ratan
Public modifier:-
Public modifier is applicable for variables,methods,classes.
All packages are able to access public members.
Default modifier:-
It is applicable for variables,methods,classes.
We are able to access default members only within the package and it is not possible to access
outside package .
Default access is also known as package level access.
The default modifier in java is default.
Error-3:-
Whenever we are using other package class member that members also must be public.
Note : When we declare class as public the corresponding members are not public,
if we want access public class members that members also must be public.
File-1: Sravya.java
package com.sravya.states.info;
public class Sravya
{ public void ts(){System.out.println("jai telengana");}
public void ap(){System.out.println("jai andhra");}
public void others(){System.out.println("jai jai others");}
}
File-2: Tcs.java
package com.tcs.states.requiredinfo;
import com.sravya.states.info.*;
class Tcs
{ public static void main(String[] args)
{ Sravya s = new Sravya();
s.ts(); s.ap(); s.others();
}
}
E:\>javac -d . Sravya.java compilation of Sravya
E:\>javac -d . Tcs.java compilation of Tcs
E:\>java com.tcs.states.requiredinfo.Tcs execution of Tcs
jai telengana
jai andhra
jai jai others
Example:-
135 | P a g e
Durgasoft Mr. Ratan
Private modifier:-
private modifier applicable for methods and variables.
We are able to access private members only within the class and it is not possible to access even
in child classes.
class Parent
{ private int a=10;
};
class Child extends Parent
{ void m1()
{ System.out.println(a); //a variables is private Child class unable to access
}
public static void main(String[] arghs)
{ Child c = new Child();
c.m1();
}
};
error: a has private access in Parent
Note :- the most accessable modifier in java Is public & most restricted modifier in java is private.
Example :-
Protected modifier:-
Protected modifier is applicable for variables,methods.
We are able access protected members with in the package and it is possible to access outside
packages also but only in child classes.
But in outside package we can access protected members only by using child reference. If wetry
to use parent reference we will get compile time error.
A.java:-
package app1;
public class A
{ protected int fee=1000;
};
B.java:-
package app2;
import app1.*;
public class B extends A
{ public static void main(String[] args)
{ B b = new B( );
System.out.println(b.fee);
}
};
Parent-class method child-class method
Default default -->valid (same level)
protected , public --> valid (increasing permission )
Private --> invalid (decreasing permission)
136 | P a g e
Durgasoft Mr. Ratan
Summary of variables:-
modifier Private no-modifier protected public
Same class yes yes yes yes
Same package sub class no yes yes yes
Same package non sub class no yes yes yes
Different package sub class no no yes yes
Different package non sub class no no no yes
Example :-
Test.java:-
package app1;
public class Test
{ public void m1(){System.out.println("app1.Test class m1()");}
}
A.java:-
package app1.corejava;
public class A
{ public void m1(){System.out.println("app1.corejava.A class m1()");}
}
Ratan.java:-
import app1.Test;
137 | P a g e
Durgasoft Mr. Ratan
import app1.corejava.A;
class Ratan
{ public static void main(String[] args)
{ Test t = new Test();
t.m1();
A a =new A();
a.m1();
}
}
Example :-
Test.java:-
package app1;
public class Test
{ public void m1(){System.out.println("app1.Test class m1()");}
}
X.java:-
package app1.corejava;
public class X
{ public void m1(){System.out.println("app1.core.X class m1()");}
}
Y.java:-
package app1.corejava.advjava;
public class Y
{ public void m1(){System.out.println("app1.corejava.advjava.Y class m1()");}
}
Z.java:-
Package app1.corejava.advjava.structs;
public class Z
{ public void m1(){System.out.println("app1.corejava.advjava.structs.Z class m1()");}
}
Ratan.java:-
import app1.Test;
import app1.corejava.X;
import app1.corejava.advjava.Y;
import app1.corejava.advjava.structs.Z;
class Ratan
{ public static void main(String[] args)
{ Test t = new Test(); t.m1();
X x = new X(); x.m1();
Y y = new Y(); y.m1();
Z z = new Z(); z.m1();
}
};
Note :- applicable modifiers on constructors
1) Public
2) Private
3) Default (if we are not providing modifiers)
138 | P a g e
Durgasoft Mr. Ratan
4) Protected
Private constructors:-
class Parent
{ private Parent(){}//private constructor
}
class Child extends Parent
{ Child()
{super();} //we are calling parent class private constructor it is not possible
};
D:\>javac Test.java
Test.java:6: Parent() has private access in Parent
Static import:-
1. This concept is introduced in 1.5 version.
2. if we are using the static import it is possible to call static variables and static methods of a
particular class directly to the application without using class name.
a. import static java.lang.System.*;
The above line is used to call all the static members of System class directly into application
without using class name.
Example:-
package com.dss.java.corejava;
public class Sravya
{ public static int fee=1000;
public static void course()
{ System.out.println("core java");
}
public static void duration()
{ System.out.println("1-month");
}
public static void trainer()
{ System.out.println("ratan");
}
};
without static import package com.tcs.course.coursedetails;
139 | P a g e
Durgasoft Mr. Ratan
Example :-
When you import main package we are able to access only package classes, it is not possible to
access sub package classes, if we want sub package classes must import sub packages also.
Ex:-
com
|-->sravya
|--->A.class
|--->B.class
|--->C.class
|--->ratan
|--->D.class
In above example when we import com.sravya.*it is possible to access only three classes(A,B,C) but it is
not possible to access sub package classes (ratan package D class)if we want sub package classes must
import sub package(import com.sravya.ratan.*).
File-1: A.java
package jav.corejava; }
public class A
{ public void m1() Package structure:-
{System.out.println("core java World!"); jav
} |-->corejava
140 | P a g e
Durgasoft Mr. Ratan
|--->A.class
File-2: B.java:
package jav.corejava.advjava; jav
public class B |-->corejava
{ public void m1() |--->A.class
{System.out.println("Adv java World!"); |--->advjava
} |--->B.class
}
File-3: C.java:-
package jav.corejava.advjava.structs; jav
public class C |-->corejava
{ public void m1() |--->A.class
{System.out.println("Structs World!"); |--->advjava
} |--->B.class
} |--->structs
File-4:- MainTest.java |--->C.class
Package structure :-
import jav.corejava.A;
import jav.corejava.advjava.B;
import jav.corejava.advjava.structs.C;
class MainTest
{ public static void main(String[] args)
{ A a = new A(); a.m1();
B b = new B(); b.m1();
C c = new C(); c.m1();
}
}
Example :- in java it is not possible to use predefined package names as a user defined packages.
package java.lang;
class Test
{ public static void main(String[] args)
{ System.out.println("Ratan World!");
}
}
class A
{ };
D:\DP>javac -d . Test.java
D:\DP>java java.lang.Test
Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.lang
141 | P a g e
Durgasoft Mr. Ratan
3) Protected
4) default
File-2:-
Package com.dss;
Import com.dss.st.Test;
class Test1
{ public static void main(String[] args)
{ //Test t = new Test(); compilation error Test() has private access in Test
Test t1 = Test.getInstance();
Test t2 = Test.getInstance();
System.out.println(t1.hashCode());//31168322
System.out.println(t2.hashCode());//31168322
}
};
142 | P a g e
Durgasoft Mr. Ratan
143 | P a g e
Durgasoft Mr. Ratan
Interfaces
1. Interface is also one of the type of class it contains only abstract methods. And Interfaces not
alternative for abstract class it is extension for abstract classes.
2. The abstract class contains atleast one abstract method but the interface contains only abstract
methods.
3. For the interfaces the compiler will generates .class files.
4. Interfaces giving the information about the functionalities and these are not giving the
information about internal implementation.
5. Inside the source file it is possible to declare any number of interfaces. And we are declaring the
interfaces by using interface keyword.
Syntax:-Interface interface-name
interface it1 { }
and bydefault above three methods are public
the interface contains constants and these constants by default public static final
Note-1 :- if u dont no the anything about implementation just we have the requirment specification
them we should go for inteface
Note-2:- If u know the implementation but not completly then we shold go for abstract class
Note-3 :-if you know the implementation completly then we should go for concreate class
Note: - If we are declaring or not each and every interface method by default public abstract. And the
interfaces are by default abstract hence for the interfaces object creation is not possible.
Example-1 :-
Interface constrains abstract methods and by default these methods are “public abstract “.
144 | P a g e
Durgasoft Mr. Ratan
Interface contains abstract method for these abstract methods provide the implementation in
the implementation classes.
Implementation class is nothing but the class that implements particular interface.
While providing implementation of interface methods that implementation methods must be
public methods otherwise compiler generate error message “attempting to assign weaker
access privileges”.
Example-2:-
145 | P a g e
Durgasoft Mr. Ratan
Interface contains abstract method for these abstract methods provide the implementation in
the implementation class.
If the implementation class is unable to provide the implementation of all abstract methods
then declare implementation class with abstract modifier, take child class of implementation
class then complete the implementation of remaining abstract methods.
In java it is possible to take any number of child classes but at final complete the
implementation of all abstract methods.
//Test2is abstract class contains 1 abstract method m3()hence object creation not possible
abstract class Test2 extends Test1
{ public void m2()
{ System.out.println("m2 method"); }
};
//Test3 is normal class because it contains only normal methods hence object creation possible
class Test3 extends Test2
{ public void m3()
{ System.out.println("m3 method"); }
public static void main(String[] args)
{ Test3 t = new Test3();
t.m1(); t.m2(); t.m3();
}
};
interface It1 //abstract
{ void m1(); //public abstract
void m2();
void m3();
}
abstract class Test implements It1
{ public void m1(){System.out.println("m1 method");}
};
abstract class Test1 extends Test
{ public void m2(){System.out.println("m2 method");}
};
class Test2 extends Test1
{ public void m3(){System.out.println("m3 method");}
146 | P a g e
Durgasoft Mr. Ratan
Example 3:-
The interface reference variables is able to hold child class objects.
interface It1 // interface declaration
{ void m1(); //abstract method by default [public abstract]
void m2(); //abstract method by default [public abstract]
void m3(); //abstract method by default [public abstract]
}
//Test1 is abstract class contains 2 abstract methods m2() m3()hence object creation not possible
abstract class Test1 implements It1
{ public void m1()
{ System.out.println("m1 method"); }
};
//Test2 is abstract class contains 1 abstract method m3() hence object creation not possible
abstract class Test2 extends Test1
{ public void m2()
{ System.out.println("m2 method"); }
};
//Test3 is normal class because it contains only normal methods hence object creation possible
class Test3 extends Test2
{ public void m3()
{ System.out.println("m3 method"); }
public static void main(String[] args)
{ It1 t = new Test3(); t.m1(); t.m2(); t.m3();
Test1 t1 = new Test3(); t1.m1(); t1.m2(); t1.m3();
Test2 t2 = new Test3(); t2.m1(); t2.m2(); t2.m3();
}
};
interface It1
{ void m1();
}
interface It2
{ void m2();
}
147 | P a g e
Durgasoft Mr. Ratan
148 | P a g e
Durgasoft Mr. Ratan
7) The abstract class is able to provide 3. The interface allows declaring only
implementations of interface abstract methods.
methods.
8) One java class is able to extends only 4. Interface methods are by default
one abstract class at a time. public abstract.
9) Inside abstract class it is possible to
declare main method &constructors. 5. The interface contains abstract
10) It is not possible to instantiate methods writ the implementations
abstract class. in implementation classes.
11) For the abstract classes compiler
will generate .class files. 6. In implementation class the
12) The variables of abstract class need implementation methods must be
not be public static final. public.
Example-1:-
Inside the interfaces it is possible to declare variables and methods.
By default interface methods are public abstract and by default interface variables are public
static final.
The final variables are replaced with their values at compilation time only.
149 | P a g e
Durgasoft Mr. Ratan
System.out.println(a);
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
};
Application after compilation:-(.class file)
interface It1
{ public abstract void m1();// compiler generate public abstract
public static final int a = 10;//public static final generated by compiler
}
class Test implements It1
{ public void m1()
{ System.out.println("m1 method");
System.out.println(10);//a is final variable hence it replaced at compilation time only
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
};
150 | P a g e
Durgasoft Mr. Ratan
Message.java:-
package com.sravya.declarations;
public interface Message
{ void morn();
void even();
void gn();
}
Helper.java-
package com.sravya.helper;
import com.sravya.declarations.Message;
public abstract class Helper implements Message
{ public void gn(){System.out.println("good night from helper class");}
}
TestClient1.java:-
package com.sravya.client;
import com.sravya.declarations.Message;
class TestClient1 implements Message
{ public void morn(){System.out.println("good morning");}
public void even(){System.out.println("good evening");}
public void gn(){System.out.println("good 9t");}
public static void main(String[] args)
{ TestClient1 t = new TestClient1();
t.morn();
t.even();
t.gn();
}
}
TestClient2.java:-
package com.sravya.client;
import com.sravya.helper.Helper;
class TestClient2 extends Helper
{ public void morn(){System.out.println("good morning");}
public void even(){System.out.println("good evening");}
public static void main(String[] args)
{ TestClient2 t = new TestClient2();
t.morn();
t.even();
t.gn();
}
}
D:\>javac -d . Message.java
D:\>javac -d . Helper.java
D:\>javac -d . TestClient1.java
D:\>javac -d . TestClient2.java
151 | P a g e
Durgasoft Mr. Ratan
D:\>java com.sravya.client.TestClient1
good morning
good evening
good 9t
D:\>java com.sravya.client.TestClient2
good morning
good evening
good night from helper class
BusinessLogic.java:-
package com.dss.businesslogics;
import com.dss.declarations.Message;
public class BusinessLogic implements Message
{ public void msg1(){System.out.println("i like you");}
public void msg2(){System.out.println("i miss you");}
}
TestClient.java:-
package com.dss.client;
import com.dss.businesslogics.BusinessLogic;
class TestClient
{ public static void main(String[] args)
{ BusinessLogic b = new BusinessLogic();
b.msg1();
b.msg2();
Message b1 = new BusinessLogic();
b1.msg1();
b1.msg2();
}
}
152 | P a g e
Durgasoft Mr. Ratan
153 | P a g e
Durgasoft Mr. Ratan
};
Case 10:-
class Test implements it1,it2,it3
{ provide the implementation of 6 methods m1() & m2() & m3() & m4() & m5() & m6
};
Case 11:-
class Test implements it1,it2,it3,it4
{ provide the implementation of 7 methodsm1() & m2() & m3() & m4() & m5() & m6 & m7()
};
Nested interfaces:-
Example :- declaring interface inside the class is called nested interface.
class A
{ interface it1//nested interface declared in A class
{ void add(); }
};
class Test implements A.it1
{ public void add()
{ System.out.println("add method");
}
public static void main(String[] args)
{ Test t=new Test(); t.add();
}
};
Example :- it is possible to declare interfaces inside abstract class also.
abstract class A
{ abstract void m1();
interface it1 //nested interface declared in A class
{ void m2(); }
};
class Test implements A.it1
{ public void m1()
{ System.out.println("m1 method");
}
public void m2()
{ System.out.println("m2 method");
}
public static void main(String[] args)
{ Test t=new Test();
t.m1(); t.m2();
}
};
Ex:- declaring interface inside the another interface is called nested interface.
interface it2
{ void m1();
interface it1
{ void m2(); }
};
class Test2 implements it2.it1
154 | P a g e
Durgasoft Mr. Ratan
155 | P a g e
Durgasoft Mr. Ratan
Adaptor class:-
It is aintermediate class between the interface and user defined class. And it contains empty
implementation of interface methods.
Example:-
interface It // interface
{ void m1():
void m2();
;;;;;;;;
void m100();
}
class X implements It //adaptor class
{ public void m1(){}
public void m2(){}
;;;;;;;;
public void m100{}
};
//user defined class implementing interface
class Test implements It
{ must provide 100 methods impl
};
//user defined class extending Adaptor class(X)
class Test extends X
{ override required methods because already X contins empty implementions
};
156 | P a g e
Durgasoft Mr. Ratan
}
GoodStudent.java:-
package com.dss.bl;
import com.dss.declarations.Message;
public class GoodStudent implements Message
{ public void morn(){System.out.println("good morning ratan");}
public void eve(){System.out.println("good evening ratan");}
public void night(){System.out.println("good nightratan");}
}
TestClient.java:-
package com.dss.client;
import com.dss.bl.GoodStudent;
import com.dss.bl.Student;
class TestClient
{ public static void main(String[] args)
{ GoodStudent s = new GoodStudent();
s.eve();s.morn();s.night();
com
|-->dss
|--->declarations
| |-->Message.class
|-->helper
| |--->HelperAdaptor.class
|-->bl
| |-->GoodStudent.class
| |-->Student.class
|-->client
|-->TestClient.class
Example :-
Demo.java
package a;
public interface Demo
{ public void sayHello(String msg);
}
ImplClass:-
157 | P a g e
Durgasoft Mr. Ratan
package a;
class Test implements Demo
{ public void sayHello(String msg)//overriding method of Demo interface
{ System.out.println("hi ratan--->"+msg);
}
};
public class ImplClass
{ public Test objectcreation()//it returns Test class Object
{ Test t = new Test();
return t;
}
}
Client.java
import a.ImplClass;
import a.Demo;
class Client
{ public static void main(String[] args)
{ ImplClass i = new ImplClass();
Demo d = i.objectcreation();
//it returns Object of class Test but we don’t know internally which object is created
d.sayHello("hello");
}
}
String manipulations
1) Java.lang.String
2) Java.lang.StringBuffer
3) Java.lang.StringBuilder
4) Java.util.StringTokenizer
Java.lang.String:-
String is used to represent group of characters or character array enclosed with in the double
quotes.
class Test
158 | P a g e
Durgasoft Mr. Ratan
char[] ch={'r','a','t','a','n'};
String str3=new String(ch);
System.out.println(str3);
char[] ch1={'a','r','a','t','a','n','a'};
String str4=new String(ch1,1,5);
System.out.println(str4);
byte[] b={65,66,67,68,69,70};
String str5=new String(b);
System.out.println(str5);
byte[] b1={65,66,67,68,69,70};
String str6=new String(b1,2,4);
System.out.println(str6);
}
}
159 | P a g e
Durgasoft Mr. Ratan
== operator :-
It is comparing reference type and it returns Boolean value as a return value.
If two reference variables are pointing to same object then it returns true otherwise false.
Example:-
class Test
{ public static void main(String[] args)
{ Test t1 = new Test();
Test t2 = new Test();
Test t3 = t1;
System.out.println(t1==t2); //false
System.out.println(t1==t3); //true
160 | P a g e
Durgasoft Mr. Ratan
String str1="ratan";
String str2="ratan";
System.out.println(str1==str2); //true
Example :-
class Test
{ public static void main(String[] args)
{ //immutability class (modifications on existing content not allowed)
String str="ratan";
str.concat("soft");
System.out.println(str);
161 | P a g e
Durgasoft Mr. Ratan
One java class method is able to return same class object or different class object that method is
called factory method.
In java if the method is returning some class object that method is called factory method.
There are two types of factory methods in java
o Instance factory method
o Static factory method
Instance factory method:-
Concat() is factory method because it is present in String class and able to return String class
object only.
String str="ratan";
String str1 = str.concat("soft");
System.out.println(str1);
toString() is factory method because StringBuffer class toString() method is returning String class
object.
StringBuffer sb = new StringBuffer("anu");
String sss = sb.toString();
Static factory method:-
if the factory method is called by using class name that method is called static factory method.
Integer i = Integer.valueOf(100);
System.out.println(i);
Example :-
class Test
{ public static void main(String[] args)
{ //instance factory method [fctory method is called ]
String str="ratan";
String str1 = str.concat("soft");
System.out.println(str1);
StringBuffer sb = new StringBuffer("anu");
String sss = sb.toString();
Java.lang.String vs java.lang.StringBuffer:-
Internal implementation equals() method:-
equals() method present in object used for reference comparison & return Boolean value.
o If two reference variables are pointing to same object returns true otherwise false.
String is child class of object and it is overriding equals( ) methods used for content comparison.
o If two objects content is same then returns true otherwise false.
StringBuffer class is child class of object and it is not overriding equals() method hence it is using
parent class(Object) equals() method used for reference comparison.
o If two reference variables are pointing to same object returns true otherwise false.
162 | P a g e
Durgasoft Mr. Ratan
class Object
{ public boolean equals(java.lang.Object)
{ // reference comparison;
}
};
class String extends Object
{ //String class is overriding equals() method
public boolean equals(java.lang.Object);
{ //content comparison;
}
};
class StringBuffer extends Object
{ //not overriding hence it is using parent class equals() method
//reference comparison;
};
Example :-
class Test
{ Test(String str) { }
public static void main(String[] args)
{ Test t1 = new Test("ratan");
Test t2 = new Test("ratan");
//Object class equals() method executed (reference comparison)
System.out.println(t1.equals(t2));
Java.lang.String vs java.lang.StringBuffer:-
Internal implementation of toString method:-
toString( ) method Returns a string representation of the object and it is present in
java.lang.Object class.
String is child class of Object and String is overriding toString() used to return content of the
String.
StringBuffer is child class of Object and StringBuffer is overriding toString() used to return
content of the StringBuffer.
Note :- whenever we are printing reference variable internally it is calling toString() method
163 | P a g e
Durgasoft Mr. Ratan
In java when we print any type of reference variables internally it calls toString() method.
class Object
{ public java.lang.String toString()
{ return getClass().getName() + '@' + Integer.toHexString(hashCode()); }
}
class String extends Object
{ //overriding method
public java.lang.String toString()
{ return "content of String"; }
};
class StringBuffer extends Object
{ //overriding method
public java.lang.String toString()
{ return "content of String"; }
};
Example:-
class Test
{ public static void main(String[] args)
{ Test t = new Test();
//the below two lines are same (if we are printing reference variables it’s calling toString() method)
System.out.println(t); //object class toString() executed
System.out.println(t.toString());//object class toString() executed
String str="ratan";
System.out.println(str); //String class toString() executed
System.out.println(str.toString());//String class toString() executed
In above example when we call t.toString() JVM searching toString() in Test class since not there then
parent class(Object) toString() method is executed.
== operator vs equals() :-
In above example we are completed equals() method.
== operator used to check reference variables & returns boolean ,if two reference variables are
pointing to same object returns true otherwise false.
class Test
{ Test(String str){}
public static void main(String[] args)
{ Test t1 = new Test("ratan");
Test t2 = new Test("ratan");
System.out.println(t1==t2);//reference comparison false
164 | P a g e
Durgasoft Mr. Ratan
String str1="anu";
String str2="anu";
System.out.println(str1==str2); //reference comparison true
System.out.println(str1.equals(str2));//content comparison true
165 | P a g e
Durgasoft Mr. Ratan
System.out.println(s2==s3);//true
//String class equals() executed content comparison
System.out.println(s1.equals(s2));//true
class Test
{ public static void main(String[] args)
{ String str1 = "hello";
String str2 = "hello";
String str3= new String("hello");
System.out.println(str1==str2); //true
System.out.println(str1==str3); //false
System.out.println(str1==str3); //false
System.out.println(str1.equals(str2)); //true
System.out.println(str1.equals(str3)); //true
System.out.println(str2.equals(str3)); //true
}
}
Java.lang.String class methods:-
1) CompareTo() & compareToIgnoreCase():-
By using compareTo() we are comparing two strings character by character, such type of
checking is called lexicographically checking or dictionary checking.
compareTo() is return type is integer and it returns three values
a. zero ----> if both String are equal
b. positive --->if first string first character Unicode value is bigger than second String first
character Unicode value then it returns positive.
c. Negative ---> if first string first character Unicode value is smaller than second string first
character Unicode value then it returns negative.
compareTo() method comparing two string with case sensitive.
166 | P a g e
Durgasoft Mr. Ratan
class Test
{ public static void main(String... ratan)
{ String str1="ratan";
String str2="Sravya";
String str3="ratan";
System.out.println(str1.compareTo(str2));//14
System.out.println(str1.compareTo(str3));//0
System.out.println(str2.compareTo(str1));//-13
System.out.println(“ratan”.compareTo(“RATAN”));//+ve
System.out.println(“ratan”.compareToIgnoreCase(“RATAN”));//0
}
};
Difference between length() method and length variable:-
length variable used to find length of the Array.
length() is method used to find length of the String.
Example :-
int [] a={10,20,30};
System.out.println(a.length); //3
String str="rattaiah";
System.out.println(str.length()); //8
167 | P a g e
Durgasoft Mr. Ratan
System.out.println(ss.length());//7
System.out.println(ss.trim());//ratan
System.out.println(ss.trim().length());//5
}
}
replace() & toUpperCase() & toLowerCase():-
public java.lang.String replace(Stirng str,String str1):-
public java.lang.String replace(char, char);
replace() method used to replace the String or character.
public java.lang.String toLowerCase();
public java.lang.String toUpperCase();
The above methods are used to convert lower case to upper case & upper case to lower case.
Example:-
class Test
{ public static void main(String[] args)
{ String str="rattaiah how r u";
System.out.println(str.replace('a','A')); //rAttAiAh
System.out.println(str.replace("how","who")); //rattaiah how r u
168 | P a g e
Durgasoft Mr. Ratan
169 | P a g e
Durgasoft Mr. Ratan
System.out.println(i);
i=sb.lastIndexOf("hi");
System.out.println(i);
}
}
replace():-
class Test
{ public static void main(String[] args)
{ StringBuffer sb=new StringBuffer("hi ratan hi");
sb.replace(0,2,"oy");
System.out.println("after replaceing the string:-"+sb);
}
}
Java.lang.StringBuilder:-
1) Introduced in jdk1.5 version.
2) StringBuilder is identical to StringBuffer except for one important difference.
3) Every method present in the StringBuilder is not Synchronized means that is not thread safe.
4) multiple threads are allow to operate on StringBuilder methods hence the performance of the
application is increased.
Cloneable:-
1) The process of creating exactly duplicate object is called cloning.
2) We can create a duplicate object only for the cloneable classes .
3) We can create cloned object by using clone()
4) The main purpose of the cloning is to maintain backup.
170 | P a g e
Durgasoft Mr. Ratan
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="hi ratan w r u wt bout anushka";
StringTokenizer st = new StringTokenizer(str);//split the string with by default (space symbol)
while (st.hasMoreElements())
{
System.out.println(st.nextElement());
}
}
}
171 | P a g e
Durgasoft Mr. Ratan
Wrapper classes
Java is an Object oriented programming language so represent everything in the form of
the object, but java supports 8 primitive data types these all are not part of object.
To represent 8 primitive data types in the form of object form we required 8 java classes
these classes are called wrapper classes.
All wrapper classes present in the java.lang package and these all classes are immutable
classes.
Wrapper classes hierarchy:-
Object
172 | P a g e
Durgasoft Mr. Ratan
Note :- To create wrapper objects all most all wrapper classes contain two constructors but
Float contains three constructors(float,double,String) & char contains one constructor(char).
toString():-
toString() method present in Object class it returns class-name@hashcode.
String,StringBuffer classes are overriding toString() method it returns content of the objects.
All wrapper classes overriding toString() method to return content of the wrapper class objects.
Example :-
class Test
{ public static void main(String[] args)
{ Integer i1 = new Integer(100);
System.out.println(i1);
System.out.println(i1.toString());
173 | P a g e
Durgasoft Mr. Ratan
Example:-
In java we are able to call toString() method only on reference type but not primitive type.
If we are calling toString() method on primitive type then compiler generate error message.
class Test
{ public static void main(String[] args)
{ Integer i1 = Integer.valueOf(100);
System.out.println(i1);
System.out.println(i1.toString());
int a=100;
System.out.println(a);
//System.out.println(a.toString()); error:-int cannot be dereferenced
}
}
valueOf():-
in java we are able to create wrapper object in two ways.
a) By using constructor approach
b) By using valueOf() method
valueOf() method is used to create wrapper object just it is alternate to constructor approach
and it a static method present in wrapper classes.
Example:-
class Test
{ public static void main(String[] args)
{ //constructor approach to create wrapper object
Integer i1 = new Integer(100);
174 | P a g e
Durgasoft Mr. Ratan
System.out.println(i1);
Integer a2 = Integer.valueOf("1000");
System.out.println(a2);
}
}
Integer a2 = Integer.valueOf("1000");
System.out.println(a2);
175 | P a g e
Durgasoft Mr. Ratan
parseXXX():- it is used to convert String into corresponding primitive value& it is a static method present
in wrapper classes.
Example :-
class Test
{ public static void main(String[] args)
{ String str1="100";
String str2="100";
System.out.println(str1+str2);
//parseXXX() converion of String to primitive type
int a1 = Integer.parseInt(str1);
float a2 = Float.parseFloat(str2);
System.out.println(a1+a2);
}
}
176 | P a g e
Durgasoft Mr. Ratan
Example:-
class Test
{ public static void main(String[] args)
{ //autoboxing [primitive - wrapper object]
Integer i = 100;
System.out.println(i);
System.out.println(i.toString());
Factory method:-
One java class method returns same class object or different class object is called factory
method.
There are three types of factory methods in java.
o Instance factory method.
o Static factory method.
o Pattern factory method.
The factory is called by using class name is called static factory method.
The factory is called by using reference variable is called instance factory method.
One java class method is returning different class object is called pattern factory method.
Example:-
177 | P a g e
Durgasoft Mr. Ratan
class Test
{ public static void main(String[] args)
{ //static factory method
Integer i = Integer.valueOf(100);
System.out.println(i);
Runtime r = Runtime.getRuntime();
System.out.println(r);
String s1="sravyainfotech";
String s2 = s1.substring(0,6);
System.out.println(s2);
178 | P a g e
Durgasoft Mr. Ratan
2) Open a file.
3) Read the data from the file.
4) Writing information to file.
5) Closing file.
Stream :-
Stream is a channel it support continiuos flow of data from one palce to another place
Java.io is a package which contains number of classes by using that classes we are able to send
the data from one place to another place.
In java language we are transferring the data in the form of two ways:-
1. Byte format
2. Character format
Stream/channel:-
It is acting as medium by using steam or channel we are able to send particular data from one
place to the another place.
2)FileOutputStream
public native void write(int) throws java.io.IOException;
public void close() throws java.io.IOException;
To read the data from the destination file to the java application we have to use FileInputSream
class.
To read the data from the .txt file we have to read() method.
Java.io.FileOutputStream:-
To write the data to the destination file we have to use the FileOutputStream.
179 | P a g e
Durgasoft Mr. Ratan
To write the data to the destination file we have to use write() method.
Example :-
import java.io.*;
class Test
{ public static void main(String[] args)throws Exception
{ FileReader fr = new FileReader("abc.txt");//read data from source file
FileWriter fw = new FileWriter("xyz.txt");//write data to target file
int c;
while((c=fr.read())!=-1) //read and checking operations
{ System.out.print((char)c); //printing data of the file
fw.write(c); //writing data to target file
}
System.out.println("read() & write operatoins are completed");
//stream closing operations
fr.close();
fw.close();
}
}
Line oriented I/O:-
180 | P a g e
Durgasoft Mr. Ratan
Character oriented streams supports single character and line oriented streams supports single
line data.
BufferedReader:- to read the data line by line format and we have to use readLine() to read the data.
PrintWriter :- to write the data line by line format and we have to use println() to write the data.
Example :-
import java.io.*;
class Test
{ static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args)
{ try{
br=new BufferedReader(new FileReader("get.txt"));
pw=newPrintWriter(new FileWriter("set.txt"));
String line;
while ((line=br.readLine())!=null)//reading & checking
{ System.out.println(line); //printing data of file
pw.println(line); //writing data to target file
}
//close the streams
br.close();
pw.close();
}
catch(IOException io)
{ System.out.println("getting IOException");
}
}
}
Buffered Streams:-
Up to we are working with non buffered streams these are providing less performance because
these are interact with the hard disk, network.
Now we have to work with Buffered Streams
BufferedInputStream read the data from memory area known as Buffer.
Ex:-
import java.io.*;
class Test
{ static BufferedReader br;
static BufferedWriter bw;
public static void main(String[] args)
{ try{
br=new BufferedReader(new FileReader("Test1.java"));
181 | P a g e
Durgasoft Mr. Ratan
Ex:-
import java.io.*;
class Test
{ static BufferedInputStream bis;
static BufferedOutputStream bos;
public static void main(String[] args)
{ try{
bis=new BufferedInputStream(new FileInputStream("abc.txt"));
bos=new BufferedOutputStream(new FileOutputStream("xyz.txt"));
int str;
while ((str=bis.read())!=-1)
{ bos.write(str);
}
bis.close();
bos.close();
}
catch(Exception e)
{ System.out.println(e);
System.out.println("getting Exception");
}
}
}
Ex:-
import java.io.*;
class Test
{ public static void main(String[] args) throws IOException
{ BufferedReader br=new BufferedReader(new FileReader("abc.txt"));
String str;
while ((str=br.readLine())!=null)
{ System.out.println(str);
}
}
}
182 | P a g e
Durgasoft Mr. Ratan
Serialization:-
The process of saving an object to a file (or) the process of sending an object across the network is called
serialization.
But strictly speaking the process of converting the object from java supported form to the network
supported form of file supported form.
To do the serialization we required fallowing classes
1. FileOutputStream
2. ObjectOutputStream
Deserialization:-
The process of reading the object from file supported form or network supported form to the
java supported form is called deserialization.
We can achieve the deserialization by using fallowing classes.
1. FileInputStream
2. ObjectInputStream
import java.io.*;
class Emp implements Serializable
{ int eid;
String ename;
Emp(int eid,String ename)
{this.eid=eid;
this.ename=ename;
}
public static void main(String[] args)throws Exception
{
Emp e = new Emp(111,"ratan");
Transient modifier is the modifier applicable for only variables and we can’t apply for
methodsand classes.
At the time of serialization, if we don’t want to save the values of a particular variable to
meetsecurity constraints then we should go for transient modifier.
183 | P a g e
Durgasoft Mr. Ratan
At the time of serialization JVM ignores the original value of transient variable and default
valuewill be serialized
import java.io.*;
class Emp implements Serializable
{ transient int eid;
transient String ename;
}
0----null
Exception Handling
Information regarding Exception:-
Dictionary meaning of the exception is abnormal termination.
An expected event that disturbs or terminates normal flow of execution called exception.
If the application contains exception then the program terminated abnormally the rest of the
application is not executed.
To overcome above limitation in order to execute the rest of the application must handle the
exception.
In java we are having two approaches to handle the exceptions.
1) By using try-catch block.
2) By using throws keyword.
184 | P a g e
Durgasoft Mr. Ratan
Exception Handling:-
The main objective of exception handling is to get normal termination of the application in order to
execute rest of the application code.
Exception handling means just we are providing alternate code to continue the execution of
remaining code and to get normal termination of the application.
Every Exception is a predefined class present in different packages.
java.lang.ArithmeticException
java.io.IOException
java.sql.SQLException
javax.servlet.ServletException
185 | P a g e
Durgasoft Mr. Ratan
Unchecked Exception:-
The exceptions which are not checked by the compiler at the time of compilation are called
unchecked Exception.
ArithmeticException,ArrayIndexOutOfBoundsException,NumberFormatException….etc
If the application contains un-checked Exception code is compiled but at runtime JVM(Default
Exception handler) display exception message then program terminated abnormally.
To overcome runtime problem must handle the exception in two ways.
o By using try-catch blocks.
o By using throws keyword.
Example :- different types of unchecked exceptions.
class Test
{ public static void main(String[] args)
{ //java.lang.ArithmeticException: / by zero
System.out.println(10/0);
//java.lang.ArrayIndexOutOfBoundsException
int[] a={10,20,30};
System.out.println(a[5]);
//java.lang.StringIndexOutOfBoundsException
System.out.println("ratan".charAt(10));
}
}
Note-1:-
If the application contains checked exception compiler generate information about
exception so code is not compiled hence must handle that exception by using try-catch block
or throws keyword it means for the checked exceptions try-catch blocks or throws keyword
mandatory but if the application contains un-checked exception try-catch blocks or throws
keyword is optional it means code is compiled but at runtime program is terminated
abnormally.
Note 2:-
In java whether it is a checked Exception or unchecked Exception must handle the
Exception by using try-catch blocks or throws keyword to get normal termination of
application.
Note-3:-
In java whether it is checked Exception or unchecked exceptions are occurred at runtime
but not compile time.
186 | P a g e
Durgasoft Mr. Ratan
Error:-
Errors are caused due to lack of system resources like,
o Heap memory full.
o Stack memory problem.
o AWT component problems…..etc
Ex: - StackOverFlowError, OutOfMemoryError, AssertionError…………etc
Exceptions are caused due to developers mistakes or end user supplied inputs but errors are
caused due to lack of system resources.
We are handle the exceptions by using try-catch blocks or throws keyword but we are unable to
handle the errors.
Example:-
class Test
{ public static void main(String[] args)
{ Test[] t = new Test[100000000];
}
};
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
187 | P a g e
Durgasoft Mr. Ratan
In above tree Structure RuntimeException its child classes and Error its child classes are
Unchecked remaining all exceptions are checked Exceptions.
188 | P a g e
Durgasoft Mr. Ratan
1) Whenever the exception is raised in the try block JVM won’t terminate the program immidiatly
it will search corresponding catch block.
a. If the catch block is matched that will be executed then rest of the application executed
and program is terminated normally.
b. If the catch block is not matched program is terminated abnormally.
class Test
{
public static void main(String[] args)
{
System.out.println("ratan 1st class");
System.out.println("ratan 2st class");
System.out.println("ratan inter");
System.out.println("ratan trainer");
try
{ //Exceptional code
System.out.println("ratan weds anushka"+(10/0));
}
catch (ArithmeticException ae)
{ //alternate code
System.out.println("ratan weds aruna");
}
System.out.println("ratan kids");
}
}
D:\>java Test
ratan 1st class
ratan 2st class
ratan inter
ratan trainer
ratan weds aruna
ratan kids
Example :-
If the exceptions raised in try block JVM will search for corresponding catch block,
o If the catch block is matched corresponding catch is executed then rest of the application is
executed & program terminated normally.
o If the catch block is not matched program is terminated abnormally the rest of the
application is not executed.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
System.out.println(10/0);
}
catch(NullPointerException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
189 | P a g e
Durgasoft Mr. Ratan
}
}
E:\sravya>java Test
sravya
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example-3:-If there is no exception in try block the catch blocks are not checked.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
System.out.println("anu");
}
catch(NullPointerException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}
E:\sravya>java Test
sravya
anu
rest of the app
Example:-
in Exception handling independent try blocks are not allowed must declare try-catch ortry-
finally or try-catch-finally.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
System.out.println("anu");
}
System.out.println("rest of the app");
}
}
E:\sravya>javac Test.java
Test.java:4: 'try' without 'catch' or 'finally'
Example:-
In between try-catch blocks it is not possible to declare any statements must declare try with
immediate catch block.
class Test
{ public static void main(String[] args)
{ try
190 | P a g e
Durgasoft Mr. Ratan
{ System.out.println("sravya");
System.out.println(10/0);
}
System.out.println("anu");
catch(ArithmeticException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}
Example:-
If the exception raised in try block jvm will search corresponding catch block.
If the exception raised other than try block it is always abnormal termination.
In below example exception raised in catch block hence program is terminated abnormally.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
System.out.println(10/0);
}
catch(ArithmeticException e)
{ System.out.println(10/0);
}
System.out.println("rest of the app");
}
}
E:\sravya>java Test
sravya
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.main(Test.java:9)
Example:-
If the exception raised in try block remaining code of try block won’t be executed.
1) Once the control is out of the try block the control never entered into try block once again.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println(10/0);
System.out.println("sravya");
System.out.println("ratan");
}
catch(ArithmeticException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
191 | P a g e
Durgasoft Mr. Ratan
}
E:\sravya>java Test
5
rest of the app
Example 8:-
The way of handling the exception is varied from exception to the exception hence it is recommended
to provide try with multiple number of catch blocks.
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in); //Scanner object used to take dynamic input
System.out.println("provide the division value");
int n=s.nextInt();
try
{ System.out.println(10/n);
String str=null;
System.out.println("u r name is :"+str);
System.out.println("u r name length is--->"+str.length());
}
catch (ArithmeticException ae)
{ System.out.println("good boy zero not allowed geting Exception"+ae);
}
catch (NullPointerException ne)
{ System.out.println("good girl getting Exception"+ne);
}
System.out.println("rest of the code");
}
}
Output:- provide the division value: 5
Write the output
Output:- provide the division value: 0
Write the output
Example-9:- By using Exceptional catch block we are able to hold any type of exceptions.
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("provide the division value");
int n=s.nextInt();
try
{ System.out.println(10/n);
String str=null;
System.out.println("u r name is :"+str);
System.out.println("u r name length is--->"+str.length());
}
catch (Exception e)//this catch block is able to handle all types of Exceptions
{System.out.println("I am an inexperienced or lazy programmer here="+e);
}
192 | P a g e
Durgasoft Mr. Ratan
193 | P a g e
Durgasoft Mr. Ratan
catch () catch ()
{ try { }
{ } }
catch () catch ()
{ } { try
} { }
Possibility-6 catch ()
try { }
{ try }
{ }
Example 11:-
It is possible to combine two exceptions in single catch block the syntax is
catch(ArithmeticException | StringIndexOutOfBoundsException a) .
import java.util.Scanner;
public class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("enter a number");
int n = s.nextInt();
try {
System.out.println(10/n);
System.out.println("ratan".charAt(13));
}
catch(ArithmeticException | StringIndexOutOfBoundsException a)
{ System.out.println("ratansoft");
}
System.out.println("Rest of the application");
}
}
D:\DP>java Test D:\DP>java Test
enter a number enter a number
0 2
ratansoft 5
Rest of the application ratansoft
Rest of the application
Finally block:-
1) Finally block is always executed irrespective of try and catch.
2) It is used to provide clean-up code
a. Database connection closing. Connection.close();
b. streams closing. Scanner.close();
c. Object destruction . Test t = new Test();t=null;
3) It is not possible to write finally alone.
a. try-catch-finally --valied
b. try-catch --valied
194 | P a g e
Durgasoft Mr. Ratan
c. catch-finally --invalied
d. try-catch-catch-finally --valied
e. try-finally --valied
f. catch-catch-finally --invalied
g. Try --invalied
h. Catch --invalied
i. Finally -invalied
Syntax:-
try
{ risky code;
}
catch (Exception obj)
{ handling code;
}
finally
{ Clean-up code;(database connection closing,streams closing……etc)
}
Example:-
if the exception raised in try block the JVM will search for corresponding catch block ,
If the corresponding catch block is matched the catch block is executed then finally block is
executed.
If the corresponding catch block is not matched the program is terminated abnormally just
before abnormal termination the finally block will be executed then program is terminated
abnormally.
All possibilities of finally block execution :-
Case 1:- case 2:-
try try
{ System.out.println("try"); { System.out.println(10/0);
} }
catch (ArithmeticException ae) catch (ArithmeticException ae)
{ System.out.println("catch"); { System.out.println("catch");
} }
finally finally
{ System.out.println("finally"); { System.out.println("finally");
} }
Output:- Output:-
try catch
finally finally
195 | P a g e
Durgasoft Mr. Ratan
196 | P a g e
Durgasoft Mr. Ratan
}
};
D:\>java Test
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.main(Test.java:5)
Case 2:-In your program whenever we are using System.exit(0) the JVM will be shutdown hence the
rest of the code won’t be executed .
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("ratan");
System.exit(0);
}
finally
{ System.out.println("finally block");
}
System.out.println("rest of the code");
}
};
D:\>java Test
Ratan
Methods to print Exception information:-
class Test1
{ void m1()
{ m2(); }
void m2()
{ m3(); }
void m3()
{ try{
System.out.println(10/0);}
catch(ArithmeticException ae)
{
System.out.println(ae.toString());
System.out.println(ae.getMessage());
ae.printStackTrace();
}
}
public static void main(String[] args)
{ Test1 t = new Test1();
t.m1();
}
};
D:\DP>java Test1
197 | P a g e
Durgasoft Mr. Ratan
198 | P a g e
Durgasoft Mr. Ratan
{ }
Example :-
statement 1
statement 2
try
{ statement 3
try
{ statement 4
statement 5
}
catch ()
{ statement 6
statement 7
}
}
catch ()
{ statement 8
statement 9
try
{ statement 10
statement 11
}
catch ()
{ statement 12
statement 13
}
}
Finally{
statement 14
statement 15
}
Statement -16
Statement -17
case 1:- if there is no Exception in the above example
1, 2, 3, 4, 5, 14, 15 Normal Termination
Case 2:- if the exception is raised in statement 2
1 , Abnrmal Termination
Case 3:- if the exception is raised in the statement 3 the corresponding catch block is matched.
1,2,8,9,10,11,14,15 normal termination
Case 4:- if the exception is raise in the statement-4 the corresponding catch block is not
matched and outer catch block is not matched.
1,2,3 abnormal termination.
Case 5:- If the exception is raised in the statement 5 and corresponding catch block is not
matched and outer catch block is matched.
1,2,3,4,8,9,10,11,14,15 normal termination
Case 6:- If the exception is raised in the statement 5 and the corresponding catch block is not
matched and outer catch block is matched while executing outer catch inside the try
199 | P a g e
SravyaInfotech Mr. Ratan
block the exception is raised in the statement 10 and the corresponding catch is
matched.
1,2,3,4,8,9,12,13,14,15 normal termination.
Case 7:- If the exception raised in statement 14.
1,2,3,4,5 abnormal termination.
Case 8:- if the Exception raised in statement 17.
Throws :-
1) In the exception handling must handle the exception in two ways
a. By using try-catch blocks.
b. By using throws keyword.
2) Try-catch block is used to handle the exception but throws keyword is used to delegate the
responsibilities of the exception handling to the caller method.
3) The main purpose of the throws keyword is bypassing the generated exception from present
method to caller method.
4) Use throws keyword at method declaration level.
5) It is possible to throws any number of exceptions at a time based on the programmer
requirement.
6) If main method is throws the exception then JVm is responsible to handle the exception.
200 | P a g e
SravyaInfotech Mr. Ratan
Throw:-
1) The main purpose of the throw keyword is to creation of Exception object explicitly either for
predefined or user defined exception.
2) Throw keyword works like a try block. The difference is try block is automatically find the
situation and creates an Exception object implicitly. Whereas throw keyword creates an
Exception object explicitly.
3) Throws keyword is used to delegate the responsibilities to the caller method but throw is used
to create the exception object.
4) If exception object created by JVM it will print predefined information (/ by zero) but if
exception Object created by user then user defined information is printed.
5) We are using throws keyword at method declaration level but throw keyword used at method
implementation (body) level.
201 | P a g e
SravyaInfotech Mr. Ratan
class Test
{ static void validate(int age)
{ if (age<18)
{
//creating Exception object by user & handover to Jvm
throw new ArithmeticException("not eligible for vote");
}
else
{ System.out.println("welcome to the voting");
}
}
public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int n=s.nextInt();
validate(n);
System.out.println(“rest of the code”);
}
}
Objective-2 :- throw keyword is used to create the exception object explicitly by the developer for the
user defined exceptions.
There are two types of exceptions present in the java language
1) Predefined Exceptions.
2) User defined Exceptions.
Predefined Exception:-
These exceptions are introduced by James Gosling comes along with software.
Ex:- ArithmeticException,IOException,NullPointerException…………..etc
User defined Exceptions:-
Exceptions created by user are called userdefined Exceptions.
Ex: InvalidAgeException,BombBlostException………..etc
202 | P a g e
SravyaInfotech Mr. Ratan
203 | P a g e
SravyaInfotech Mr. Ratan
Ex:- creation of user defined un-checked exception by using default constructor approach:-
Step-1:- create userdefined exception.
InvalidAgeException.java
//InvalidAgeException.java
204 | P a g e
SravyaInfotech Mr. Ratan
package com.tcs.userexceptions;
public class InvalidAgeExcepiton extends RuntimeException
{
//default constructor
};Note: - in this example we are creating user defined unchecked exception so try-catch blocks and
throws keywords are optional.
Step-2:- use user created Exception in our project.
Project.java
package com.tcs.project;
import com.tcs.userexceptions.InvalidAgeExcepiton;
import java.util.Scanner;
class Test
{ static void status(int age)
{ if (age>25)
{System.out.println("eligible for mrg");
}
else
{//useing user created Exception
throw new InvalidAgeExcepiton();
}
}
public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("enter u r age");//23
int age = s.nextInt();
Test.status(age);
}
}Ex:- creation of user defined un-checked exception by using parameterized constructor
approach:-
InvalidAgeException.java
//InvalidAgeException.java
package com.tcs.userexceptions;
public class InvalidAgeExcepiton extends RuntimeException
{
public InvalidAgeExcepiton(String str)
{super(str);
}
};
Project.java
package com.tcs.project;
import com.tcs.userexceptions.InvalidAgeExcepiton;
import java.util.Scanner;
class Test
{ static void status(int age)
{ if (age>25)
{System.out.println("eligible for mrg");
}
else
205 | P a g e
SravyaInfotech Mr. Ratan
206 | P a g e
SravyaInfotech Mr. Ratan
System.out.println(str.charAt(3));//t
System.out.println(str.charAt(13));//StringIndexOutOfBoundsException
NegativeArraySizeException:-
int[] a1=new int[100];
System.out.println(a1.length);//100
int[] a=new int[-9];
System.out.println(a.length);//NegativeArraySizeException
InputMismatchException:-
Scanner s=new Scanner(System.in);
System.out.println("enter first number");
int a=s.nextInt();
D:\>java Test
enter first number
ratan
Exception in thread "main" java.util.InputMismatchException
207 | P a g e
SravyaInfotech Mr. Ratan
UncheckedException Description
Multi Threading
Information about multithreading:-
1) The earlier days the computer’s memory is occupied only one program after completion of one
program it is possible to execute another program is called uni programming.
2) Whenever one program execution is completed then only second program execution will be
started such type of execution is called co operative execution, this execution we are having lot
of disadvantages.
a. Most of the times memory will be wasted.
208 | P a g e
SravyaInfotech Mr. Ratan
b. CPU utilization will be reduced because only program allow executing at a time.
c. The program queue is developed on the basis co operative execution
To overcome above problem a new programming style will be introduced is called multiprogramming.
Advantages of multiprogramming:-
Thread:-
1) Thread is nothing but separate path of sequential execution.
2) The independent execution technical name is called thread.
3) Whenever different parts of the program executed simultaneously that each and
every part is called thread.
4) The thread is light weight process because whenever we are creating thread it is not
occupying the separate memory it uses the same memory. Whenever the memory is
shared means it is not consuming more memory.
5) Executing more than one thread a time is called multithreading.
209 | P a g e
SravyaInfotech Mr. Ratan
class CurrentThreadDemo
{ public static void main(String[] arhgs)
{ Thread t=Thread.currentThread();
System.out.println("current Thread--->"+t);
//change the name of the thread
t.setName("ratan");
System.out.println("after name changed---> "+t);
}
};
210 | P a g e
SravyaInfotech Mr. Ratan
Example :-
class MyThread extends Thread//defining a Thread
{ //business logic of user defined Thread
public void run()
{ for (int i=0;i<10;i++)
{ System.out.println("userdefined Thread");
}
}
};
class ThreadDemo
{ public static void main(String[] args) //main thread started
{ MyThread t=new MyThread(); //MyThread is created
t.start(); //MyThread execution started
//business logic of main Thread
for (int i=0;i<10;i++)
{ System.out.println("Main Thread");
}
}
};
Flow of execution:-
1) Whenever we are calling t.start() method then JVM will search start() method in the MyThread
class since not available so JVM will execute parent class(Thread) start() method.
Thread class start() method responsibilities
a. User defined thread is registered into Thread Scheduler then only decide new Thread is
created.
b. The Thread class start() automatically calls run() to execute logics of userdefined Thread.
Thread Scheduler:-
Thread scheduler is a part of the JVM. It decides thread execution.
Thread scheduler is a mental patient we are unable to predict exact behavior of Thread
Scheduler it is JVM vendor dependent.
Thread Scheduler mainly uses two algorithms to decide Thread execution.
1) Preemptive algorithm.
2) Time slicing algorithm.
We can’t expect exact behavior of the thread scheduler it is JVM vendor dependent. So we
can’tsay expect output of the multithreaded examples we can say the possible outputs.
211 | P a g e
SravyaInfotech Mr. Ratan
Preemptive scheduling:-
In this highest priority task is executed first after this task enters into waiting state or dead state
then only another higher priority task come to existence.
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.
212 | P a g e
SravyaInfotech Mr. Ratan
First approach:-
important point is that when extending the Thread class, the sub class cannot extend any
other base classes because Java allowsonlysingle inheritance.
Second approach:-
1) Implementing the Runnable interface does not give developers any control over the thread
itself, as it simply defines the unit of work that will be executed in a thread.
2) By implementing the Runnable interface, the class can still extend other base classes if
necessary.
Creating two threads by extending Thread class using anonymous inner classes:-
class ThreadDemo
{ public static void main(String[] args)
{ Thread t1 = new Thread() //anonymous inner class
{ public void run()
{System.out.println("user Thread-1");
}
};
213 | P a g e
SravyaInfotech Mr. Ratan
214 | P a g e
SravyaInfotech Mr. Ratan
}
};
215 | P a g e
SravyaInfotech Mr. Ratan
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t=new MyThread();
t.start();
for (int i=0;i<5 ;i++ )
{ System.out.println("main thread");
}
}
}
Different Threads are performing different tasks:--
1) Particular task is performed by the number of threads here number of threads(t1,t2,t3) are
executing same method (functionality).
2) In the above scenario for each and every thread one stack is created. Each and every
method called by particular Thread the every entry stored in the particular thread stack.
216 | P a g e
SravyaInfotech Mr. Ratan
{ System.out.println("Sravyasoft task");
}
}
class ThreadDemo
{ public static void main(String[] args)//main Thread is started
{ MyThread t1=new MyThread(); //new Thread created
MyThread t2=new MyThread(); //new Thread created
MyThread t3=new MyThread(); //new Thread created
t1.start(); //Thread started
t2.start(); //Thread started
t3.start(); //Thread started
}
}
Thread Priorities:-
1. Every Thread in java has some property. It may be default priority provided be
the JVM orcustomized priority provided by the programmer.
2. The valid range of thread priorities is 1 – 10. Where one is lowest priority and 10
is highest priority.
217 | P a g e
SravyaInfotech Mr. Ratan
3. The default priority of main thread is 5. The priority of child thread is inherited
from the parent.
4. Thread defines the following constants to represent some standard priorities.
5. Thread Scheduler will use priorities while allocating processor the thread which
is havinghighest priority will get chance first and the thread which is having low
priority.
6. If two threads having the same priority then we can’t expect exact execution
order it dependsupon Thread Scheduler.
7. The thread which is having low priority has to wait until completion of high
priority threads.
8. Three constant values for the thread priority.
a. MIN_PRIORITY = 1
b. NORM_PRIORITY = 5
c. MAX_PRIORITY = 10
Thread class defines the following methods to get and set priority of a Thread.
Public final int getPriority()
Public final void setPriority(int priority)
Here ‘priority’indicates a number which is in the allowed range of 1 – 10. Otherwise we will get
Runtime exception saying “IllegalArgumentException”.
Thread priority decide when to switch from one running thread to another this process is called
context switching.
Java.lang.Thread.yield():-
Yield() method causes to pause current executing Thread for giving the chance for
waitingthreads of same priority.
218 | P a g e
SravyaInfotech Mr. Ratan
If there are no waiting threads or all threads are having low priority then the same
thread willcontinue its execution once again.
Syntax:-
Public static native void yield();
Ex:
class MyThread extends Thread
{ public void run()
{
for(int i=0;i<10;i++)
{ Thread.yield();
System.out.println("child thread");
}
}
}
class ThreadYieldDemo
{ public static void main(String[] args)
{ MyThread t1=new MyThread();
t1.start();
for(int i=0;i<10;i++)
{ System.out.println("main thread");
}
}
}
Java.lang.Thread.join(-,-)method:-
Join method allows one thread to wait for the completion of another thread.
o t.join(); ---> here t is a Thread Object whose thread is currently running.
Join() is used to stop the execution of the thread until completion of some other Thread.
if a t1 thread is executed t2.join() at that situation t1 must wait until completion of the t2
thread.
public final void join()throws InterruptedExcetion
Public final void join(long ms)throws InterruptedException
Public final void join(long ms, int ns)throws InterruptedException
Methods of Thread class:-
class MyThread extends Thread
{ public void run()
{ for (int i=0;i<5;i++)
{ try{ Thread.sleep(2000); }
catch(InterruptedException e)
{e.printStackTrace();
}
System.out.println(i);
}
}
};
219 | P a g e
SravyaInfotech Mr. Ratan
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.start();
try
{t1.join(); }
catch (InterruptedException ie)
{ie.printStackTrace();
}
t2.start();
t3.start();
}
};
Java.lang.Thread.Interrupted():-
A thread can interrupt another sleeping or waiting thread. But one thread is able to
interrupted only another sleeping or waiting thread.
To interrupt a thread use Thread class interrupt() method.
Public void interrupt()
Effect of interrupt() method call:-
class MyThread extends Thread
{ public void run()
{ try
{ for (int i=0;i<10;i++ )
{ System.out.println("i am sleeping ");
Thread.sleep(5000);
}
}
catch (InterruptedException ie)
{ System.out.println("i got interupted by interrupt() call");
}
}
};
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t=new MyThread();
t.start();
t.interrupt();
}
};
No effect of interrupt() call:-
class MyThread extends Thread
{ public void run()
{ for (int i=0;i<10;i++ )
220 | P a g e
SravyaInfotech Mr. Ratan
Shutdown Hook:-
Shutdown hook used to perform cleanup activities when JVM shutdown normally or
abnormally.
Clean-up activities like
o Resource release
o Database closing
o Sending alert message
So if you want to execute some code before JVM shutdown use shutdown hook
The JVM will be shutdown in fallowing cases.
a. When you typed ctrl+C
b. When we used System.exit(int)
c. When the system is shutdown ……etc
To add the shutdown hook to JVM use addShutdownHook(obj) method of Runtime Class.
public void addShutdownHook(java.lang.Thread);
To remove the shutdown hook from JVM use removeShutdownHook(obj) method of Runtime
Class.
public boolean removeShutdownHook(java.lang.Thread);
To get the Runtime class object use static factory method getRuntime() & this method present
in Runtime class
Runtime r = Runtime.getRuntime();
Factory method:- one java class method is able to return same class object or different class
object is called factory method.
Example :-
class MyThread extends Thread
{ public void run()
{System.out.println("shoutdown hook");
}
};
221 | P a g e
SravyaInfotech Mr. Ratan
class ThreadDemo
{ public static void main(String[] args)throws InterruptedException
{ MyThread t = new MyThread();
//creating Runtime class Object by using factory method
Runtime r = Runtime.getRuntime();
r.addShutdownHook(t);//adding Thread to JVM hook
for (int i=0;i<10 ;i++)
{System.out.println("main thread is running");
Thread.sleep(3000);
}
}
};
D:\DP>java ThreadDemo
main thread is running
main thread is running
main thread is running
shoutdown hook
while running Main thread press Ctrl+C then hook thread will be executed.
Synchronized :-
Synchronized modifier is the modifier applicable for methods but not for classes andvariables.
If a method or a block declared as synchronized then at a time only one Thread is allowed
tooperate on the given object.
The main advantage of synchronized modifier is we can resolve data inconsistency problems.
But the main disadvantage of synchronized modifier is it increases the waiting time of the
Thread and effects performance of the system.Hence if there is no specific requirement it
isnever recommended to use.
The main purpose of this modifier is to reduce the data inconsistence problems.
Non-synchronized methods
void m1()
{ non-synchronized method any number of threads can access
}
Every thread accessing simultaneously
1) In the above case multiple threads are accessing the same methods hence we are getting data
inconsistency problems. These methods are not thread safe methods.
2) But in this case multiple threads are executing so the performance of the application will be
increased.
Synchronized methods
222 | P a g e
SravyaInfotech Mr. Ratan
223 | P a g e
SravyaInfotech Mr. Ratan
ratan ratan
ratan anu
if method is non-synchronized:- banu
D:\DP>java ThreadDemo anu
banu ratan
synchronized blocks:-
if the application method contains 100 lines but if we want to synchronized only 10 lines of code
use synchronized blocks.
The synchronized block contains less scope compare to method.
If we are writing all the method code inside the synchronized blocks it will work same as the synchronized
method.
Syntax:-
synchronized(object)
{ //code
}
class Heroin
{ public void message(String msg)
{ synchronized(this){
System.out.println("hi "+msg+" "+Thread.currentThread().getName());
try{Thread.sleep(5000);}
catch(InterruptedException e){e.printStackTrace();}
}
System.out.println("hi Sravyasoft");
}
};
class MyThread1 extends Thread
{ Heroin h;
MyThread1(Heroin h)
{this.h=h;
}
public void run()
{ h.message("Anushka");
}
};
class MyThread2 extends Thread
{ Heroin h;
MyThread2(Heroin h)
{this.h=h;
}
public void run()
{ h.message("Ratan");
}
};
class ThreadDemo
{
public static void main(String[] args)
{ Heroin h = new Heroin();
224 | P a g e
SravyaInfotech Mr. Ratan
225 | P a g e
SravyaInfotech Mr. Ratan
Note :- in above example make the setdaemon() is comment mode then the program never terminates
even main thread finished it’s execution.
Nested classes
Declaring the class inside another class is called nested classes. This concept is introduced in
the 1.1 version.
Declaring the methods inside another method is called inner methods java not supporting
inner methods concept.
226 | P a g e
SravyaInfotech Mr. Ratan
Nested classes
227 | P a g e
DurgaSoft Mr. Ratan
For the outer classes the compiler will provide the .class and for the inner classes also the compiler will
provide the .class file.
The .class file name for the inner classes is OuterclassName$innerclasssname.class
Outer class object creation :- Outer o=new Outer();
Inner class object creation :- Outer.Inner i=o.new Inner();
Outer class name :- Outer.class
Inner class name :- Outer$Inner.class
Member inner classes:-
1. If we are declaring any data in outer class then it is automatically available to inner classes.
2. If we are declaring any data in inner class then that data is should not have the scope of the
outer class.
Syntax:-
class Outer
{ class Inner
{
};
};
Object creation syntax:-
Syntax 1:-
OuterClassName o=new OuterClassName();
OuterClassName.InnerClassName oi=OuterObjectreference.new InnterClassName();
Syntax 2:-
OuterclassName.InnerClassName oi=new OuterClass().new InnerClass();
Note:- by using outer class name it is possible to call only outer class peroperties and methods and by
using inner class object we are able to call only inner classes properties and methods.
Example :-
class Outer
{ private int a=100;
class Inner
{ void data()
{ System.out.println("the value is :"+a); }
}
}
class Test
{ public static void main(String[] args)
{ Outer o=new Outer();
Outer.Inner i=o.new Inner();
i.data();
}
};
Example :-
class Outer
{ int i=100;
void m1()
{ //j=j+10;// compilation error
//System.out.println(j);//compilation error
228 | P a g e
DurgaSoft Mr. Ratan
System.out.println("m1 method");
}
class Inner
{ int j=200;
void m2()
{ i=i+10;
System.out.println(i);
}
};
};
class Test
{ public static void main(String[] args)
{ A a=new A();
System.out.println(a.i);
a.m1();
A.B b=a.new B();
System.out.println(b.j);
b.m2();
//b.m1(); compilation error
}
};
Example :-
class Outer
{ private int a=10; private int b=20;
void m1()
{ //m2(); not possible
System.out.println("outer class m1()");
}
class Inner
{ int i=100; int j=200;
void m2()
{ System.out.println("inner class m1()");
System.out.println(a+b);
System.out.println(i+j);
m1();
}
};
};
class Test
{ public static void main(String... ratan)
{ Outer o = new Outer(); o.m1();
Outer.Inner i = o.new Inner(); i.m2();
}
};
Application required this & super keywords:-
class Outer
{ private int a=10; private int b=20;
class Inner
229 | P a g e
DurgaSoft Mr. Ratan
class Outer
{ void m1(){ System.out.println("outer class m1()"); }
class Inner
{ void m1()
{ Outer.this.m1();
System.out.println("inner class m1()");
}
};
};
class Test
{ public static void main(String... ratan)
{ Outer.Inner i = new Outer().new Inner();
i.m1();
}
};
230 | P a g e
DurgaSoft Mr. Ratan
Syntax:-
class Outer
{ void m1()
{ class inner
{ };
}
};
Example:-
class Outer
{ private int a=100;
void m1()
{ class Inner
{
void innerMethod()
{ System.out.println("inner class method");
System.out.println(a);
}
};
Inner i=new Inner();
i.innerMethod();
}
};
class Test
{ public static void main(String[] args)
{ Outer o=new Outer();
o.m1();
}
};
class Outer
{ void m1()
{ class Inner
{ void m1(){System.out.println("inner class m1()");}
};
Inner i = new Inner();
i.m1();
}
public static void main(String[] args)
{ Outer o = new Outer();
o.m1();
}
};
class Outer
{ private int a=100;
void m1()
{ final int b=200;//local variables must be final variables
class Inner
{ void m1()
231 | P a g e
DurgaSoft Mr. Ratan
232 | P a g e
DurgaSoft Mr. Ratan
}
};
class Test
{ public static void main(String[] args)
{ Outer o=new Outer();
o.m1();
}
};
Static inner classes:-
In general in java classes it is not possible to declare any class as a abstract class but is possible to
declare inner class as a static modifier.
Declaring the static class inside the another class is called static inner class.
Static inner classes can access only static variables and static methods it does not access the instace
variables and instance methods.
Syntax:- class Outer
{ static class Inner
{
};
};
class Outer
{ static int a=10;
static int b=20;
static class Inner
{ int c=30;
void m1()
{ System.out.println(a);
System.out.println(b);
System.out.println(c);
}
};
public static void main(String[] args)
{ Outer o=new Outer();
Outer.Inner i=new Outer.Inner();
i.m1();
}
};
class Outer
{ static int a=10;//static variable
static int b=20;//static variable
static class Inner //this inner class able to access only static memebers of outer class
{ void m1(){
System.out.println(a);
System.out.println(b);
}
};
public static void main(String[] args)
{ Outer.Inner i = new Outer.Inner();//it creates object of static inner class
i.m1();
233 | P a g e
DurgaSoft Mr. Ratan
}
};
class Outer
{ static int a=10;//static variable
static int b=20;//static variable
static class Inner //this inner class able to access only static memebers of outer class
{ void m1(){
System.out.println(a);
System.out.println(b);
}
};
public static void main(String[] args)
{ Outer.Inner i = new Outer.Inner();//it creates object of static inner class
i.m1();
}
};
Anonymous inner class:-
1. The name less inner class is called anonymous inner class.
2. it can be used to provide the implementation of normal class or abstract class or interface
Anonymous inner classes for abstract classes:-
it is possible to provide abstract method implementations by taking inner classes.
Ex:- we are able to declare anonymousinner class inside the class.
abstract class Animal
{ abstract void eat();
};
class Test
{ //anonymous inner class
Animal a=new Animal()
{ void eat() { System.out.println("animals eating gross"); }
};
public static void main(String[] args)
{ Test t=new Test();
t.a.eat();
}
}
Ex:- we are able to declare anonymous inner class inside the main method.
abstract class Animal
{ abstract void eat();
};
class Test
{ public static void main(String[] args)
{
Animal a=new Animal()
{ void eat()
{ System.out.println("animals eating gross"); }
};
a.eat();
}
234 | P a g e
DurgaSoft Mr. Ratan
}
Note :- In above example we are taking animal class having eat() method and we are overriding
method but this thing can done by creating subclasses of existing class by using extends keyword
then what is the need of anonymous inner classes.
The answer is creating anonymous inner class simple. And whenever we are inherit few properties
(only method) of superclass instead of extending class use anonymous inner class.
//interface (contains abstract methods)
interface it
{
void m1();
void m2();
;;;;;;;;;;;;
void m100();
}
//adaptor class(contains empty implementation of interface methods)
class X implements it
{
void m1(){}
void m2(){}
;;;;;;;;
void m100(){}
};
//userdefined class extending adaptor class
class Test extends X
{
//all methods are visible here
};
//useing anonymous inner class (override required method)
class Test
{
//anonymous inner class
X x = new X()
{
//override required methods(requied methods are loaded)
void m1(){System.out.println("anonymous inner class");}
};//semicolan mandatory
};
interface It1 //interface
{
void m1(); //by default interface methods are puliv abstract
void m2();
;;;;;;;;;;;
void m100();
}
class X implements It1//adaptor class
{ //it is adaptor class contains empty implementation of all interface methods
public void m1(){} //implementation method must be public
public void m2(){}
235 | P a g e
DurgaSoft Mr. Ratan
;;;;;;;;;;;
public void m100(){}
};
abstract class Test implements It1
{
//must provide the implementation of 100 methods
};
//approach-1 it is possible to extends the class and override required method
class Test1 extends X
{
//override the required methods
public void m1(){System.out.println("m1 method");}
};
//approach-2 without extending class it is possible to create the object directly and override required
method
class Ratan
{
X x= new X()//this is anonymous inner class
{
public void m1(){System.out.println("anonymous inner class");} }; //semicoln
mandatory
public static void main(String[] args)
{ Ratan r = new Ratan();
r.x.m1();
}
};
//predefined class contains 2-methods
class A
{
void m1(){System.out.println("A m1 method ");}
void m2(){System.out.println("A m2 method ");}
};
//approach-1 extends the then override required methods
class Test extends A
{
void m1(){System.out.println("Test extends A --> m1 method ");}
public static void main(String[] args)
{
Test t = new Test(); t.m1();
}
};
//approach-2 don't extends the class declare anonymous inner class then override the required methods
class Ratan
{
A a = new A()
{
void m1(){System.out.println("Anonumous inner class m1 method ");}
};//semicolan mandatory
236 | P a g e
DurgaSoft Mr. Ratan
ENUMARATION
1. This concept is introduced in 1.5 version
2. enumeration is used to declare group of named constant s.
3. we are declaring the enum by using enum keyword. For the enums the compiler will generate
.classess
237 | P a g e
DurgaSoft Mr. Ratan
4.enum is a keyword and Enum is a class and every enum is directl child class of java.lang.Enumso it is
not possible to inherit the some other class. Hence for the enum inheritance concept is not applicable
5. by default enum constants are public static final
1. inside the enum it is possible to declare constructors. That constructors will be ececuted for each
and every constant. If we are declaring 5 constants then 5 times constructor will be executed.
2. Inside the enum if we are declaring only constants the semicolon is optional.
3. Inside the enum if we are declaring group of constants and constructors at that situation the group
of constants must be first line of the enum must ends with semicolon.
class Test
{ public static void main(String... ratan)
Ex :-Semicolan optinal { Heroin s=Heroin.samantha;
enum Heroin }
{ samantha,tara,anu,ubanu };
}
238 | P a g e
DurgaSoft Mr. Ratan
}
}
class Test
Ex:- semicolon mandatory { public static void main(String... ratan)
enum Heroin { Heroin s=Heroin.samantha;
{ samantha,tara,anu,ubanu; }
Heroin() };
{ System.out.println("ratan sir");
Ex:- constructors with arguments
enum Heroin
{ ANUSHKA,UBANU(10),DEEPIKA(10,20);
Heroin() { System.out.println("ratan"); }
Heroin(int a) { System.out.println("raghava"); }
Heroin(int a,int b) { System.out.println("sanki"); }
}
class Test
{ public static void main(String[] arhss)
{ Heroin[] h = Heroin.values();
for (Heroin h1 : h)
{ System.out.println(h1+"----"+h1.ordinal());
}
}
};
Ex:-inside the enum it is possible to provide main method.
enum Heroin
{ samantha,tara,anu;
public static void main(String[] args)
{ System.out.println("enum main method");
}
}
class Test
{ public static void main(String... ratan)
{Heroin[] s=Heroin.values();
for (Heroin s1:s)
{ System.out.println(s1+"--------"+s1.ordinal());
}
}
};
Ex:- inside the enums it is possible to declare group of constants and constructors and main method
enum Heroin
{
//group of constants
ANUSHKA,UBANU,DEEPIKA;
239 | P a g e
Durgasoft Mr. Ratan
//contructor
Heroin()
{ System.out.println("ratan");
}
//enum main method
public static void main(String[] args)
{
System.out.println("enum m ain method");
}//end main
}//end enum
class Test
{ public static void main(String[] arhss)
{ //accessing enum constants
Heroin[] h = Heroin.values();
for (Heroin h1 : h)
{
System.out.println(h1+"----"+h1.ordinal());
}
}//end main
};//end class
240 | P a g e
Durgasoft Mr. Ratan
Collectionsframework (java.util)
Collection frame contains group of classes and interfaces by using these classes & interfaces we
are representing group of objects as a single entity.
Collection is sometimes called a container. And it is object that groups multiple elements into a
single unit.
Collections are used to store, retrieve ,manipulate data.
Note :- The root interface of Collection framework is Collection it contains 15 methods so all
implementation classes are able to use that methods.
public abstract int size();
public abstract boolean isEmpty();
public abstract boolean contains(java.lang.Object);
public abstract java/util/Iterator<E> iterator();
public abstract java.lang.Object[] toArray();
public abstract <T extends java/lang/Object> T[] toArray(T[]);
public abstract boolean add(E);
public abstract boolean remove(java.lang.Object);
241 | P a g e
Durgasoft Mr. Ratan
extends
Stack(c)
1.0 version
242 | P a g e
Durgasoft Mr. Ratan
I --------------Interface
c--------------class
Legcy class:- The java classes which are introduced in 1.0 version are called legacy classes.
Ex :- Vector , Stack , HashTable…….etc
Java.util.ArrayList:-
ArrayList is implementing List interface it widely used class in projects because it is providing
functionality and flexibility
To check parent class and interface use below command.
D:\ratan>javap java.util.ArrayList
public class java.util.ArrayList<E>
extends java.util.AbstractList<E>
implements java.util.List<E>,
java.util.RandomAccess,
java.lang.Cloneable,
java.io.Serializable
ArrayList Characteristics:-
1) ArrayList Introduced in 1.2 version.
2) ArrayList stores Heterogeneous objects(different types).
3) Inside ArrayList we can insert Null objects.
4) ArrayList preserved Insertion order it means whatever the order we inserted the data in the same
way output is printed.
a. Input -e1 e2 e3 output -e1 e2 e3 insertion order is preserved
b. Input --e1 e2 e3 output --e1 e3 e2 insertion order is not- preserved
5) ArrayList methods are non-synchronized methods.
6) Duplicate objects are allowed.
7) The under laying data structure is growable array.
8) By using cursor we are able to retrieve the data from ArrayList : Iterator , ListIterator
243 | P a g e
Durgasoft Mr. Ratan
ArrayList Capacity:-
import java.util.*;
import java.lang.reflect.Field;
class Test
{ public static void main(String[] args)throws Exception
{ ArrayList<Integer> al = new ArrayList<Integer>(5);
for (int i=0;i<10 ;i++)
{ al.add(i);
System.out.println("size="+al.size()+" capacity="+getcapacity(al));
}
}
static int getcapacity(ArrayList l)throws Exception
{ Field f = ArrayList.class.getDeclaredField("elementData");
f.setAccessible(true);
return ((Object[])f.get(l)).length;
}
}
D:\>java Test
size=1 capacity=5
size=2 capacity=5
size=3 capacity=5
size=4 capacity=5
size=5 capacity=5
size=6 capacity=8
size=7 capacity=8
size=8 capacity=8
size=9 capacity=13
size=10 capacity=13
Example :-Collections vs Autoboxing
upto 1.4 version by using wrapper classes, create objects then add that objects in ArrayList.
import java.util.ArrayList;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
Integer i = new Integer(10); //creation of Integer Object
Character ch = new Character('c'); //creation of Character Object
Double d = new Double(10.5); //creation of Double Object
//adding wrapper objects into ArrayList
al.add(i);
al.add(ch);
al.add(d);
System.out.println(al);
244 | P a g e
Durgasoft Mr. Ratan
}
But from 1.5 version onwards autoboxing concept is introduced so add the primitive value directly that is
automatically converted into wrapper objects format.
import java.util.ArrayList;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(10); //primitive int value --->Integer Object conversion //AutoBoxing
al.add('a'); //primitive char value --->Integer Object conversion //AutoBoxing
al.add(10.5); //primitive double value --->Integer Object conversion //AutoBoxing
System.out.println(al);
}
}
In above example when we are adding primitive char value al.add(‘c’) in ArrayList that value is
automatically converted Character object format because ArrayList is able to store objects that
is called AutoBoxing.
When we print the ArrayList data for every object internally it is calling toString() method.
Example :- in Collection framework when we remove the data by using numeric value that is by
default treated as a index value.
ArrayList al = new ArrayList();
al.add(10);
al.add("ratan");
al.add('a');
245 | P a g e
Durgasoft Mr. Ratan
System.out.println(al);
In above example if u want remove 10object by using object name then we are using below code.
al.remove(10);
But whenever we are writing above code then JVM treats that 10 is index value hence it is generating
exception java.lang.IndexOutOfBoundsException: Index: 10, Size: 3
To overcome above limitation if we want remove 10 Integer object then use below code.
ArrayList al = new ArrayList();
Integer i = new Integer(10);
al.add(i);
al.remove(i);
System.out.println(al);
import java.util.ArrayList;
class Test
{ public static void main(String[] args)
{ Emp e1 = new Emp(111,"ratan");
Student s1 = new Student(222,"xxx");
ArrayList al = new ArrayList();
al.add(10); //toString() --->it execute Integer class toString()
al.add('a'); //toString() --->it execute Character class toString()
al.add(e1); //toString() --->it executes Object class toString()
al.add(s1); //toString() --->it executes Object class toString()
System.out.println(al.toString());//[10, a, Emp@d70d7a, Student@b5f53a]
for (Object o : al)
{ if (o instanceof Integer)
System.out.println(o.toString());
if (o instanceof Character)
System.out.println(o.toString());
if (o instanceof Emp){
Emp e = (Emp)o;
System.out.println(e.eid+"---"+e.ename);
}
if (o instanceof Student){
Student s = (Student)o;
System.out.println(s.sid+"---"+s.sname);
246 | P a g e
Durgasoft Mr. Ratan
}
}
}
}
247 | P a g e
Durgasoft Mr. Ratan
Note :-
in java it is recommended to use generic version of collections class to store specified type of data.
Syntax:-
ArrayList<type-name> al = new ArrayList<type-name>();
Examples:-
ArrayList<Integer> al = new ArrayList<Integer>(); //store only Integer objects
ArrayList<String> al = new ArrayList<String>(); //store only String objects
ArrayList<Student> al = new ArrayList<Student>(); //store only Student objects
ArrayList<product> al = new ArrayList<product>(); //store only produce objects
248 | P a g e
Durgasoft Mr. Ratan
al.add('a');
al.add(10.4); 4) If we are using generic version compiler
al.add(true); won’t generate worning messages.
System.out.println(al);
}
} Example :- generic version of ArrayList
Generic version of ArrayList(type safety) holding only Integer data.
1) Generic version is able to hold specified import java.util.*;
type of data hence it is a type safe. class Test
ArrayList<tye-name> al = new ArrayList<type-name>( ); { public static void main(String[] args)
ArrayList<Integer> al = new ArrayList<Integer>(); {ArrayList<Integer> al = new ArrayList<Integer>();
al.add(10); al.add(10);
al.add(20); al.add(20);
al.add(“ratan”);//compilation error al.add(30);
System.out.println(al); al.add(40);
System.out.println(al);
2) Type checking is not required because it }
contains only one type of data. }
249 | P a g e
Durgasoft Mr. Ratan
a1.add("anu");
a1.add("Sravya");
a1.add("yadhu");
ArrayList<String> a2 = new ArrayList<String>(a1.subList(1,3));
System.out.println(a2); //[anu,Sravya]
ArrayList<String> a3 = new ArrayList<String>(a1.subList(1,a1.size()));
System.out.println(a3); //[anu,Sravya,yadhu]
//java.lang.IndexOutOfBoundsException: toIndex = 7
//ArrayList<String> a4 = new ArrayList<String>(a1.subList(1,7));
250 | P a g e
Durgasoft Mr. Ratan
251 | P a g e
Durgasoft Mr. Ratan
Example :-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(new Emp(111,"ratan"));
al.add(new Student(1,"xxx"));
al.add("ratan");
//converison of ArrayList to array
Object[] o = al.toArray();
for (Object oo :o)
{ if (oo instanceof Emp)
{ Emp e = (Emp)oo;
System.out.println(e.eid+"---"+e.ename);
}
if (oo instanceof Student)
{ Student s = (Student)oo;
System.out.println(s.sid+"---"+s.sname);
}
if (oo instanceof String)
{ System.out.println(oo.toString());
}
}
}
}
252 | P a g e
Durgasoft Mr. Ratan
import java.util.*;
class Test
{ public static void main(String[] args)
253 | P a g e
Durgasoft Mr. Ratan
}
}
Comparable vs Comparator :-
Note :- it is possible to sort String and all wrapper objects because these objects are
implementing Cloneable interface.
If we want to sort user defined class Emp based on eid or ename then your class must
implements Comparable interface.
Comparable present in java.lang package it contains only one method compareTo(obj)
public abstract int compareTo(T);
If your class is implementing Comparable interface then that objects are sorted
automatically by using Collections.sort()And the objects are sorted by using
compareTo() method of that class.
By using comparable it is possible to sort the objects by using only one instance
variable either eid or ename.
Emp.java:-
class Emp implements Comparable
{ int eid;
String ename;
254 | P a g e
Durgasoft Mr. Ratan
Another format:-
class Emp implements Comparable<Emp>
{ ***********
public int compareTo(Emp e)
{ ***********
}
}
Test.java:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(new Emp(333,"ratan"));
al.add(new Emp(222,"anu"));
al.add(new Emp(111,"Sravya"));
Collections.sort(al);
Iterator itr = al.iterator();
while (itr.hasNext())
{ Emp e = (Emp)itr.next();
System.out.println(e.eid+"---"+e.ename);
}
255 | P a g e
Durgasoft Mr. Ratan
Java.utilComparator :-
The class whose objects are stored do not implements this interface some third party
class can also implements this interface.
Comparable present in java.langpackage but Comparator present in java.util package.
Comparator interface contains two methods,
public interface java.util.Comparator<T> {
public abstract int compare(T, T);
public abstract boolean equals(java.lang.Object);
}
Emp.java:-
class Emp
{ int eid;
String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
}
EidComp.java:-
import java.util.Comparator;
class EidComp implements Comparator
{ public int compare(Object o1,Object o2)
{ Emp e1 = (Emp)o1;
Emp e2 = (Emp)o2;
if (e1.eid==e2.eid)
{ return 0; }
else if (e1.eid>e2.eid)
{ return 1; }
else
{ return -1; }
}
}
EnameComp.java:-
import java.util.Comparator;
class EnameComp implements Comparator
{ public int compare(Object o1,Object o2)
{ Emp e1 = (Emp)o1;
Emp e2 = (Emp)o2;
return (e1.ename).compareTo(e2.ename);
//return -(e1.ename).compareTo(e2.ename); //print data descending order
256 | P a g e
Durgasoft Mr. Ratan
}
}
Test.java:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<Emp> al = new ArrayList<Emp>();
al.add(new Emp(333,"ratan"));
al.add(new Emp(222,"anu"));
al.add(new Emp(111,"Sravya"));
al.add(new Emp(444,"xxx"));
System.out.println("sorting by eid");
Collections.sort(al,new EidComp());
Iterator<Emp> itr = al.iterator();
while (itr.hasNext())
{ Emp e = itr.next();
System.out.println(e.eid+"---"+e.ename);
}
System.out.println("sorting by ename");
Collections.sort(al,new EnameComp());
Iterator<Emp> itr1 = al.iterator();
while (itr1.hasNext())
{ Emp e = itr1.next();
System.out.println(e.eid+"---"+e.ename);
}
}
}
D:\vikram>java Test
sorting by eid
111---Sravya
222---anu
333---ratan
444---xxx
sorting by ename
222---anu
111---Sravya
333---ratan
444---xxx
257 | P a g e
Durgasoft Mr. Ratan
258 | P a g e
Durgasoft Mr. Ratan
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("10");
al.add("20");
al.add("30");
Vector<String> v = new Vector<String>();
v.add("ten");
v.add("twenty");
//copy data from vector to ArrayList
Collections.copy(al,v);
System.out.println(al);
}
}
D:\vikram>java Test
[ten, twenty, 30]
Enumaration:-0
1. Enumeration cursor introduced in 1.0 version hence it is called legacy cursor.
259 | P a g e
Durgasoft Mr. Ratan
2. Enumeration is a legacy cursor it is used to retrieve the objects form only legacy classes (vector,
Stack, HashTable…)hence it is not a universal cursor.
3. to retrieve Object from collection classes Enumeration Object uses two methods.
public abstract boolean hasMoreElements();
This method is used to check whether the collection class contains Objects or not, if
collection class contains objects return true otherwise false.
public abstract E nextElement();
This method used to retrieve the objects from collection classes.
6. By using this cursor it is possible to read the data only, it not possible to update the data an not
possible to remove the data.
7. By using this cursor we are able to retrieve the data only in forward direction.
Iterator:-
1) Iterator cursor introduced in 1.2 versions.
4) The Iterator object uses three methods to retrieve the objects from collections classes.
260 | P a g e
Durgasoft Mr. Ratan
6) By using Iterator cursor we are able to perform read and remove operations but it is not
possible to perform update operation.
7) By using Iterator we are able to read the data only in forward direction.
Property
1. Purpose
261 | P a g e
Durgasoft Mr. Ratan
4. How to get the object 3) It is used to retrieve the data from only
legacy classes like vector,Stack…etc
Enumeration
LIstIterator:-
262 | P a g e
Durgasoft Mr. Ratan
263 | P a g e
Durgasoft Mr. Ratan
Implementation
class of ListIterator
Enumeration interface.
1..0 version
Iterator
Synchronized Collection Methods of Collections class:-
Collections.synchronizedSortedSet(SortedSet<T> s)
Collections.synchronizedSortedMap(SortedMap<K,V> m)
Collections.synchronizedSet(Set<T> s)
Collections.synchronizedCollection(Collection<T> c)
Collections.synchronizedList(List<T> list)
Collections.synchronizedMap(Map<K,V> m)
264 | P a g e
Durgasoft Mr. Ratan
import java.util.*;
class Test
{ public static void main(String[] args)
{ Vector v = new Vector();
v.addElement(10);
v.addElement(20);
v.addElement(30);
//it returns implementation class object of Enumeration interface
Enumeration e = v.elements();
System.out.println(e.getClass().getName());
Example application:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ //ArrayList able to store only String Objects
ArrayList<String> al =new ArrayList<String>();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add(null);
//1st appraoch to print Collection class elements (by using for-each loop)
for (String a : al)
{ System.out.println(a); }
265 | P a g e
Durgasoft Mr. Ratan
while (itr1.hasNext())
{ String str =(String)itr1.next();//type casting required because normal version
System.out.println(str);
}
Iterator<String> itr2 = al.iterator();//generic version of Iterator
while (itr2.hasNext())
{ String str =itr2.next();//type castingnot required because generic version
System.out.println(str);
}
//3rd approach to print objects by using get() method
int size = al.size();
for (int i=0;i<size;i++)
{ System.out.println(al.get(i));
}
}
}
Example:-
import java.util.*;
class Emp
{ //instance variables
int eid;
String ename;
Emp(int eid ,String ename) //local variables
{ //conversion of local variables to instance variables
this.eid = eid;
this.ename = ename;
}
public static void main(String[] args)
{ Emp main1 = new Emp(111,"ratan");
Emp main2 = new Emp(222,"Sravya");
Emp main3 = new Emp(333,"aruna");
Emp sub1 = new Emp(444,"anu");
Emp sub2 = new Emp(555,"banu");
266 | P a g e
Durgasoft Mr. Ratan
al1.add(main3);
}
System.out.println("printing objects in backword direction");
while (lstr.hasPrevious())
{ Emp e1 = lstr.previous();
System.out.println(e1.eid+" "+e1.ename);
}
}
}
267 | P a g e
Durgasoft Mr. Ratan
268 | P a g e
Durgasoft Mr. Ratan
l.add("B");
l.add("C");
l.add("D");
l.add("E");
l.addLast("Z");//it add object in last position
l.addFirst("A");//it add object in first position
l.add(1,"A1");//add the Object spcified index
System.out.println("original content:-"+l);
l.removeFirst(); //remove first Object
l.removeLast(); //remove last t Object
System.out.println("after deletion first & last:-"+l);
l.remove("E"); //remove specified Object
l.remove(2); //remove the object of specified index
System.out.println("after deletion :-"+l);//A1 B D
String val = l.get(0); //get method used to get the element
l.set(2,val+"cahged");//set method used to replacement
System.out.println("after seting:-"+l);
}
};
D:\>java Test
original content:-[A, A1, B, C, D, E, Z]
after deletion first & last:-[A1, B, C, D, E]
after deletion :-[A1, B, D]
after seting:-[A1, B, A1cahged]
Vector :-
Case:-1
The default initial capacity of the Vector is 10 once it reaches its maximum capacity it
means when we trying to insert 11 element that capacity will become double[20].
Vector v = new Vector();
System.out.println(v.capacity()); //10
v.add("ratan");
System.out.println(v.capacity()); //10
System.out.println(v.size()); //1
Case 2:-
269 | P a g e
Durgasoft Mr. Ratan
270 | P a g e
Durgasoft Mr. Ratan
System.out.println(v);
v.addAll(al); //adding ArrayList data into Vector
System.out.println(v);
v.removeAll(al); //it removes all objects of al
System.out.println(v);
System.out.println(v.firstElement()); //to retrieve first element
System.out.println(v.lastElement()); //to retrieve last element
}
}
D:\vikram>java Test
[ratan, aruna, Sravya, ccc]
4
[ratan, xxx, ccc]
[ratan, xxx, ccc, no1, no2]
[ratan, xxx, ccc]
ratan
ccc
Example :-
//product.java
class Product
{ //instance variables
int pid;
String pname;
double pcost;
Product(int pid,String pname,double pcost) //local variables
{ //conversion [passing local variable values to instance variable]
this.pid = pid;
this.pname = pname;
this.pcost = pcost;
}
};
//ArrayListDemo.java
import java.util.*;
class ArrayListDemo
{ public static void main(String[] args)
{ Product p1 = new Product(111,"pen",1300);
Product p2 = new Product(222,"laptop",13000);
Product p3 = new Product(333,"bag",1000);
Product p4 = new Product(444,"java",5000);
Product p5 = new Product(555,".net",4000);
Vector<Product> v = new Vector<Product>();
v.addElement(p1);
v.addElement(p2);
v.addElement(p3);
System.out.println("***Enumeration cursor only read operations***");
271 | P a g e
Durgasoft Mr. Ratan
Enumeration<Product> e = v.elements();
while (e.hasMoreElements())
{ Product p = e.nextElement();
System.out.println(p.pid+"----"+p.pname+"----"+p.pcost);
}
System.out.println("***Iterator cursor both read & remove operations***");
Iterator<Product> itr = v.iterator();
while (itr.hasNext())
{ Product pp = itr.next();
if ((pp.pname).equals("pen"))
itr.remove(); //pen object removed
}
272 | P a g e
Durgasoft Mr. Ratan
System.out.println(v);
}
}
Stack:- (legacy class introduced in 1.0 version)
1) It is a child class of vector
2) Introduce in 1.0 v legacy class
3) It is designed for LIFO(last in fist order )
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ Stack<String> s = new Stack<String>();
s.push("ratan"); //insert the data top of the stack
s.push("anu"); //insert the data top of the stack
s.push("Sravya");
System.out.println(s);
System.out.println(s.search("Sravya")); //1 last added object will become first
System.out.println(s.size());
System.out.println(s.peek()); //to return last element of the Stack
s.pop(); //remove the data top of the stack
System.out.println(s);
System.out.println(s.isEmpty());
s.clear();
System.out.println(s.isEmpty());
}
}
Example :-
import java.util.*;
class Test
{ public static void main(String[] args)
{ String reverse="";
Scanner s = new Scanner(System.in);
System.out.println("enter input string to check palendrome or not");
String str = s.nextLine();
Stack stack = new Stack();
273 | P a g e
Durgasoft Mr. Ratan
5) by using ListIterator we are able to read & remove & update the data.
1. It is applicable for only list type of objects.
2. By using this it is possible to read the data upate the data and delete data also.
3. By using listIterator() method we are getting LIstIterator object
EmpBean.java:-
public class EmpBean implements Comparable<EmpBean>
{ private int eid;
private String ename;
public void setEid(int eid)
{ this.eid=eid;
}
public void setEname(String ename)
{ this.ename=ename;
}
public int getEid()
{return eid;
}
public String getEname()
{return ename;
}
public int compareTo(EmpBean o)
{ if (eid==o.eid)
{return 0;
}
if (eid>o.eid)
{return 1;
}
else{return -1;}
}
};
274 | P a g e
Durgasoft Mr. Ratan
collection(i) 1.2 v
extends
1.2v
Set(i)
implements implements
extends extends
1.4 v
LinkedHashSet(c) NavigableSet(i) 1.6v
implements
TreeSet(c 1.2v
)
HashSet:-
1) Introduced in 1.2 v.
2) Duplicate objects are not allowed if we are trying to insert duplicate values then we won't get
any compilation errors an won't get any Execution errors simply add method return old value.
3) Null insertion is possible but if we are inserting more than one null it return only one null value.
4) Heterogeneous objects are allowed.
5) The under laying data structure is HashTable.
6) It is not maintain any order the elements are return in any random order .[Insertion order is not
preserved].
7) Methods are non-synchronized.
8) cursor : Iterator
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ //HashSet object creation
HashSet<String> h = new HashSet<String>();
h.add("A");
h.add("B");
h.add("C");
h.add("D");
h.add("D");
//creation of Iterator Object
Iterator<String> itr = h.iterator();
while (itr.hasNext())
{ String str = itr.next();
System.out.println(str);
275 | P a g e
Durgasoft Mr. Ratan
}
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
{ HashSet<String> h = new HashSet<String>();
h.add("ratan");
h.add("anu");
h.add("Sravya");
HashSet<String> hsub = new HashSet<String>();
hsub.add("no1");
hsub.add("no2");
hsub.addAll(h);
System.out.println(hsub.contains("anu"));
hsub.remove("anu");
System.out.println(hsub.containsAll(h));
System.out.println(hsub);
hsub.removeAll(h);
System.out.println(hsub);
hsub.retainAll(h);
System.out.println(hsub);
}
}
LinkedHashSet:-
1. Introduced in 1.4 version and It is a child class of HashSet.
2. Duplicate objects are not allowed if we are trying to insert duplicate values then we won’t get
any compilation errors an won’t get any Execution errors simply add method return false.
3. Null insertion is possible.
4. Heterogeneous objects are allowed
5. The under laying data structure is LinkedList & hashTable.
6. Insertion order is preserved.
7. Methods are non-synchronized.
8. Cursors :- Iterator.
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ Set<String> h = new LinkedHashSet<String>();
h.add("A");
h.add("B");
h.add("C");
h.add("D");
h.add("D");
//retrieving objects by using Iterator cursor
Iterator<String> itr = h.iterator();
276 | P a g e
Durgasoft Mr. Ratan
while (itr.hasNext())
{String str = itr.next();
System.out.println(str);
}
//retrieving objects by using Enumeration cursor
Enumeration<String> e = Collections.enumeration(h);
while (e.hasMoreElements())
{ System.out.println(e.nextElement());
}
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
{ HashSet<String> h = new HashSet<String>();
h.add("ratan");
h.add("anu");
h.add("Sravya");
//passing data from HashSet to LinkedHashSet
LinkedHashSet<String> lh = new LinkedHashSet<String>(h);
//lh.addAll(h);
lh.add("xxx");
lh.add("yyy");
System.out.println(lh);
//passing data from LinkedHashSet to HashSet
HashSet<String> hh = new HashSet<String>(lh);
//hh.addAll(lh);
hh.add("zzz");
System.out.println(hh);
}
}
TreeSet:-
1. TreeSet is same as HashSet but TreeSet sorts the elements is ascending order but HashSet does
not maintain any order.
2. The underlying data Structure is BalencedTree.
3. Insertion order is not preserved it is based some sorting order.
4. Heterogeneous data is not allowed.
5. Duplicate objects are not allowed
6. Null insertion is possible only once.
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeSet<String> t = new TreeSet<String>();
t.add("ratan");
t.add("anu");
t.add("Sravya");
System.out.println(t);
277 | P a g e
Durgasoft Mr. Ratan
import java.util.*;
class Fruit
{ public static void main(String[] args)
{ TreeSet<String> t = new TreeSet<String>(new MyComp());
t.add("orange");
t.add("bananna");
t.add("apple");
System.out.println(t);
}
}
class MyComp implements Comparator<String>
{ public int compare(String s1,String s2)
{
return s1.compareTo(s2);//[apple, bananna, orange]
//return -s1.compareTo(s2);//[orange, bananna, apple]
}
};
278 | P a g e
Durgasoft Mr. Ratan
class Test
{ public static void main(String[] args)
{ String[] str={"ratan","anu","Sravya","anu"};
//converion of String[] to List
List<String> l = Arrays.asList(str);
//conversion of List to Set [it eliminates duplicates]
TreeSet<String> t = new TreeSet<String>(l);
System.out.println(t);
}
}
Example :-
import java.util.Iterator;
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
// creating a TreeSet Object
TreeSet <Integer>treeadd = new TreeSet<Integer>();
// adding object in the tree set
treeadd.add(10);
treeadd.add(30);
treeadd.add(70);
treeadd.add(20);
// create iterator Object
Iterator iterator;
iterator = treeadd.iterator();
import java.util.*;
279 | P a g e
Durgasoft Mr. Ratan
class Test
{ public static void main(String[] args)
{ //creating TreeSet object
TreeSet t=new TreeSet();
//adding object in TreeSet
t.add(50); t.add(20); t.add(40);
t.add(10); t.add(30);
System.out.println(t);
SortedSet s1=t.headSet(50);
System.out.println(s1); //[10,20,30,40]
SortedSet s2=t.tailSet(30);
System.out.println(s2); //[30,40,50]
SortedSet s3=t.subSet(20,50);
System.out.println(s3); //[20,30,40]
System.out.println("last element="+t.last());
System.out.println("first element="+t.first());
System.out.println("lower element="+t.lower(50));
System.out.println("higher element="+t.higher(20));
System.out.println("print & remove first element="+t.pollFirst());
System.out.println("print & remove last element="+t.pollLast());
System.out.println("final elements="+t);
System.out.println("TreeSet size="+t.size());
System.out.println("TreeSet size="+t.remove(10));
System.out.println("TreeSet size="+t.remove(30));
}
}
D:\morn11>java Test
[10, 20, 30, 40, 50]
[10, 20, 30, 40]
[30, 40, 50]
[20, 30, 40]
last element=50
first element=10
lower element=40
igher element=30
print & remove first element=10
print & remove last element=50
final elements=[20, 30, 40]
TreeSet size=3
TreeSet size=false
TreeSet size=true
280 | P a g e
Durgasoft Mr. Ratan
Map interface:-
1.2v
Map(i)
implements implements
extends extends
1.4 v
LinkedHashMap(c NavigableMap(i) 1.6v
)
implements
TreeMap(C) 1.2v
Map:-
1. Map is a child interface of collection.
2. Up to know we are working with single object and single value where as in the map collections
we are working with two objects and two elements.
3. The main purpose of the collection is to compare the key value pairs and to perform necessary
operation.
4. The key and value pairs we can call it as map Entry.
5. Both keys and values are objects only.
6. In entire collection keys can’t be duplicated but values can be duplicate.
HashMap:-
1) interdicted in 1.2 version
2) Heterogeneous data allowed.
3) Underlying data Structure is HashTable.
4) Duplicate keys are not allowed but values can be duplicated.
5) Insertion order is not preserved.
6) Null is allowed for key(only once)and allows for values any number of times.
7) Every method is non-synchronized so multiple Threads are operate at a time hence permanence
is high.
8) cursor :- Iterator.
Example :-
import java.util.*;
class Test
{ public static void main(String[] args)
{ //creation of HashMap Object
HashMap h = newHashMap();
h.put("ratan",111); //h.put(key,value);
h.put("anu",111);
281 | P a g e
Durgasoft Mr. Ratan
h.put("banu",111);
Set s1=h.keySet(); //used to get all keys
System.out.println("all keys:--->"+s1);
Collection c = h.values(); //used to get all values
System.out.println("all values--->"+c);
Set ss = h.enrySet(); //it returns all entryes nathing but [key,value]
System.out.println("all entries--->"+ss);
//get the Iterator Object
Iterator itr = ss.iterator();
while (itr.hasNext())
{
//next() method retrun first entry to represent that entery do typeCasting
Map.Entry m= (Map.Entry)itr.next();
System.out.println(m.getKey()+"----"+m.getValue()); //printing key and value
}
}
};
LinkedHashMap:-
1) interdicted in 1.4 version
2) Heterogeneous data allowed.
3) Underlying data Structure is HashTable & linkedlist.
4) Duplicate keys are not allowed but values can be duplicated.
5) Insertion order is preserved.
6) Null is allowed for key(only once)and allows for values any number of times.
7) Every method is non-synchronized so multiple Threads are operate at a time hence permanence
is high.
8) cursor :- Iterator
Emp.java: //Student.java
class Emp class Student
{ int eid; { //instance variables
String ename; int sid;
Emp(int eid,String ename) String sname;
{this.eid=eid; Student(int sid,String sname)//local
this.ename=ename; variables
} { this.sname=sname; this.sid=sid;
} }
}
Test.java:-
import java.util.*;
class Test
{ public static void main(String[] args)
{
//creates LinkedList object with generic version
LinkedHashMap<Emp,Student> h = new LinkedHashMap<Emp,Student>();
h.put(new Emp(111,"ratan"), new Student(1,"budha"));
282 | P a g e
Durgasoft Mr. Ratan
import java.util.*;
class Test
{ public static void main(String[] args)
{ HashMap h = new LinkedHashMap();
h.put(111,"ratan");
h.put(222,"anu");
h.put(333,"sravya");
System.out.println(h);
Set s1 = h.keySet();
System.out.println(s1);
Collection c = h.values();
System.out.println(c);
Set s2 = h.entrySet();
Iterator itr = s2.iterator();
while (itr.hasNext())
{ Map.Entry m = (Map.Entry)itr.next();
System.out.println(m.getKey()+"---"+m.getValue());
}
}
}
HashTable:-
1. Introduced in the 1.0 version it’s a legacy class.
2. Every method is synchronized hence only one thread is allowed to access it is a Thread safe but
performance is decreased.
283 | P a g e
Durgasoft Mr. Ratan
3. Null insertion is not possible if we are trying to insert null values we are getting
NullPointerException.
h.put(null,"ratan");
h.put("4",null);
Ex:-
import java.util.Hashtable;
import java.util.Collection;
import java.util.Set;
class Test
{ public static void main(String[] args)
{ Hashtable<String,String> h = new Hashtable<String,String>();
//adding data in HashTable
h.put("1","one");
h.put("2","two");
h.put("3","three");
System.out.println(h);
System.out.println(h.get("1"));//one
System.out.println(h.isEmpty());
h.remove("3");
System.out.println(h.containsKey("1"));
System.out.println(h.containsKey("3"));
System.out.println(h.containsValue("one"));
System.out.println(h.size());
//to get all values objects
Collection<String> c = h.values();
for (String i : c)
{ System.out.println(i);
}
//to get all key objects
Set<String> s = h.keySet();
for (String ss : s)
{ System.out.println(ss);
}
}
}
Example :-
We are able to add one class data into another class in two ways
1) Passing one class reference variable to another class
Hashtable h = new Hashtable();
HashMap<String,String> h1 = new HashMap<String,String>(h);
2) By using putAll() method
h1.putAll(h);
import java.util.Hashtable;
import java.util.*;
284 | P a g e
Durgasoft Mr. Ratan
class Test
{ public static void main(String[] args)
{ Hashtable<String,String> h = new Hashtable<String,String>();
h.put("1","one");
h.put("2","two");
h.put("3","three");
//passing Hashtable data into HashMap
HashMap<String,String> h1 = new HashMap<String,String>(h);
//h1.putAll(h);
h1.put("hm","ratan");
System.out.println(h1);
//passing HashMap data into LinkedHashMap
LinkedHashMap<String,String> lhm = new LinkedHashMap<String,String>(h1);
//lhm.putAll(h1);
lhm.put("lhm","anu");
System.out.println(lhm);
}
}
TreeMap:-
Example-1:-
import java.util.TreeMap;
class Test
{ public static void main(String[] args)
{ TreeMap<String,String> tmain = new TreeMap<String,String>();
tmain.put("ratan","no1");
tmain.put("anu","no2");
285 | P a g e
Durgasoft Mr. Ratan
tsub.put("y","no4");
System.out.println(tsub);
if (tmain.containsKey("ratan"))
{System.out.println("ratan is great");
}
if (tsub.containsValue("no1"))
{System.out.println("no1 ratan only");
}
//printing all the keys
Set<String> s = tsub.keySet();
for (String ss : s)
{ System.out.println(ss);
}
//printing all the values
Collection<String> s1 = tsub.values();
for (String ss1 : s1)
{ System.out.println(ss1);
}
Set<Entry<String,String>> s2 = tsub.entrySet();
for (Entry<String,String> ss2 : s2)
{ System.out.println(ss2);
}
tsub.clear();
System.out.println(tsub);
}
}
Java.util.Properties:-
Abc.properties :-
username = system
password = manager
driver = oracle.jdbc.driver.OracleDriver
trainer = Ratan
Test.java:-
import java.util.*;
import java.io.*;
class Test
{ public static void main(String[] args) throws FileNotFoundException,IOException
{
//locate properties file
FileInputStream fis=new FileInputStream("abc.properties");
//load the properties file by using load() method of Properties class
Properties p = new Properties();
286 | P a g e
Durgasoft Mr. Ratan
p.load(fis);
//get the data from properties class by using getProperty()
String username = p.getProperty("username");
String driver = p.getProperty("driver");
String password = p.getProperty("password");
String trainer = p.getProperty("trainer");
If first object sid value is greater than existing object then it returns positive//no change in data
If the object sid values is less than existing object then it returns negative.//change location
If any negative or both are equals then it returns zero. //no change in data
Student.java
class Student implements Comparable
287 | P a g e
Durgasoft Mr. Ratan
{ int sid;
String sname;
Student(int sid,String sname)//local var
{ this.sname=sname; this.sid=sid;
}
public int compareTo(Object obj)
{ Student s = (Student)obj;
if (sid>s.sid)
{return 1;
}
if (sid<s.sid)
{return -1;
}
If(sid==0){
return 0;}
}
}
Test.java:-
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(11,"ratan"));
al.add(new Student(2,"Sravya"));
al.add(new Student(333,"anu"));
Collections.sort(al);
Iterator<Student> itr =al.iterator();
while (itr.hasNext())
{ Student s = itr.next();
System.out.println(s.sid+"----"+s.sname);
}
}
}
import java.util.*;
class Comp implements Comparator
{
public int compare(Object o1,Object o2)
{
EmpBean e1 = (EmpBean)o1;
EmpBean e2 = (EmpBean)o2;
if (e1.eid==e2.eid)
{return 0;
288 | P a g e
Durgasoft Mr. Ratan
}
if (e1.eid>e1.eid)
{return 1;
}
else{return -1;}
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
{
TreeSet<EmpBean> s = new TreeSet<EmpBean>(new Comp());
EmpBean e1 = new EmpBean();
e1.setEid(111);
e1.setEname("ratan");
EmpBean e2 = new EmpBean();
e2.setEid(22);
e2.setEname("anu");
s.add(e1);
s.add(e2);
}
}
public class EmpBean implements Comparable<EmpBean>
{ int eid;
String ename;
public void setEid(int eid)
{ this.eid=eid;
}
public void setEname(String ename)
{ this.ename=ename;
}
public int getEid()
{return eid;
}
public String getEname()
{return ename;
}
public int compareTo(EmpBean o)
289 | P a g e
Durgasoft Mr. Ratan
{
if (eid==o.eid)
{return 0;
}
if (eid>o.eid)
{return 1;
}
else{return -1;}
}
};
networking
Introduction to networking:-
1) The process of connecting the resources (computers) together to share the data is called
networking.
2) Java.net is package it contains number of classes by using that classes we are able to
connection between the devices (computers) to share the information.
3) Java.net package provide support for the TCP (Transmission Control Protocol),UDP(user data
gram protocol) protocols.
Categories of network:-
290 | P a g e
Durgasoft Mr. Ratan
Client-server:-
In the client server architecture always client system behaves as a client and server system
behaves as a server.
Peer-to-peer:-
Inthe peer to peer client system sometimes behaves as a server, server system sometimes
behaves like a client the roles are not fixed.
Types of networks:-
Intranet:-
It is also known as a private network. To share the information in limited area
range(within the organization) then we should go for intranet.
Internet:-
It is also known as public networks. Where the data maintained in a centralized server
hence we are having more sharability. And we can access the data from anywhere else.
Extranet:-
This is extension to the private network means other than the organization , authorized
persons able to access.
The frequently used terms in the networking:-
1) IP Address
2) URL(Uniform Resource Locator)
3) Protocol
4) Port Number
5) MAC address.
6) Connection oriented and connection less protocol
7) Socket.
Protocol:-
Protocol is a set of rules fallowed by the every computer present in the network this is useful to
send the data physically from one place to another place in the network.
TCP(Transmission Control Protocol)(connection oriented protocol)
UDP (User Data Gram Protocol)(connection less protocol)
Telnet
SMTP(Simple Mail Transfer Protocol)
IP (Internet Protocol)
IP Address:-
1) IP Address is a unique identification number given to the computer to indentify it uniquely
in the network.
2) The IP Address is uniquely assigned to the computer it is not duplicated.
3) The IP Address range is 0-255 if we are giving the other than this range that is not allowed.
4) We can identify the particular computer in the network with the help of IP Address.
5) The IP Address contains four digit number
a. 125.0.4.255----good
b. 124.654.5.6-----bad
c. 1.2.3.4.5.6-------bad
291 | P a g e
Durgasoft Mr. Ratan
6) Each and every website contains its own IP Address we can access the sites through the
names otherwise IP Address.
Site Name :- www.google.com
IP Address :- 74.125.224.72
Ex:-
import java.net.*;
import java.io.*;
class Test
{
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter site name");
String sitename=br.readLine();
InetAddress in=InetAddress.getByName(sitename);
System.out.println("the ip address is:"+in);
}
}
java Test
www.yahoo.com
The IP Address is: www.yahoo.com/ 106.10.139.246
Java Test
Please press enter key then we will get IP Address of the system.
The IP Address is : local host/we are getting IP Address of the system
Note:-
If the internet is not available we are getting java.net.UnKnownHostException.
http://www.Sravyasoft.com:10/Corejava_rattaiah.asp
292 | P a g e
Durgasoft Mr. Ratan
To achieve the fallowing communication the java peoples are provided the fallowing classes.
a. Socket
b. ServerSocket
Application Layer
TCP
IP
Physical Layer
293 | P a g e
Durgasoft Mr. Ratan
Application Layer:-
Takes the data from the application and sends it to the TCP layer.
TCP Protocol:-
it will take the data which is coming from Application Layer and divides in to small units called
Packets. Then transfer those packets to the next layer called IP. The packet contains group of
bytes of data.
IP:-
It will take the packets which is coming from TCP and prepare envelop called ‘frames’ hence the
frame contains the group of packets. Then it will identify the particular target machine on the
basis of the IP address and sent that frames to the physical layer.
Physical Layer:-
Based on the physical medium it will transfer the data to the target machine.
To achieve the UDP communication the java peoples are provided the fallowing classes.
1. DataGrampacket.
2. DataGramSocket.
Socket:-
1) Socket is used to create the connection between the client and server.
2) Socket is nothing but a combination of IP Address and port number.
3) The socket is created at client side.
4) Socket is class present in the java.net package
5) It is acting as a communicator between the client and server.
6) Whenever if we want to send the data first we have to create a socket that is acts as a medium.
294 | P a g e
Durgasoft Mr. Ratan
Client.java:-
import java.net.*;
import java.io.*;
class Client
{
public static void main(String[] args)throws Exception
{
Socket s=new Socket("localhost",5555);
String str="ratan from client";
OutputStream os=s.getOutputStream();
PrintStream ps=new PrintStream(os);
ps.println(str);
InputStream is=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str1=br.readLine();
System.out.println(str1);
}
}
Server.java:-
import java.io.*;
import java.net.*;
class Server
{
public static void main(String[] args) throws Exception
{
//to read the data from client
ServerSocket ss=new ServerSocket(5555);
Socket s=ss.accept();
OutputStream os=s.getOutputStream();
PrintStream ps=new PrintStream(os);
ps.println(data);
}
}
295 | P a g e
Durgasoft Mr. Ratan
Java.awt package
Abstract Window Tool kit is an API it supports graphical user interface programming.
By using java.awt package we are able to develop the components like
o TextFiled , Label, Button ,Checkbox ,RadioButton…..etc
AWT components are platform dependent it displays the application according to the view of
operating system.
By using java.awt package we are able to prepare static components to provide the dynamic
nature to the component use java.awt.event package.(it is a sub package of java.awt).
1. This application not providing very good look and feel hence the normal users facing problem
with these types of applications.
296 | P a g e
Durgasoft Mr. Ratan
2. By using AWT we are preparing application these applications are called console based or CUI
application.
Note
Java.awt package is used to prepare static components.
Java.awt.event package is used to provide the life to the static components.
component :-
The root class of java.awt package is Component class.
Component is an object which is displayed pictorially on the screen.
Ex:- Button,Label,TextField......etc
Container:-
it is a component in awt that contains another components like Button,TextField…etc
Container is a sub class of Component class.
The classes that extends container classes those classes are containers such as Frame, Dialog
and Panel.
Event:-
The event nothing but a action generated on the component or the change is made on the state
of the object.
Ex:-
Button clicked, Checkboxchecked, Itemselected in the list, Scrollbar scrolled
horizontal/vertically.
Classes of AWT:-
The classes present in the AWT package.
297 | P a g e
Durgasoft Mr. Ratan
Java.awt.Frame:-
Frame is a Basic component in AWT, it contains other components like Button, TextField...etc.
There are two approaches to create a frame
1) By extending Frame class.
2) By creating Object of Frame class.
298 | P a g e
Durgasoft Mr. Ratan
Constructors:-
Frame f=new Frame();
Frame f=new Frame("MyFrame");
Characteristics of the Frame:-
When we create a Frame class object the Frame will be created automatically with invisible
mode so to provide visible nature to the frame use setVisible() method of Frame class.
public void setVisible(boolean b)
where b==true visible mode b==false means invisible mode.
When we created a Frame the initial size of the Frame is 0 pixel heights& 0 pixel width so it is
not visible to use.To provide particular size to the Frame we have to use setSize() method.
public void setSize(int width,int height)
To provide title to the Frame use.public void setTitle(String Title)
When we create a Frame, the default background color of the Frame is white. If you want to
provide particular color to the Frame we have to use the following method.
public void setBackground(color c)
299 | P a g e
Durgasoft Mr. Ratan
2. To set a particular font to the text,we have to use Font class present in java.awt package
Font f=new Font(String type,int style,int size);
Ex: Font f= new Font("arial",Font.Bold,30);
Ex :-
import java.awt.*;
class Test extends Frame
{
public static void main(String[] args)
{
Test t=new Test();
t.setVisible(true);
t.setSize(500,500);
t.setTitle("myframe");
t.setBackground(Color.red);
}
public void paint(Graphics g)
{
Font f=new Font("arial",Font.ITALIC,25);
g.setFont(f);
g.drawString("hi ratan how r u",100,100);
}
}
Note:-
1. When we create a MyFrame class constructor,jvm executes MyFrame class construcor just
before this JVM has to execute Frame class zero argument constructor.
2. In Frame class zero argument constructor repaint() method will be executed, it will access
predefined Frame class paint() method. But as per the requirement overriding paint()
method will be executed.
3. Therefore the paint() will be executed automatically at the time of Frame creation.
Constructor:-
Label l=new Label();
Label l=new Label(“user name”);
Ex :- f.setVisible(true);
import java.awt.*; f.setTitle("ratan");
class Test f.setBackground(Color.red);
{ f.setSize(400,500);
public static void main(String[] args) Label l=new Label("user name:");
{ f.add(l);
Frame f=new Frame(); }
300 | P a g e
Durgasoft Mr. Ratan
TextField:-
TextField is an editable area and it is possible to provide single line of text.
Enter Button doesn’t work on TextField.
o To set Text to the textarea we have to use t.setText(“Sravya”);
o To get the text form the TextArea we have to use String s=t.getText();
o To append text into the TextAreat.appendText("ratan");
Constructor:-
TextFiled tx=new TextFiled();
TextField tx=new TextField(“ratan”);
Ex :-
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Frame f=new Frame();
f.setVisible(true);
f.setTitle("ratan");
f.setBackground(Color.red);
f.setSize(400,500);
//TextField tx=new TextField(); empty TextField
TextField tx=new TextField("ratan");
//TextField with data
f.add(tx);
}
}
TextArea:-TextArea is a Editable Area&enter button will work on TextArea.
TextArea t=new TextArea();
TextArea t=new TextArea(int rows,int columns);
To set Text to the textarea we have to use ta.setText(“Sravya”);
301 | P a g e
Durgasoft Mr. Ratan
To get the text form the TextArea we have to use String s=ta.getText();
To append the text into the TextAreause ta.appendText("ratan");
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Frame f=new Frame();
f.setVisible(true);
f.setTitle("ratan");
f.setBackground(Color.red);
f.setSize(400,500);
f.setLayout(new FlowLayout());
Label l=new Label("user name:");
TextArea tx=new TextArea(4,10);//4 character height 10 character width
tx.appendText("ratan");
tx.setText("aruna");
System.out.println(tx.getText());
f.add(l);
f.add(tx);
}
}
Choice:-List is allows to select multiple items but choice is allow to select single Item.
Choice ch=new Choice();
Methods :-
1. To add items to the choice use add() method.
2. To remove item from the choice based on String use remove()method. choice.remove(“HYD”);
3. To remove the item based on the index position use choice.remove(2);
4. To remove the all elementsch.removeAll();
5. To inset the data into the choice based on the particular position.choice.insert(2,”ratan”);
6. To get selected item from the choice use String s=ch.getSelectedItem();
7. To get the selected item index number use int a=ch.getSelectedIndex();
ex:- import java.awt.*;
302 | P a g e
Durgasoft Mr. Ratan
class Test
{ public static void main(String[] args)
{ Frame f=new Frame();
f.setVisible(true);
f.setTitle("ratan");
f.setBackground(Color.red);
f.setSize(400,500);
Choice ch=new Choice();
ch.add("c");
ch.add("cpp");
ch.add("java");
ch.add(".net");
ch.remove(".net");
ch.remove(0);
ch.insert("ratan",0);
f.add(ch);
System.out.println(ch.getItem(0));
System.out.println(ch.getSelectedItem());
System.out.println(ch.getSelectedIndex());
//ch.removeAll();
}
}
List: List is providinglist of options to select.Based on your requirement we can select any number of
elements. To add the List to the frame we have to use add() method.
CONSTRUCTOR:-
List l=new List();It will creates the list by default size is four elements.
List l=new List(3);It will display the three items size and it is allow selecting the only single item.
List l=new List(5,true);It will display the five items and it is allow selecting the multiple items.
Methods:-
To add the elements to the List use list.add(“c”);
To add the elements to the List at specified index list.add(“ratan”,0);
To remove element from the List use list.remove(“c”);
To get selected item from the List use String x=l.get SelectedItem();
To get selected items from the List we have to use String[] x=s.getSelectedItems()
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Frame f=new Frame();
f.setVisible(true);
f.setTitle("ratan");
f.setBackground(Color.red);
f.setSize(400,500);
f.setLayout(new FlowLayout());
List l=new List(4,true);
l.add("c"); l.add("cpp"); l.add("java"); l.add(".net");
l.add("ratan"); l.add("arun",0); l.remove(0); f.add(l);
303 | P a g e
Durgasoft Mr. Ratan
System.out.println(l.getSelectedItem());
}
}
Checkbox: - The user can select more than one checkbox at a time.
1) Checkbox cb1=new CheckBox();
2) Checkbox cb2=new CheckBox(“MCA”);
3) Checkbox cb3=new CheckBox(“BSC”,true);
Methods:-
1. To set a label to the CheckBox explicitly usecb.setLabel(“BSC”);
2. To get the label of the checkbox use String str=cb.getLabel();
3. To get state of the CheckBox useBoolean b=ch.getState();
Ex:-
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Frame f=new Frame();
f.setVisible(true);
f.setTitle("ratan");
f.setBackground(Color.red);
f.setSize(400,500);
Checkbox cb1=new Checkbox("BTECH",true);
f.add(cb1);
System.out.println(cb1.getLabel());
System.out.println(cb1.getState());
}
}
304 | P a g e
Durgasoft Mr. Ratan
RADIO BUTTON:
AWT doesnot provide any predefined support to create RadioButtons.
It is possible to select Only item from group of items and we are able to create RadioButton by
using two classes.
o CheckBoxgroup
o CheckBox
step 1:-Create CheckBox group object. CheckBoxGroup cg=new CheckBoxGroup();
step 2:- pass Checkboxgroup object to the Checkbox class argument.
CheckBox cb1=new CheckBox(“male”,cg,false);
CheckBox cb2=new CheckBox(“female”,cg,false);
Methods:-
1) To get the status of the RadioButton use String str=Cb.getState();
2) To get Label of the RadioButton use String str=getLabel().
Ex:-
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Frame f=new Frame();
f.setVisible(true);
f.setTitle("ratan");
f.setBackground(Color.red);
f.setSize(400,500);
CheckboxGroup cg=new CheckboxGroup();
Checkbox cb1=new Checkbox("male",cg,true);
f.add(cb1);
System.out.println(cb1.getLabel());
System.out.println(cb1.getState());
}
}
305 | P a g e
Durgasoft Mr. Ratan
Layout Managers:-
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Frame f=new Frame();
f.setVisible(true);
f.setTitle("ratan");
f.setBackground(Color.red);
f.setSize(400,500);
Label l1=new Label("user name:");
TextField tx1=new TextField();
Label l2=new Label("password:");
TextField tx2=new TextField();
Button b=new Button("login");
f.add(l1); f.add(tx1); f.add(l2);
f.add(tx1); f.add(b);
}
}
Event delegation model:-
1. When we create a component the components visible on the screen but it is not possible to
perform any action for example button.
2. Whenever we create a Frame it can be minimized and maximized and resized but it is not
possible to close the Frame even if we click on Frame close Button.
3. The Frame is a static component so it is not possible to perform actions on the Frame.
4. To make static component into dynamic component we have to add some actions to the Frame.
5. To attach actions to the Frame component we need event delegation model.
Whenever we click on button no action will be performed clicking like this is called event.
Event: - Event is nothing but a particular action generated on the particular component.
1. When an event generates on the component the component is unable to respond because
component can't listen the event.
2. To make the component listen the event we have to add listeners to the component.
3. Wherever we are adding listeners to the component the component is able to respond based on
the generated event.
4. A listener is a interface which contain abstract methods and it is present in java.awt.event
package
5. The listeners are different from component to component.
306 | P a g e
Durgasoft Mr. Ratan
A component delegate event to the listener and listener is designates the event to appropriate
method by executing that method only the event is handled.This is called Event Delegation Model.
Delegates
Handling method
component Delegates listeners Delegates
Delegates
Click the button(event is raised)
Handling method
Note: -
To attach a particular listener to the Frame we have to use following method
Public void AddxxxListener(xxxListener e)
Where xxx may be ActionListener,windowListener
The Appropriate Listener for the Frame is “windowListener”
ScrollBar:-
1. By using ScrollBar we can move the Frame up and down.
ScrollBar s=new ScrollBar(int type)
Type of scrollbar
1. VERTICAL ScrollBar
2. HORIZONTAL ScrollBar
To create a HORIZONTAL ScrollBar:-
ScrollBar sb=new ScrollBar(ScrollBar.HORIZONTAL);
To get the current position of the scrollbar we have to use the following method.
public int getValue()
To create a VERTICAL ScrollBar:-
ScrollBar sb=new ScrollBar(ScrollBar.VERTICAL);
Appropriate Listeners for Components:-
307 | P a g e
Durgasoft Mr. Ratan
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setSize(400,500);
this.setVisible(true);
this.setTitle("myframe");
this.addWindowListener(new myclassimpl());
}
}
class myclassimpl implements WindowListener
{ public void windowActivated(WindowEvent e)
{ System.out.println("window activated");
}
public void windowDeactivated(WindowEvent e)
{ System.out.println("window deactivated");
}
public void windowIconified(WindowEvent e)
308 | P a g e
Durgasoft Mr. Ratan
{ System.out.println("window iconified");
}
public void windowDeiconified(WindowEvent e)
{ System.out.println("window deiconified");
}
public void windowClosed(WindowEvent e)
{ System.out.println("window closed");
}
public void windowClosing(WindowEvent e)
{ System.exit(0);
}
public void windowOpened(WindowEvent e)
{ System.out.println("window Opened");
}
};
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.setBackground(Color.red);
this.setTitle("rattaiah");
this.addWindowListener(new Listenerimpl());
}
};
class Listenerimpl extends WindowAdapter
{ public void windowClosing(WindowEvent we)
{ System.exit(0);
}
};
class Demo
{ public static void main(String[] args)
309 | P a g e
Durgasoft Mr. Ratan
310 | P a g e
Durgasoft Mr. Ratan
311 | P a g e
Durgasoft Mr. Ratan
********GRIDLAYOUT**********
import java.awt.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.setTitle("rattaiah");
this.setBackground(Color.red);
this.setLayout(new GridLayout(4,4));
for (int i=0;i<10 ;i++ )
{ Button b=new Button(""+i);
this.add(b);
}
}
};
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
312 | P a g e
Durgasoft Mr. Ratan
*********ACTIONLISTENER**********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements ActionListener
{ TextField tx1,tx2,tx3;
Label l1,l2,l3;
Button b1,b2;
int result;
myframe()
{ this.setSize(250,400);
this.setVisible(true);
this.setLayout(new FlowLayout());
l1=new Label("first value");
l2=new Label("second value");
l3=new Label("result");
tx1=new TextField(25);
tx2=new TextField(25);
tx3=new TextField(25);
b1=new Button("add");
b2=new Button("mul");
b1.addActionListener(this);
b2.addActionListener(this);
this.add(l1); this.add(tx1); this.add(l2);
this.add(tx2); this.add(l3); this.add(tx3);
this.add(b1); this.add(b2);
}
public void actionPerformed(ActionEvent e)
{ try{
int fval=Integer.parseInt(tx1.getText());
int sval=Integer.parseInt(tx2.getText());
String label=e.getActionCommand();
if (label.equals("add"))
{ result=fval+sval;
}
if (label.equals("mul"))
{ result=fval*sval;
}
tx3.setText(""+result);
}
catch(Exception ee)
{
ee.printStackTrace();
}
}
};
313 | P a g e
Durgasoft Mr. Ratan
class Demo
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{ Label l1,l2;
TextField tx1,tx2;
Button b;
String status="";
MyFrame()
{ setVisible(true);
setSize(400,400);
setTitle("girls");
setBackground(Color.red);
l1=new Label("user name:");
l2=new Label("password:");
tx1=new TextField(25);
tx2=new TextField(25);
b=new Button("login");
b.addActionListener(this);
tx2.setEchoChar('*');
this.setLayout(new FlowLayout());
this.add(l1);
this.add(tx1);
this.add(l2);
this.add(tx2);
this.add(b);
}
public void actionPerformed(ActionEvent ae)
{ String uname=tx1.getText();
String upwd=tx2.getText();
if (uname.equals("Sravya")&&upwd.equals("dss"))
{ status="login success"; }
else
{ status="login failure"; }
repaint();
}
public void paint(Graphics g)
{
314 | P a g e
Durgasoft Mr. Ratan
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
******MENUITEMS************
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{
String label="";
MenuBar mb;
Menu m1,m2,m3;
MenuItem mi1,mi2,mi3;
MyFrame()
{ this.setSize(300,300);
this.setVisible(true);
this.setTitle("myFrame");
this.setBackground(Color.green);
mb=new MenuBar();
this.setMenuBar(mb);
m1=new Menu("new");
m2=new Menu("option");
m3=new Menu("edit");
mb.add(m1);
mb.add(m2);
mb.add(m3);
mi1=new MenuItem("open");
mi2=new MenuItem("save");
mi3=new MenuItem("saveas");
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
m1.add(mi1);
m1.add(mi2);
315 | P a g e
Durgasoft Mr. Ratan
m1.add(mi3);
}
public void actionPerformed(ActionEvent ae)
{
label=ae.getActionCommand();
repaint();
}
*****MOUSELISTENER INTERFACE**********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements MouseListener
{ String[] msg=new String[5];
myframe()
{ this.setSize(500,500);
this.setVisible(true);
this.addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{ msg[0]="mouse clicked......("+e.getX()+","+e.getY()+")";
repaint();
}
public void mousePressed(MouseEvent e)
{ msg[1]="mouse pressed......("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseReleased(MouseEvent e)
{ msg[2]="mouse released......("+e.getX()+","+e.getY()+")";
repaint();
}
316 | P a g e
Durgasoft Mr. Ratan
*******ITEMLISTENER INTERFACE**********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements ItemListener
{ String qual="",gen="";
Label l1,l2;
CheckboxGroup cg;
Checkbox c1,c2,c3,c4,c5;
Font f;
myframe()
{ this.setSize(300,400);
this.setVisible(true);
this.setLayout(new FlowLayout());
c1=new Checkbox("BSC");
c2=new Checkbox("BTECH");
c3=new Checkbox("MCA");
317 | P a g e
Durgasoft Mr. Ratan
cg=new CheckboxGroup();
c4=new Checkbox("Male",cg,false);
c5=new Checkbox("Female",cg,true);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
class rc
{ public static void main(String[] args)
{ myframe f=new myframe();
}
318 | P a g e
Durgasoft Mr. Ratan
};
*********KEYLISTENER INTERFACE***********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame
{ myframe()
{ this.setSize(400,400);
this.setVisible(true);
this.setBackground(Color.green);
this.addKeyListener(new keyboardimpl());
}
};
class keyboardimpl implements KeyListener
{ public void keyTyped(KeyEvent e)
{ System.out.println("key typed "+e.getKeyChar());
}
public void keyPressed(KeyEvent e)
{ System.out.println("key pressed "+e.getKeyChar());
}
public void keyReleased(KeyEvent e)
{ System.out.println("key released "+e.getKeyChar());
}
}
class Demo
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
***********CHECK LIST AND CHOICE************
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements ItemListener
{ Label l1,l2;
List l;
Choice ch;
String[] tech;
String city="";
myframe()
{ this.setSize(300,400);
this.setVisible(true);
this.setLayout(new FlowLayout());
l=new List(3,true);
l.add("c"); l.add("c++"); l.add("java");
l.addItemListener(this);
319 | P a g e
Durgasoft Mr. Ratan
ch=new Choice();
ch.add("hyd"); ch.add("chenni"); ch.add("Banglore");
ch.addItemListener(this);
sb=new Scrollbar(Scrollbar.VERTICAL);
this.add("East",sb);
sb.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{ position=sb.getValue();
}
public void paint(Graphics g)
320 | P a g e
Durgasoft Mr. Ratan
{ g.drawString("position:"+position,100,200);
repaint();
}
}
class scrollbarex
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
SWINGS
1. AWT components are heavyweight component but swing components are light weight
component.
2. AWT components consume more number of system resources Swings consume less number of
system resources.
3. AWT components are platform dependent but Swings are platform independent.
321 | P a g e
Durgasoft Mr. Ratan
4. AWT is provided less number of components where as swings provides more number of
components.
5. AWT doesn’t provide Tooltip Test support but swing components have provided Tooltip test
support.
6. in awt for only window closing : windowListenerwindowAdaptor
In case of swing use small piece of code.
i. f.setDefaultCloseOption(JFrame.EXIT-ON-CLOSE);
7. AWT will not follow MVC but swing follows MVC Model View Controller It is a design pattern to
provide clear separation b/w controller part,model part,view part.
a. Controller is a normal java class it will provide controlling.
b. View part provides presentation
c. Model part provides required logic.
8. In case of AWT we will add the GUI components in the Frame directly but Swing we will add all
GUI components to panes to accommodate GUI components.
Classes of swing:-
322 | P a g e
Durgasoft Mr. Ratan
323 | P a g e
Durgasoft Mr. Ratan
Example :-
import java.awt.*;
import javax.swing.*;
class MyFrame extends JFrame
{ JLabel l1,l2,l3,l4,l5,l6,l7;
JTextField tf;
JPasswordField pf;
JCheckBox cb1,cb2,cb3;
JRadioButton rb1,rb2;
JList l;
JComboBox cb;
JTextArea ta;
JButton b;
Container c;
MyFrame() //constructor
{
this.setVisible(true);
this.setSize(150,500);
this.setTitle("SWING GUI COMPONENTS EXAMPLE");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=this.getContentPane();
c.setLayout(new FlowLayout());
c.setBackground(Color.green);
l1=new JLabel("User Name");
l2= new JLabel("password");
l3= new JLabel("Qualification");
l4= new JLabel("User Gender");
l5= new JLabel("Technologies");
l6= new JLabel("UserAddress");
l7= new JLabel("comments");
tf=new JTextField(15);
tf.setToolTipText("TextField");
pf=new JPasswordField(15);
pf.setToolTipText("PasswordField");
cb1=new JCheckBox("BSC",false);
cb2=new JCheckBox("MCA",false);
cb3=new JCheckBox("PHD",false);
rb1=new JRadioButton("Male",false);
rb2=new JRadioButton("Female",false);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1); bg.add(rb2);
String[] listitems={"cpp","c","java"};
l=new JList(listitems);
String[] cbitems={"hyd","pune","bangalore"};
cb=new JComboBox(cbitems);
ta=new JTextArea(5,20);
b=new JButton("submit");
c.add(l1); c.add(tf); c.add(l2); c.add(pf);
324 | P a g e
Durgasoft Mr. Ratan
325 | P a g e
Durgasoft Mr. Ratan
326 | P a g e
Durgasoft Mr. Ratan
********JTABLE******************
import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;
class Demo1
{ public static void main(String[] args)
{JFrame f=new JFrame();
f.setVisible(true);
f.setSize(300,300);
Container c=f.getContentPane();
String[] header={"ENO","ENAME","ESAL"};
Object[][] body={{"111","aaa",5000},{"222","bbb",6000},{"333","ccc",7000},{"444","ddd",8000}};
JTable t=new JTable(body,header);
JTableHeader th=t.getTableHeader();
c.setLayout(new BorderLayout());
c.add("North",th);
c.add("Center",t);
}
}
*****************APPLET****************
import java.awt.*;
import java.applet.*;
public class Demo2 extends Applet
{
public void paint(Graphics g)
{
Font f=new Font("arial",Font.BOLD,20);
g.setFont(f);
Configuration of Applet:-
<html>
<applet code="Demo2.class" width="500" height="500">
</applet>
</html>
327 | P a g e
Durgasoft Mr. Ratan
328 | P a g e
Durgasoft Mr. Ratan
INTERNATIONALIZATION (i18N)
Internationalization is also called as i18n because in between I & n 18 words are present.
By using Locale class and ResourceBundle class we are enable I18n on the application.
Local is nothing but language + country.
For making your application to support I18n we need to prepare local specific properties
file it means for English one properties file & hindi one properties file …etc.
The property file format is key = value
The properties file name fallowed pattern bundlenamewith language code and country
code.
o ApplicationMessages_en_US.properties.
In single web application contains different properties file all the properties files key
must be same and values are changed local to Locale.
Java.util.Locale:-
Locale Object is decide properties file based on argument you passed and then it display
locale specific details based on Properties file entry.
Locale l = new Locale(args[0],args[1]);
Locale l = new Locale(en,US);
D:\5batch>javap java.util.Locale
Compiled from "Locale.java"
public final class java.util.Locale extends java.lang.Object i
public static final java.util.Locale ENGLISH;
public static final java.util.Locale FRENCH;
public static final java.util.Locale GERMAN;
public static final java.util.Locale ITALIAN;
public static final java.util.Locale JAPANESE;
public static final java.util.Locale KOREAN;
public static final java.util.Locale CHINESE;
public static final java.util.Locale SIMPLIFIED_CHINESE;
public static final java.util.Locale TRADITIONAL_CHINESE;
public static final java.util.Locale FRANCE;
public static final java.util.Locale GERMANY;
public static final java.util.Locale ITALY;
public static final java.util.Locale JAPAN;
public static final java.util.Locale KOREA;
public static final java.util.Locale CHINA;
public static final java.util.Locale PRC;
public static final java.util.Locale TAIWAN;
public static final java.util.Locale UK;
public static final java.util.Locale US;
public static final java.util.Locale CANADA;
329 | P a g e
Durgasoft Mr. Ratan
330 | P a g e
Durgasoft Mr. Ratan
Application 1:-
Steps to design application:-
Step-1:- prepare properties files to support different languages and countries.
Application.properties default properties file(base properties file)
Application_fr_FR.properties French properties file
Allication_ratan_RATAN.properties Ratan country properties file
Step 2:- create locale object it identified particular language and country and it decides
execution of properties file.
Locale l = new Locale(“en”,”US”);
The above statement specify language is English and country united states
Locale l = new Locale("fr","CA");
Locale x = new Locale("fr","FR");
The above two locales specifies France language in Canada & France
Instead of hard coding language name and country name get the values from command prompt
at runtime.
Public static void main(String[ ] args)
{ Locale l = new Locale(args[0],args[1]);
}
D:\5batch>java Test fr FR
Application.properties:-
countryname = USA
lang = eng
Application_fr_FR.properties:-
countryname = canada
lang = france
Allication_ratan_RATAN.properties:-
countryname=Ratan
lang= ratan
331 | P a g e
Durgasoft Mr. Ratan
Test.java:-
import java.util.*;
class Test
{ public static void main(String[] args)
{
//if no local is Matched this property file is executed
ResourceBundle bundle1 = ResourceBundle.getBundle("Application");
//it create ResourceBundle with local that is already defined
Locale l1 = Locale.FRANCE;
ResourceBundle bundle2 = ResourceBundle.getBundle("Application",l1);
//it creates ResourceBundle with new user created Locale
Locale l2 = new Locale("ratan","RATAN")
ResourceBundle bundle3 = ResourceBundle.getBundle("Application",l2);
System.out.println(bundle1.getString("countryname")+"--"+bundle1.getString("lang"));
System.out.println(bundle2.getString("countryname")+"--"+bundle2.getString("lang"));
System.out.println(bundle3.getString("countryname")+"--"+bundle3.getString("lang"));
}
}
Output:-
D:\5batch>java Test
USA--eng
Canada--france
Ratan--Ratan
APPLICATION 2:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ //creates local object with the help of arguments
Locale l = new Locale(args[0],args[1]);
//it creates resource bundle with local passed from as command line arguments
ResourceBundle bundle = ResourceBundle.getBundle("Application",l);
System.out.println(bundle.getString("countryname"));
System.out.println(bundle.getString("lang"));
}
}
D:\5batch>java Test x y
USA
eng
D:\5batch>java Test fr FR
canada
france
D:\5batch>java Test ratan RATAN
Ratan
ratan
332 | P a g e
Durgasoft Mr. Ratan
Application.properties:-
wish = hello
lovely = i love you
angry = i hate you
Application_fr_FR.properties:-
wish = hlloe
lovely = i evol you
angry = i etah you
Application_hi_IN.properties:-
wish=\u0c39\u0c46\u0c32\u0c4d\u0c32\u0c4a
lovely=\u0c07 \u0c32\u0c4a\u0c35\u0c46 \u0c2f\u0c4a\u0c09
angry=\u0c07 \u0c39\u0c24\u0c46 \u0c09
import java.util.*;
class Test
{ public static void main(String[] args)
{ Locale l = new Locale(args[0],args[1]);
ResourceBundle rb = ResourceBundle.getBundle("Application",l);
System.out.println(rb.getString("wish"));
System.out.println(rb.getString("lovely"));
System.out.println(rb.getString("angry"));
}
}
D:\5batch>java Test fr FR
D:\5batch>java Test x y hlloe
hello i evol you
i love you i etah you
i hate you D:\5batch>java Test hi IN
??????
? ???? ???
? ??? ?
333 | P a g e
Durgasoft Mr. Ratan
Step 2:- unzip the file and click on index.html page select language and type the words.
Step 3:- copy the content and save the data in text file and while saving select Unicode.
334 | P a g e
Durgasoft Mr. Ratan
Application :-
Application.properties:-
wish = hello
lovely = i love you
angry = i hate you
Application_fr_FR.properties:-
wish = hlloe
lovely = i evol you
angry = i etah you
Application_tl_IN.properties:-
wish=\u0c39\u0c46\u0c32\u0c4d\u0c32\u0c4a
lovely=\u0c07 \u0c32\u0c4a\u0c35\u0c46 \u0c2f\u0c4a\u0c09
angry=\u0c07 \u0c39\u0c24\u0c46 \u0c09
Test.java:-
import java.util.*;
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Locale l = new Locale(args[0],args[1]);
ResourceBundle b = ResourceBundle.getBundle("Application",l);
Frame f = new Frame(); //to create frame
f.setVisible(true); //to provide visibility to frame
f.setSize(300,75);//to align the frame set bounds
f.setLayout(new FlowLayout());//to set the frame proper format
//creation of buttons with labels
Button b1 = new Button(b.getString("wish"));
Button b2 = new Button(b.getString("lovely"));
Button b3 = new Button(b.getString("angry"));
//adding buttons into frame
f.add(b1);
f.add(b2);
f.add(b3);
}
}
335 | P a g e
Durgasoft Mr. Ratan
Test.java:- example
import java.util.*;
public class Test {
static public void main(String[] args) {
String language;
String country;
Locale currentLocale;
ResourceBundle messages;
if (args.length != 2)
{ language = new String("en");
country = new String("US");
}
else
{ language = new String(args[0]);
country = new String(args[1]);
}
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle("Application", currentLocale);
System.out.println(messages.getString("wish"));
System.out.println(messages.getString("lovely"));
System.out.println(messages.getString("angry"));
336 | P a g e
Durgasoft Mr. Ratan
}
}
D:\5batch>java Test
hello
i love you
i hate you
D:\5batch>java Test x y
hello
i love you
i hate you
D:\5batch>java Test tl IN
??????
? ???? ???
? ??? ?
D:\5batch>java Test fr FR
hlloe
i evol you
i etah you
Example :- display Date in different Locale.
DateFormat.DEFAULT,
DateFormat.SHORT,
DateFormat.MEDIUM,
DateFormat.LONG,
DateFormat.FULL
Test.java:-
import java.util.*;
import java.text.DateFormat;
class Test
{ public static void main(String[] args)
{
Date d = new Date();
//default locale en US
DateFormat df1 = DateFormat.getDateInstance(DateFormat.DEFAULT,Locale.getDefault());
System.out.println(df1.format(d));
//date of fresh
337 | P a g e
Durgasoft Mr. Ratan
import java.util.*;
import java.text.*;
class Test
{ public static void main(String[] args)
{Date d = new Date();
DateFormat df1 = DateFormat.getTimeInstance(DateFormat.DEFAULT,Locale.getDefault());
System.out.println(df1.format(d));
DateFormat df2 = DateFormat.getTimeInstance(DateFormat.MEDIUM,Locale.FRENCH);
System.out.println(df2.format(d));
DateFormat df3 = DateFormat.getTimeInstance(DateFormat.SHORT,Locale.ITALY);
System.out.println(df3.format(d));
}
};
Example on both data and Time format:-
338 | P a g e
Durgasoft Mr. Ratan
import java.util.*;
import java.text.*;
class Test
{ public static void main(String[] args)
{ Date d = new Date();
DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL,Locale.getDefault());
System.out.println(df1.format(d));
DateFormat df2 = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL,Locale.FRENCH);
System.out.println(df2.format(d));
}
};
339 | P a g e
Durgasoft Mr. Ratan
JVM Architecture:-
340 | P a g e
Durgasoft Mr. Ratan
Java stacks:-
Whenever new thread is created for each and every new thread the JVM will creates PC(program
coubter) register and stack.
If a thread executing java method the value of pc register indicates the next instruction to
execute.
Stack will stores method invocations of every thread. The java method invocation includes local
variables and return values and intermediate calculations.
The each and every method entery will be stored in stack. And the stack contains grounp of
enteries and each and every entry stored in one stack frame hence stack is group of stack
frames.
Whenever the method complets the entry is automatically deleted from the stach so whatever
the functionalities declared in method it is applicable only for respective methods.
Java native method stack is used to store the native methods invocations.
341 | P a g e
Durgasoft Mr. Ratan
Modifiers summary:-
In java no concept like “access specifiers and access modifiers”and only one concept is there
modifiers concept.
How many Modifiersin java means don’t say 3 or 4 or 5 ,in java 11 modifiers are there.
The default modifier in java is “default”.
The most restricted modifier in java is private (only with in the class).
The most accessable modifier in java is public (all package can access)
The only one modifier applicable to local variables is “final”.
Proof 1:-
private class Test
{ public static void main(String[] args)
{
}
}
Compilation Error:-
D:\morn11>javac Test.java
Test.java:1: modifier private not allowed here
private class Test
modifier classesmethodsvariables
public yes yes yes
private no yes yes
default yes yes yes
protected no yes yes
final yes yes yes
abstract yes yes no
strictfp yes yes no
transient no no yes
native no yes no
static no yes yes
synchronized no yes no
volatile no no yes
342 | P a g e
Durgasoft Mr. Ratan
343 | P a g e
Durgasoft Mr. Ratan
Arrays
Arrays are used to represent group of elements as a single entity but these elements are
homogeneous & fixed size.
The size of Array is fixed it means once we created Array it is not possible to increase and
decrease the size.
Array in java is index based first element of the array stored at 0 index.
Advantages of array:-
Instead of declaring individual variables we can declare group of elements by using array it
reduces length of the code.
We can store the group of objects easily & we are able to retrieve the data easily.
We can access the random elements present in the any location based on index.
Array is able to hold reference variables of other types.
0 1 2 3 4 5 6 7 8 index
Length is 9
Different ways to declare a Array:-
int[] values;
int []values;
int values[];
declaration & instantiation & initialization :-
Approach 1:- int a[]={10,20,30,40}; //declaring, instantiation, intialization
Approach 2:- int[] a=new int[100]; //declaring, instantiation
a[0]=10; //initialization
a[1]=20;
;;;;;;;;;;;;;;;;;;;;;;
a[99]=40;
344 | P a g e
Durgasoft Mr. Ratan
Example :- taking array elements from dynamic input by using scanner class.
import java.util.*;
class Test
{ public static void main(String[] args)
{ int[] a=new int[5];
Scanner s=new Scanner(System.in);
System.out.println("enter values");
for (int i=0;i<a.length;i++)
{ System.out.println("enter "+i+" value");
a[i]=s.nextInt();
}
for (int a1:a)
{ System.out.println(a1);
}
}
}
345 | P a g e
Durgasoft Mr. Ratan
Example:- adding the objects into Array and printing the objects.
class Test
{ public static void main(String[] args)
{ int[] a = new int[5];
a[0]=111;
for (int a1:a)
{ System.out.println(a1);
}
Emp e1 = new Emp(111,"ratan");
Emp e2 = new Emp(222,"anu");
Emp e3 = new Emp(333,"sravya");
Emp[] e = new Emp[5];
e[0]=e1;
e[1]=e2;
e[2]=e3;
for (Emp ee:e)
{ System.out.println(ee); }
}
}
Output:-
E:\>java Test
111 0 0 0 0
Emp@530daa Emp@a62fc3 Emp@89ae9e null null
Example:- printing array elements with elements and default values.
class Test
{ public static void main(String[] args)
{ Emp[] e = new Emp[5];
e[0]=new Emp(111,"ratan");
e[1]=new Emp(222,"anu");
e[2]=new Emp(333,"sravya");
for (Object ee:e)
{ if (ee instanceof Emp)
{ Emp eee = (Emp)ee;
System.out.println(eee.eid+"----"+eee.ename);
}
if (ee==null)
{ System.out.println(ee);
}
}
}
}
Output:-
E:\>java Test
111----ratan
222----anu
333----sravya
null
null
346 | P a g e
Durgasoft Mr. Ratan
347 | P a g e
Durgasoft Mr. Ratan
348 | P a g e
Durgasoft Mr. Ratan
349 | P a g e
Durgasoft Mr. Ratan
10 20 30 10 20 30
0 1 2 0 1 2
a[0][0]------10 a[0][1]------20 a[0][2]-----30 a[1][0]-----40
a[1][1]-----50 a[1][2]-----60
Example:-
class Test
{ public static void main(String[] args)
{ String[][] str={{"A.","B.","C."},{"ratan","ratan","ratan"}};
System.out.println(str[0][0]+str[1][0]);
System.out.println(str[0][1]+str[1][1]);
System.out.println(str[0][2]+str[1][2]);
}
}
350 | P a g e
Durgasoft Mr. Ratan
}
}
Example :- febonacci series
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ System.out.println("enter the no required for febonacci");
int a = new Scanner(System.in).nextInt();
351 | P a g e
Durgasoft Mr. Ratan
352 | P a g e
Durgasoft Mr. Ratan
14) Can we compile multiple source files at a time and is it possible to execute multiple .classes at a
time?
15) The compiler understandable file format and JVM understandable file format?
16) What is the difference between JRE and JDK?
17) What is the difference between path and class path?
18) What is the purpose of environmental variables setup?
19) What do you en by open source software?
20) What are operations done at compilation time and execution time?
21) What is the purpose of JVM?
22) JVM platform dependent or independent?
23) In java program execution starts from?
24) How many types of commands in java and what is the purpose of commands?
25) Is it possible to provide multiple spaces in between two tokens?
26) Class contains how many elements based on Ratan sir class notes?
27) Source file contains how many elements?
28) What are dependent languages and technologies in market on java?
29) Who is generating .class file and .class files generation is based on what?
30) What is .class file contains?
31) What is the purpose of data types and how many data types are present in java?
32) Who is assigning default values to variables?
33) What is the default value of int, char, Boolean, double?
34) Is null is a keyword or not?
35) What do you mean by main class?
36) Is it possible to declare multiple classes with main method?
37) Can I have multiple main methods in single class?
38) What is the default package in java?
39) Can I import same class twice yes-what happened no -why ?
40) Do I need to import java.lang package ? yes --->why no--->why?
41) Is empty java source file is valid or not?
42) Is it java file contains more than one class?
43) What is the purpose of variables in java?
44) How many types of variables in java and what are those variables?
45) What is the life time of static variables and where these variables are stored?
46) What is the life time of instance variables and where these variables are stored?
47) What is the life time of local variables and where these variables are stored?
48) For the static members when memory is allocated?
49) Where we declared local variables & instance variables & static variables
50) For the instance members when memory is allocated?
51) For the local variables when memory is allocated?
52) What is the difference between instance variables and static variables?
53) Can we declare instance variables inside the instance methods and static variables inside the
static method?
54) If the local variables of methods and class instance variables having same names at that
situation how we are represent local variables and how are representing instance variable?
55) What do you mean by method signature?
56) What do you mean by method implementation?
57) How many types of methods in java and how many types of areas in java?
58) What is the purpose of template method?
353 | P a g e
Durgasoft Mr. Ratan
354 | P a g e
Durgasoft Mr. Ratan
Oops
355 | P a g e
Durgasoft Mr. Ratan
10) Inside the constructor if we are not providing this() and super() keyword the compiler
generated which type of super keyword?
11) How to call super class constructors?
12) Is it possible to use both super and this keyword inside the method?
13) Is it possible to use both super and this keyword inside the constructor?
14) If the child class and parent class contains same variable name that situation how to call
parent class variable in child class?
15) One class able to extends how many classes at a time?
16) If we are extending the your class will become parent class if we are not extending what
is the parent class?
17) What do you mean by aggregation and what is the difference between aggregation and
inheritance?
18) What do you mean by aggregation and composition and Association?
19) Aggregation is also known as?
20) How many objects are created ?
a. MyClassHero c1,c2;
C1 = New MyClassHero();
21) What is the root class for all java classes?
22) Which approach is recommended to create object either parent class object or child class
object?
23) Except one class all class contains parent class in java what is that except class?
24) What is the purpose of instance of keyword in java?
25) What do you mean by polymorphism?
26) What do you mean by method overloading and method overriding?
27) How many types of overloading in java?
28) Is it possible to override variable in java?
29) What do you mean by constructor overloading?
30) What are rules must fallow while performing method overriding?
31) When we will get compilation error like “overridden method is final”?
32) What is the purpose of final modifier java?
33) Is it possible to override static methods yes-how no-why?
34) Parent class reference variable is able to hold child class object?
35) How many types of polymorphism in java?
36) What do you mean by dynamic method dispatch?
37) The applicable modifiers for local variables?
38) Is it all methods present in final class is always final and is it all variables present final
class is always final?
39) If Parent class is holding child class object then by using that we are able to call only
overridden methods of child class but how to call direct methods of child class?
40) Object class contains how many methods?
41) When we will get compilation error like “con not inherit from final parent”?
42) How many types of type casting in java?
43) What do you mean by co-variant return types?
44) What do u mean by method hiding?
45) What do you mean by abstraction?
46) How many types of classes in java?
47) Normal class is also known as ?
48) What is the difference between normal method and abstract method?
356 | P a g e
Durgasoft Mr. Ratan
49) What is the difference between normal class and abstract class?
50) Is it possible to create a object for abstract class?
51) What do you mean by abstract variable?
52) Is it possible to override non-abstract method as a abstract method?
53) Is it possible to declare main method inside the abstract class or not?
54) What is the purpose of abstract modifier in java?
55) How to prevent object creation in java?
56) What is the definition of abstract class?
57) In java is it abstract class reference variable is able to hold child class object?
58) What do you mean by encapsulation?
59) What do you mean by tightly encapsulated class?
60) What do you mean accessor method and mutator method ?
61) How many ways area there to set some values to class properties?
62) Can we overload method?
63) Can we inherit main method in child class?
64) In java main method is called by ?
65) The applicable modifiers on main method?
66) While declaring main method public static modifiers order mandatory or optional?
67) What is the argument of main method?
68) What is the return type of main method?
69) What are the mandatory modifiers for main method and optional modifiers of main
method?
70) Why main method is static?
71) What do you by command line arguments?
72) Is it possible to pass command line arguments with space symbol no good yeshow ?
73) What is the purpose of strictfp classes?
74) What is the purpose of strictfp modifier?
75) What is the purpose of native modifier?
76) What do you mean by native method and it also known as?
77) What do you mean by javaBean class?
78) The javabean class is also known as?
79) Applicable modifiers on local variables?
80) What is the execution process of constructors if two classes are there in inheritance
relationship?
81) What is the execution process of instance blocks if two classes are there in inheritance
relationship?
82) What is the execution process of static blocks if two classes are there in inheritance
relationship?
83) What is the purpose of instanceof operator in java & what is the return-type?
84) If we are using instanceof both reference-variable & class-name must have some
relationship otherwise compiler generated error message is what?
Packages
1. What do you mean by package and what it contains?
2. What is the difference between user defined package and predefined package?
3. What are coding conventions must fallow while declaring user defined package names?
4. Is it possible to declare motile packages in single source file?
357 | P a g e
Durgasoft Mr. Ratan
Exception handling
1. What do you mean by Exception?
2. How many types of exceptions in java?
3. What is the difference between Exception and error?
4. What is the difference between checked Exception and un-checked Exception?
5. Checked exceptions are caused by?
6. Unchecked exceptions are caused by?
7. Errors are caused by?
8. Is it possible to handle Errors in java?
9. What the difference is between partially checked and fully checked Exception?
10. What do you mean by exception handling?
11. How many ways are there to handle the exception?
358 | P a g e
Durgasoft Mr. Ratan
359 | P a g e
Durgasoft Mr. Ratan
Interfaces
a. What do you mean by interface how to declare interfaces in java?
b. Interfaces allows normal methods or abstract methods or both?
c. For the interfaces compiler generates .class files or not?
d. Interface is also known as?
e. What is the abstract method?
f. By default modifiers of interface methods?
g. What is the purpose of implements keyword?
h. Is it possible to declare variables in interface ?
i. Can abstract class have constructor ? can interface have constructor?
j. What must a class do to implement interface?
k. What do you by implementation class?
360 | P a g e
Durgasoft Mr. Ratan
Different types of methods in java (must know information about all methods)
1) Instance method
2) Static method
3) Normal method
4) Abstract method
5) Accessor methods
6) Mutator methods
7) Inline methods
8) Call back methods
9) Synchronized methods
361 | P a g e
Durgasoft Mr. Ratan
362 | P a g e
Durgasoft Mr. Ratan
9) Public variables
String manipulation
1) How many ways to create a String object & StringBuffer object?
2) What is the difference between
a. String str=”ratan”;
b. String str = new String(“ratan”);
3) equals() method present in which class?
4) What is purpose of String class equals() method.
5) What is the difference between equals() and == operator?
6) What is the difference between by immutability & immutability?
7) Can you please tell me some of the immutable classes and mutable classes?
8) String & StringBuffer & StringBuilder & StringTokenizer presented package names?
9) What is the purpose of String class equals() & StringBuffer class equals()?
10) What is the purpose of StringTokenizer nd this class functionality replaced method name?
11) How to reverse String class content?
12) What is the purpose of trim?
13) Is it possible to create StringBuffer object by passing String object as a argument?
14) What is the difference between concat() method & append()?
15) What is the purpose of concat() and toString()?
16) What is the difference between StringBuffer and StringBuilder?
17) What is the difference between String and StringBuffer?
18) What is the difference between compareTo() vs eqauls()?
19) What is the purpose of contains() method?
20) What is the difference between length vs length()?
21) What is the default capacity of StringBuffer?
22) What do you mean by factory method?
23) Concat() method is a factory method or not?
24) What is the difference between heap memory and String constant pool memory?
25) String is a final class or not?
26) StringBuilder and StringTokenizer introduced in which versions?
27) What do you mean by legacy class & can you please give me one example of legacy class?
28) How to apply StringBuffer class methods on String class Object content?
29) When we use String & StringBuffer & String
30) What do you mean by cloneaing and use of cloning?
31) Who many types of cloneaing in java?
32) What do you mean by cloneable interface present in which package and what is the purpose?
33) What do you mean by marker interface and Cloneable is a marker interface or not?
34) How to create duplicate object in java(by using which method)?
Wrapper classes
1. What is the purpose of wrapper classes?
2. How many Wrapper classes present in java what are those?
3. How many ways are there to create wrapper objects?
4. When we will get NumberFormatException?
5. How many constructors are there to create Character Wrapper class Object ?
363 | P a g e
Durgasoft Mr. Ratan
Collections
1) What is the main objective of collections?
2) What are the advantages of collections over arrays?
3) Collection frame work classes are present in which package?
4) What is the root interface of collections?
5) List out implementation classes of List interface?
6) List out implementation classes of set interface?
7) List out implementation classes of map interface?
8) What is the difference between heterogeneous and homogeneous data?
9) What do you mean by legacy class can you please tell me some of the legacy classes present in
collection framework?
10) What are the characteristics of collection classe?
11) What is the purpose of generic version of collection classes?
12) What is the difference between general version of ArrayList and generic version of ArrayList?
13) What is purpose of generic version of ArrayList & arrays?
14) How to get Array by using ArrayList?
15) What is the difference betweenArrayList and LinkedList?
16) How to decide when to use ArrayList and when to use LinkedList?
17) What is the difference between ArrayList & vector?
18) How can ArrayList be synchronized without using vector?
19) Arrays are already used to hold homogeneous data but what is the purpose of generic version of
Collection classes?
20) What is the purpose of RandomAccess interface and it is marker interface or not?
21) What do you mean by cursor and how many cursors present in java?
22) How many ways are there to retrieve objects from collections classes what are those?
23) What is the purpose of Enumeration cursor and how to get that cursor object?
24) By using how many cursors we are able to retrieve the objects both forward backward direction
and what are the cursors?
25) What is the purpose of Iterator and how to get Iterator Object?
26) What is the purpose of ListIterator and how to get that object?
27) What is the difference between Enumeration vs Iterator Vs ListIterator?
364 | P a g e
Durgasoft Mr. Ratan
28) We are able to retrieve objects from collection classes by using cursors and for-each loop what is
the difference?
29) All collection classes are commonly implemented some interfaces what are those interfaces?
30) What is the difference between HashSet & linkedHashSet?
31) all most all collection classes are allowed heterogeneous data but some collection classes are not
allowed can you please list out the classes?
32) What is the purpose of TreeSet class?
33) What is the difference between Set & List interface?
34) What is the purpose of Map interface?
35) What do you mean by entry.
36) What is the difference between HashMap & LinkedHashMap?
37) What is the difference between comparable vs Comparator interface?
38) What is the difference between TreeSet andTtreeMap?
39) What is the difference between HashTable and Properties file key=value pairs?
40) What do you mean by properties file and what are the advantages of properties file?
41) Properties class present in which package?
42) What is the difference between collection & collections?
Garbage Collector
Enumeration
1) What is the purpose Enumeration?
2) How to declare enum?
3) enum constants are by default?
4) One enum is able extends other enum or not?
365 | P a g e
Durgasoft Mr. Ratan
Nested classes
1) What are the advantages of inner classes?
2) How many types of nested class?
3) How many types of inner classes?
4) What do you by static inner classes?
5) The inner class is able to access outer class private properties or not?
6) The outer class is able to access inner classes properties& methods or not?
7) How to create object inner class and outer class?
a. Class Outer
{ class Inner{ }
}
8) For the inner classes compiler generates .class files or not? If generates write the name of above
inner class .class file name ?
9) The outer class object is able to call inner class properties & methods or not?
10) The inner class object is able to call outer class properties and methods or not?
11) What is the difference between normal inner classes and static inner classes?
12) What do you mean by anonymous inner classes?
13) What do you mean by method local inner classes?
14) Is it possible to create inner class object without outer class object?
15) Java supports inner method concept or not ?
16) Is it possible to declare main method inside inner classes?
17) Is it possible to declare constructors inside inner classes?
18) If outer class variables and inner class variables are having same name then hoe to represent
outer class variables and how to represent inner class variables?
19) Is it possible to declare same method in both inner class and outer class?
20) Is it possible to declare main method inside outer classes?
File IO
1. What is the purpose of java.io package?
2. What do you mean by stream?
3. What do you mean by channel and how many types of channels present in java?
366 | P a g e
Durgasoft Mr. Ratan
Multhreading
1. What do you mean by Thread?
2. What do you mean by single threaded model?
3. What is the difference single threaded model and multithreaded model?
4. What do you mean by main thread and what is the importance?
5. What is the difference between process and thread?
6. How many ways are there to create thread which one prefer?
7. Thread class& Runnable interface present in which package?
8. Runnable interface is marker interface or not?
9. What is the difference between t.start() & t.run() methods where t is object of Thread class?
10. How to start the thread?
11. What are the life cycle methods of thread?
12. Run() method present in class/interface ?Is it possible to override run() method or not?
13. Is it possible to override start method or not?
14. What is the purpose of thread scheduler?
15. Thread Scheduler fallows which algorithm?
16. What is purpose of thread priority?
17. What is purpose of sleep() & isAlive() & isDemon() & join() & getId() & activeCount() methods?
18. Jvm creates stack memory one per Thread or all threads only one stack?
19. What is the thread priority range & how to set priority and how to get priority?
20. What is the default name of user defined thread and main thread? And how to set the name
and how to get the name?
367 | P a g e
Durgasoft Mr. Ratan
Internationalization
1) What is the main importance of I18n?
2) What is the purpose of locale class?
3) What is the format of the properties file?
4) Local class present in which package?
5) What do you mean by properties file and what it contains?
6) What is the purpose of ResourceBundle class and how to create object?
7) How to convert different languages characters into Unicode characters?
8) What is the command used to convert different language characters into Unicode characters?
9) Who decides properties file executions?
10) What is the method used to get values from properties file?
11) By using which classes we are achieving i18n?
12) What is the default Locale and how to get it?
13) Is it possible to create your own locale?
14) What is purpose of DateFormat class and it is preset in which package?
15) What are the DataFormat Constantans’ to print Date & time?
16) How to print date in different Locales?
17) How to print time in different locales?
18) How to print both date & time by using single method?
19) What do you mean by factory method? getBundle() is factory method or not?
20) How to get particular locale language & country?
by Mr. Ratan.
368 | P a g e