Corejava by Ratan_4
Corejava by Ratan_4
Ratan
1|P ag e
Durgasoft Mr.Ratan
CORJAVA
1. Introduction
Basics of java
First application
2. Java class
Variables
Methods
Constructors
Instance blocks
Static blocks
3. Oops
Class
Object
Inheritance
Polymorphism
Abstraction
Encapsulation
4. Packages
Predefined packages
User defined packages
Importing packages
Project modules
Source file declaration
5. Modifiers
Public , private , protected
,abstract,final,static,native,strictfp,volatile,transient,synchronized, (11 modifiers )
6. Interface
Interface declarations
Marker interface
Adaptor classes
Interface vs inheritance
7. Garbage Collector
8. Flow control statements & operators
If,if-else,else-if,switch
For,while,do-while
9. String manipulations
String
StringBuffer
StringBuilder
StringTokenizer
2|P ag e
Durgasoft Mr.Ratan
10. Wrapperclass
Data types vs Wrapper classes
All 8 wrapper classes explanations
Auto boxing vsAutounboxing
All possible conversions
toStirng() , parseXXX(),valueOf(), XXXValue().
3|P ag e
Durgasoft Mr.Ratan
Introduction
Declaration of Arrays
Arrays storing Object data & primitive data.
16. Generics.
Type safety.
17. Collection framework
Introduction about Arrays
Advantages of collection over arrays
Collection vs Collections
Key interfaces of Collections
Characteristics of Collection framework classes
Information about cursors
Introduction about Map interface
List interface implementation classes
Set interface implementation classes
Map interface implementation classes
Comparable vs comparator
Sorting mechanisms of Collection objects
18. Enumeration
Introduction
Advantages of enumeration
Enum vs enum
Difference between enum vs class
19. Assertions
20. INTERNATIONALIZATION (I18N)
Design application to support dif country languages
Local class
ResourceBundle
Date in different formats
Info about properties file
21. Regular Expressions.
22. JVM architecture
What is JVM
Structure of the JVM
Components of JVM
23. Annotations
Introduction
Advantages of annotations
Different annotations working
24. Networking
Introduction
Socket and ServerSocket
URL info
Client-Server programming
4|P ag e
Durgasoft Mr.Ratan
5|P ag e
Durgasoft Mr.Ratan
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
6|P ag e
Durgasoft Mr.Ratan
Adv java
Hibernate structs
Web services,tools(ant,maven,svn…..)
Spring
Java keywords:-(50)
Data Types do source-file: throw
byte continue class throws
short (10) extends (5)
int interface
long Predefined constants implements 1.5 version:-
float package enum
double import assert
char (6) (2)
boolean method-level:-
(8) void True, false, null (3) unused:-
return goto
Flow-Control:- (2) const
if (2)
else Object-level:-
switch new
case this
default super Exception handling:-
break instanceof try
for (4) catch
while finally
7|P ag e
Durgasoft Mr.Ratan
8|P ag e
Durgasoft Mr.Ratan
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.
Java uses c,cpp syntaxes mainly hence who knows C,CPP for that java is simple
language.
2. Object Oriented:-
Java is object oriented technology because it is representing total data of the class in
the form of object.
The languages which are support object,class,Inheritance,Polymorphism,
9|P ag e
Durgasoft Mr.Ratan
When we compile the application by using one operating system (windows) that Compiled file
can execute in all operating systems(Windows,Linux,Mac…etc) this behavior is called platform
independency.
Example :- java,Ruby,Scala,PHP …etc
4. Architectural Neutral:-
Java tech applications compiled in one Architecture/hardware (RAM, Hard Disk) and that
Compiled program runs on any architecture(hardware) is called Architectural Neutral.
5. Portable:-
In Java 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 good at two main areas that technology is robust technology.
a. Exception Handling
b. Memory Allocation
Java is providing predefined support to handle the exceptions.
Java provides Garbage collector to support memory management.
7. Secure:-
To provide implicit security Java provides 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.securitypackage.
8. Dynamic:-
Java is dynamic technology it follows dynamic memory allocation(at runtime the
memory is allocated).
9. Distributed:-
By using java it is possible to develop distributed applications & to develop distributed
applications java uses RMI,EJB…etc
10. Multithreaded: -
Thread is a light weight process and a small task in large program.
In java it is possible to create user thread & it possible to execute simultaneously is called
multithreading.
10 | P a g e
Durgasoft Mr.Ratan
The main advantage of multithreading is it shares the same memory & threads are
important at multimedia, gaming, web application.
11. High Performance:-
If any technology having features like Robust, Security, Platform Independent, Dynamic and
so on then that technology is high performance.
Types of java applications:-
1. Standalone applications:
It is also known as window based applications or desktop applications.
This type of applications must install in every machine like media player, antivirus …etc
By using AWT & Swings we are developing these type of applications.
This type of application does notrequired client-server architecture.
2. Web applications:
a. The applications which are executed at server side those applications are called web
applications like Gmail, facebook ,yahoo…etc .
b. All applications present in internet those are called web-applications.
c. The web applications required client-server architecture.
i. Client : who sends the request.
ii. Server : it contains application & it process the app & it will generate response.
iii. Database : used to store the data.
d. To develop the web applications we are using servlets,structs,spring…etc
3. Enterprise applications:-
It is a business application &most of the people use the term it I big business application.
Enterprise applications are used to satisfy the needs of an organizationrather than individual
users. Such organizations are business, schools, government …etc
An application designed for corporate use is called enterprise application.
An application in distributed in nature such as banking applications.
All j2ee &EJB is used to create enterprise application.
4. Mobile applications:-
The applications which are design for mobile platform are called mobile applications.
We are developing mobile applications by sing android,IOS,j2me…etc
There are three types of mobile applications
o Web-application (gmai l ,online shopping,oracle …etc)
o Native (run on device without internet or browser)ex:phonecall,calculator,alaram,games
These are install from application store& to run these apps internet not required.
o Hybrid (required internet data to launch) ex:whats up,facebook,LinkedIn…etc
These are installed form app store but to run this application internet data required.
5. Distributed applications:-
Software that executes on two or more computers in a network. In a client-server
environment.Application logic is divided into components according to function.
Ex : aircraft control systems,industrial control systems,network applications…etc
Types of software :
The set of instructions that makes the computer system do something.
1) Application software
The program that allows the user to perform particular task.
11 | P a g e
Durgasoft Mr.Ratan
After clicking above link we will get below window then accept license agreement by clinking radio
button then choose the software based on your operating system and processor to download.
12 | P a g e
Durgasoft Mr.Ratan
After installing To check whether the java is installed in your system or not open the command prompt
type javac command.
Process to open command prompt:Start --->run---->open:cmd---->ok
C:\Users\RATAN>javac
Whenever we are getting above information then decide in our system java is installed
but the java is not working.
Why java is not working Reason:-
C:\Users\RATAN>javac
Whenever we are typing javac command on the command prompt operating system will
pickup javac command search for that command,
a) in the internal operating system calls but javac is not available in the internal system calls list.
b) If it not available in internal system calls list thenimmediately it won’t raise any error, it will
search in environmental variables
In above two cases if the javac command is not available then operating system will raise error
message “javac is not recognized as an internal or external command”
To overcome above problem to make eligible javac command operating system set
environmental variables.
The location of javac command is : C:\Program Files\Java\jdk1.7.0\bin
Right click on mycomputer --->properties----->Advanced system setting--->Environment Variables --
User variables--->new----> variable name : path
Variable value : C:\programfiles\java\jdk1.6.0_11\bin;
----->ok---->ok
13 | P a g e
Durgasoft Mr.Ratan
Now the java is working in your system to check open the new command prompt &type javac
command then we will get list of commands then decide in your system java is working.
In your system or your friend system to check java is installed or not open the command prompt
& type javac command
a) If error message displayed java is not working.('javac' is not recognized as an internal or external command)
b) If list of commands are displayed then decide java is working properly.
Steps to Design a First Application:-
Step-1:- Select an Editor.
Step-2:- Write the application.
Step-3:- save the application.
Step-4:- Compilation Process.
Step-5:- Execution process.
14 | P a g e
Durgasoft Mr.Ratan
Example application:-
import java.lang.System;
import java.lang.String;
class Test //class declaration
{ //class starts
public static void main(String[] args) //program execution starting point
{ //main starts
System.out.println("hi Ratan"); //printing statement
} //main ends
}; //class ends
class A
{
};
class B
{
};
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
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 is allows declaring multiple java classes.
Note: - The source file allowed only one public class, if we are trying to declare multiple public classes
then compiler generate error message.
15 | P a g e
Durgasoft Mr.Ratan
Whenever we are performing compilationthe compiler will check the syntax errors.
If the application contains syntax errors then compiler will generate error message in the form of
compilation error.
If the application does not contains syntax errors then compiler will generate .class
files.(conversion of .java to .class)
Note: - in java .class 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.
16 | P a g e
Durgasoft Mr.Ratan
D:
|-->ratan
|-->Sravya.java
|-->A.java
|-->B.java
|-->C.java
javac A.java one file is compiled(A.java)
javac B.java C.java two files are compiled
javac *.java all files are compiled
Whenever you are executing particular class file then JVM perform fallowing actions.
JVM wills loads corresponding .class file byte code into memory.
After loading .class file JVM calls main method to start the execution process.
In above two cases if the class file or main method is not available then at runtime JVM will generate
error message.
If the main method is not available: “Main method not found in class A, please define the main method”.
If the .class is not available : “Could not find main class”.
Executing all generated .class files based on example given in second step:-
Test class ---> class is loaded & main is present
A class ---> class is loaded but main is not present
B class ---> class is loaded but main is not present
XXX class ---> XXX class is not present
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
17 | P a g e
Durgasoft Mr.Ratan
Note 1: - compiler is translator it is translating .java file to .class where as JVM is also a translator it is
translating .class file to machine code.
Note 2:-Compiler understandable file format is .java file but JVM understandable file format is .class file.
Note 3:- it is possible to compile multiple files at a time but it is possible to execute only one .class file at
a time.
Note 4:- The .java file contains high level language (English) but .class file contains byte code
instructions.
Note 5:- The source is allowed to declaring multiple non-public classes but only one public class.
18 | P a g e
Durgasoft Mr.Ratan
Example-1:-
Java contains 14 predefined packages but the default package in java is java.lang package it
means if we are importing or not by default this package is imported.
In below example importing classes are optional.
class Test
{ public static void main(String[] args)
{ System.out.println("hi ratan");
}
}
Example-2:-
The class contains main method is called Mainclass and java allows 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!");
}
}
19 | P a g e
Durgasoft Mr.Ratan
class Test3
{ public static void main(String[] args)
{ System.out.println("Test3 World!");
}
}
D:\morn11>java Test1 D:\morn11>java Test2 D:\morn11>java Test3
Test1 World! Test2 World! Test3 World!
Class Elements:-
Java is a class based language it means everything we are representing based on class.
The java class contains 5-elements if we know these five elements flow of execution perfectly
then java is very simple language otherwise java is very difficult.
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 }
}
20 | P a g e
Durgasoft Mr.Ratan
Constants:-
While declaring constants all the words are uppercase letters .
Ex: MAX_PRIORITY MIN_PRIORITY NORM_PRIORITY
NOTE:- The coding standards are mandatory for predefined library & optional for user defined library
but as a java developer 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 write the detailed description about application logics to understand the
logics easily.
Comments are very important in real time because today we are developing the application but
that application maintained by some other person so to understand the logics by everyone writes
the comments.
Comments are non-executable code these are ignored at compile time.
3) Documentation Comments:-
By using documentation commentsit possible to prepare API(Application programming
interface) documents.(e will discuss later chapte)
21 | P a g e
Durgasoft Mr.Ratan
Syntax: - /*
*statement-1
*statement-2
*/
Example:-
/*project name:-green project
team size:- 6
team lead:- ratan
*/
class Test //class declaration
{ //class starts
public static void main(String[] args) // execution starting point
{ //main starts
System.out.println("ratan"); //printing statement
}//main ends
};//class ends
Separators in java:-
Symbol name usage
() parentheses used to contains list of parameters & contains expression.
{} braces block of code for class, method, constructors & local scopes.
. period used to separate package names from sub packages. And also
used for separate a variable,method from a reference type.
22 | P a g e
Durgasoft Mr.Ratan
Output: - Sravyainfotech
Core java
Java identifiers:-
Every name in java is called identifier such as,
Class-name
Method-name
Variable-name
2. Java identifiers are case sensitive of course java is case sensitive programming language. The
below three declarations are different & valid.
class Test
{ int NUMBER=10;
int number=10;
int Number=10;
};
3. The identifier should not duplicated& below example is invalid because it contains duplicate
variable name.
class Test
{ int a=10;
23 | P a g e
Durgasoft Mr.Ratan
int a=20;
};
4. In the java applications it is possible to declare all the predefined class names & interfaces names
as a identifier but it is not recommended to use.
class Test
{ public static void main(String[] args)
{ int String=10;
float Exception=10.2f;
System.out.println(String);
System.out.println(Exception);
}
};
Byte :-
Size : 1-byte
MAX_VALUE : 127
MIN_VALUE : -128
Range : -128 to 127
Formula : -2n to 2n-1 -28 to 28-1
24 | P a g e
Durgasoft Mr.Ratan
6 5 4 3 2 1 0 64+32+16+8+4+2=128
2 2 2 2 2 2 2
Note :-
To represent numeric values (10,20,30…etc) use byte,short,int,long.
To represent decimal 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.
Except Boolean and char remaining all data types consider as a signed data types because we can
represent both +ve & -ve values.
Float vs double:-
Float will give 5 to 6 decimal places of accuracy but double gives 14 to 15 places of accuracy.
Float will fallow single precision but double will fallow double precision.
Syntax:- data-type name-of-variable=value/literal;
Ex:- int a=10;
Int ------ Data Type
a ------ variable name
= ------ assignment
10 ------ constant value
; ------ statement terminator
printing variables :-
int a=10;
System.out.println(a); //valid
System.out.println("a"); //invalid
System.out.println('a'); //invalid
Example :-//Test.java
class Test
{ public static void main(String[] args)
{ float f=10.5;
System.out.println(f);
25 | P a g e
Durgasoft Mr.Ratan
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 or perform type casting.
float f =10.5f; //using f constant (valid)
float f =(float)10.5; //using type casting (valid)
variable declarations:
int a=10; ----> integer variable
double d=10.5; ----> double variable
char ch='a'; ----> char variable
boolean b=true; ----> boolean variable
float f=10.5f; ----> float variable
String str=”ratan”; ----> String variable
Note: String is not a data type & it is a class present in java.lang package to represent group
of characters or character array enclosed with in double quotes.
26 | P a g e
Durgasoft Mr.Ratan
Java Variables:-
Variables are used to store the constant values by using these values we are achieving project
requirements.
Variables are also known as fields of a class or properties of a class.
All variables must have a type. You can use primitive types such as int, float, boolean,
etc. Or array type or class type or enum type.
Variable declaration is composed of three components in order,
o Zero or more modifiers.
o The variable type.
o The variable name.
Example : public final int x=100;
27 | P a g e
Durgasoft Mr.Ratan
28 | P a g e
Durgasoft Mr.Ratan
29 | P a g e
Durgasoft Mr.Ratan
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
{ int a=10;
int b=20; // instance variables
static int c=30; static int d=40; //static variables
void m1() //instance method
{ 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
}
};
30 | P a g e
Durgasoft Mr.Ratan
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)
{ 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.
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)
{ 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);
31 | P a g e
Durgasoft Mr.Ratan
Class Vs Object:-
Class is a logical entity it contains logics whereas 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
static int b=20; //static variable
public static void main(String[] args)
{ Test t = new Test();
System.out.println(t.a); //10
System.out.println(t.b); //20
t.a=111; t.b=222;
System.out.println(t.a); //111
System.out.println(t.b); //222
Test t1 = new Test(); //10 222
System.out.println(t1.a); //10
System.out.println(t1.b); //222
t1.b=444;
Test t2 = new Test(); //10 444
System.out.println(t2.b); //444
}
}
32 | P a g e
Durgasoft Mr.Ratan
Usage within the method inside the class. inside the class all
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.
33 | P a g e
Durgasoft Mr.Ratan
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 allocatedduring object creation hence
access the instance members by using object-name (reference-variable).
Method calling Syntax:-
Void m1() { logics here } //instance method
Objectname.instancemethod( ); //calling instance method
Test t = new Test();
t.m1( );
static method:-
static void m1() //static method
{ //body //static area
}
Note: - for the static member’s memory allocated during .class file
loading hence access the static members by using class-name.
Method calling syntax:-
Static void m2() { logics here } //static method
Classname.staticmethod( ); // call static method by using class name
Test.m2( );
34 | P a g e
Durgasoft Mr.Ratan
Method Signature:-
Method-name & parameters list is called method signature.
Syntax:- Method-name(parameter-list)
Example:- m1(int a)
m1(int a,int b)
35 | P a g e
Durgasoft Mr.Ratan
36 | P a g e
Durgasoft Mr.Ratan
Example-4:-
For java methods return type is mandatory otherwise the compilation will generate error
message “invalid method declaration; return type required “.
class Test
{ m1()
{ System.out.println("m1 instance method");
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}
Example-5:-
Inside the 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 message “m1()
is already defined in Test ”(Java class not allowed Duplicate methods)
But It is possible to write two methods with different signature,
void m1()
Void m1(int a) method signatures are different it is method overloading concept.
class Test
{ void m1()
{ System.out.println("m1 instance method");
}
void m1()
{ System.out.println("m1 instance method");
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}
37 | P a g e
Durgasoft Mr.Ratan
Example-6 :-
Declaring the class inside another class is called inner classes, java supports inner classes.
Declaring the methods inside other 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();
}
};
38 | P a g e
Durgasoft Mr.Ratan
39 | P a g e
Durgasoft Mr.Ratan
Example-10 :-
Case 1:- This keyword not required
In below example instance variables and local variables having different names so this
keyword not required.
class Test
{ //instance variables
int a=100;
int b=200;
void add(int i,int j)
{ System.out.println(a+b); //instance variables addition
System.out.println(i+j); //local variables addition
}
public static void main(String[] args)
{ Test t = new Test();
t.add(10,20);
}
}
40 | P a g e
Durgasoft Mr.Ratan
Example-11 :-
In java this keyword is instance variable hence it is not possible to use inside static area.
If we are using this variable inside static context then compiler will generate error
message “non-static variable this cannot be referenced from a static context”.
In the static context it is not possible to use this & super keywords.
class Test
{ int a=100;
static void add(int a)
{ System.out.println(this.a);
}
public static void main(String[] args)
{ Test t = new Test();
t.add(10);
}
}
Compilation error:- non-static variable this cannot be referenced from a static context.
Example-12 :- Conversion of local variables to instacevariables to improve the scope of the variable.
class Test
{ //instance variables
int val1;
int val2;
void values(int val1,int val2)//local variables
{ System.out.println(val1);
System.out.println(val2);
//conversion of local to instance (passing local variables values to instance variables)
this.val1=val1;
this.val2=val2;
}
void add(){ System.out.println(val1+val2); }
void mul(){ System.out.println(val1*val2); }
public static void main(String[] args)
{ Test t = new Test();
t.values(10,20);
t.add();
t.mul();
}
}
41 | P a g e
Durgasoft Mr.Ratan
For java methods return type is mandatory & void represent return nothing.
Methods can have return type primitive such as byte,short,int,long,float….etc OR it can have
object return type like Arrays,String,Objects….etc
If the method is having return type other than void then must return the value by using return
keyword otherwise compiler will generate error message “missing return statement”
Below syntax invalid becausemethod must return int value by using return statement.
int m1()
{ System.out.println("Anushka");
}
The below example is valid because it is returning int value by using return statement.
int m1()
{ System.out.println("Anushka");
return 100;
}
Inside the method we are able to declare only one returnstatement thatstatement must be last
statement of the method otherwise compiler will generate error message “unreachable
statement”.
The below example is invalid because return statement is must be last statement.
int m1()
{ return 100;
System.out.println("Anushka");
}
The below example valid because return statement is last statement.
int m1()
{ System.out.println("Anushka");
return 100;
}
Every method is able to returns the value but holding (storing) that return value is optional, but it
is recommended to hold the return value check the status o the method.
42 | P a g e
Durgasoft Mr.Ratan
class Test
{ int m1(int a,char ch)
{ System.out.println("***m1 method***");
System.out.println(a+"---"+ch);
return 100;
}
boolean m2(String str1,String str2)
{ System.out.println("****m2 method****");
System.out.println(str1+"---"+str2);
return true;
}
static String m3(double d,boolean b)
{ System.out.println("****m3 method****");
System.out.println(d+"---"+b);
return "ratan";
}
public static void main(String[] args)
{ Test t=new Test();
int x = t.m1(10,'a');
System.out.println("m1() return value-->"+x);
boolean b = t.m2("ratan","anu");
System.out.println("m2() return value-->"+b);
43 | P a g e
Durgasoft Mr.Ratan
Example 15 :- Java.util.Scanner
Scanner class present in java.util package and it is introduced in 1.5 versions & it is used to take
dynamic input from the keyboard.
To communicate with system resources use System class & to take input from keyboard
use in variable(in=input).
Scanner s = new Scanner(System.in); //Scanner object creation
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);
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);
s.close(); //used to close the stream
}
}
Case:- The \s represents whitespace.
import java.util.*;
public class Test
{ public static void main(String args[])
{ String input = "7 tea 12 coffee";
Scanner s = new Scanner(input).useDelimiter("\\s");
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close(); }}
44 | P a g e
Durgasoft Mr.Ratan
45 | P a g e
Durgasoft Mr.Ratan
Example 18:- The java class is able to return user defined class as a return value.
class X{};
class Emp{};
class Test
{ X m1()
{ System.out.println("m1 method");
X x = new X();
return x;
}
Emp m2()
{ System.out.println("m2 method");
Emp e = new Emp();
return e;
}
static String m3()
{ System.out.println("m3 method");
return "ratan";
}
public static void main(String[] args)
{ Test t = new Test();
X x1 = t.m1();
Emp e = t.m2();
String str = Test.m3();
}
}
Note: when we print object reference variable it always print hash code of the object (we will discuss later).
Example 19: this keyword representing current class objects.
Java method is able to return current class object in two ways.
1) Creating object & return reference variable.
2) Return this keyword.
In above two approaches 2nd approach is recommended to return the current class object.
class Test
{ Test m1()
{ System.out.println("m1 method");
Test t = new Test();
return t;
}
Test m2()
{ System.out.println("m2 method");
return this;
}
public static void main(String[] args)
{ Test t = new Test();
Test t1 = t.m1();
Test t2 = t.m2();
}
};
46 | P a g e
Durgasoft Mr.Ratan
47 | P a g e
Durgasoft Mr.Ratan
48 | P a g e
Durgasoft Mr.Ratan
CONSTRUCTORS
Class Vs Object:-
Class is a logical entity it contains logics whereas 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 instance factory method.
o By using static factory method
o By using pattern factory method
o By using deserialization….etc
But we are able to declare the class by using class keyword.
New :-
new keyword is used to create object in java.
When we create object by using new operator after new keyword that part is constructor then
constructor execution will be done.
49 | P a g e
Durgasoft Mr.Ratan
Default Constructor:-
Inside the class if we are not declaring at least one constructor then compiler generates zero
argument constructors with empty implementation at the time of compilation.
The compiler generated constructor is called default constructor.
Inside the class default constructor is invisible mode.
To check the default constructor provided by compiler open the .class file code by using java
decompiler software.
50 | P a g e
Durgasoft Mr.Ratan
Example:-
Inside the class if we are declaring at least one constructor (either 0-arg or parameterized) then
compiler won’t generate default constructor.
Inside the class if we are not declaring at least one constructor(either 0-arg or parameterized)
then compiler will generate default constructor.
if we are trying to compile below application the compiler will generate error message
“Cannot find symbol ” because compiler is unable to generate default constructor.
class Test
{ Test(int i)
{ System.out.println("1-arg constructor");
}
Test(int a,int b)
{ System.out.println("2-arg constructor");
}
public static void main(String[] args)
{ Test t1=new Test();
Test t2=new Test(10);
Test t3=new Test(100,200);
}
}
E:\>javac Test.java
Test.java:9: cannot find symbol
Symbol: constructor Test()
Location: class Test
51 | P a g e
Durgasoft Mr.Ratan
Note :-default constructor is zero argument constructor but all zero argument
constructors are not default constructors.
52 | P a g e
Durgasoft Mr.Ratan
Example:-
class Box
{ double height;
double width;
double depth;
};
Box mybox; mybox is the reference to an object of type Box. After executing this line mybox
contains the value null.
mybox = new Box();it creates the Box object and assign to mybox reference type.
Example:-
class Box
{ double height=10;
double width=20;
double depth=30;
void volume()
{ System.out.println(height*width*depth);
}
};
class Test
{ public static void main(String[] args)
{ Box b1 = new Box();
Box b2 = b1;
b1=null;
b2.volume();
//b1.volume(); java.lang.NullPointerException
}
};
In above example both b1 & b2 are pointing to same object. Here b1has been set to null but still
b2 is pointing to the original object.
Note: - When we assign one object reference variable to another object reference variable, you
are not creating a copy of the object we are creating copy of the reference.
53 | P a g e
Durgasoft Mr.Ratan
Advantages of constructors:-
1) Constructors are used to write block of java code that code will be executed
during object creation.
2) Constructors are used to initialize instance variables during object creation.
Example :- default constructor execution process.
class Employee
{ //instance variables
int eid;
String ename;
double esal;
void display()
{ //printing instance variables values
System.out.println("****Employee details****");
System.out.println("Employee name :-->"+ename);
System.out.println("Employee eid :-->"+eid);
System.out.println("Employee sal :-->"+esal);
}
public static void main(String[] args)
{ Employee e1 = new Employee();
e1.display();
}
}
D:\morn11>java Employee
****Employee details****
Employee name :-->null
Employee eid :-->0
Employee sal :-->0.0
Problems in above example:-
In above example during object creation time default constructor is executed with empty
implementation and initial values of instance variables (default values) printed .
In above example Emp object is created but default values are printing hence to overcome
this limitation use user defined constructor to initialize some values to instance variables.
Example 2:- user defined o-argument constructor execution process.
class Employee
{ //instance variables
int eid;
String ename;
double esal;
Employee()//user defined 0-argument constructor
{ //assigning values to instance values during object creation
eid=111;
ename="ratan";
esal =60000;
}
54 | P a g e
Durgasoft Mr.Ratan
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)
{ Employee e1 = new Employee();
e1.display();
}
}
In above example during object creation user provided 0-arg constructor executed used
to initialize some values to instance variables.
Problem in above example:-
In above example when we create object it initializing values to instance variables but
when we create multiple object for every object same 0-argument constructors is executing it
initializing same values for all objects
public static void main(String[] args)
{ Emp e1 = new Emp();
e1.display();
Emp e2 = new Emp();
e2.display();
}
D:\morn11>java Employee
****Employee details****
Employee name :-->ratan
Employee name :-->111
Employee name :-->60000.0
Employee name :-->ratan
Employee name :-->111
Employee name :-->60000.0
55 | P a g e
Durgasoft Mr.Ratan
56 | P a g e
Durgasoft Mr.Ratan
class Test
{ public static void main(String[] args)
{ //a is primitive variable
int a=10;
System.out.println(a);
//t is reference variable
Test t = new Test();
System.out.println(t);
}
}
57 | P a g e
Durgasoft Mr.Ratan
Constructor calling:-
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:-
Call the java methods by uisng method name but 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)
{ new Test();
}
}
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”.
Test()
{ this(10); //current class 1-argument constructor calling
System.out.println("0 arg");
}
Compilation error:-(this keyword not a first statement)
Test()
{ System.out.println("0 arg");
this(10); //current class 1-argument constructor calling
}
58 | P a g e
Durgasoft Mr.Ratan
Example-3:-
1. Constructor calling must be first statement in constructor code it means this keyword must be
first statement in constructor.
2. In java one constructor is able to call only one constructor at a time but not possible to call more
than one constructor.
Compilation error:-
Test()
{ this(100);//1-arg constructor calling
this('g',10);//2-arg constructor calling[compilation error]
System.out.println("0-arg constructor logics");
}
Object creation parts:-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
Example :- By using constructors copy the values of one object to another object.
class Student
{ int sid;
String sname;
int smarks;
Student(int sid,String sname,int smarks)
{ this.sid=sid; this.sname=sname; this.smarks=smarks;
}
Student(Student s) //constructor expected Student object
{ this.sid=s.sid; this.sname=s.sname; this.smarks=s.smarks;
}
void disp()
{ System.out.println("****student Details****");
System.out.println("student name = "+sname);
System.out.println("student id = "+sid);
System.out.println("student mrks = "+smarks);
}
public static void main(String[] args)
{ Student s = new Student(111,"ratan",100);
Student s1 = new Student(s); //constructor is taking Student object
s.disp(); s1.disp();
}
}
59 | P a g e
Durgasoft Mr.Ratan
Constructor chaining :-
One constructor is calling same class constructor is called constructor calling.
We are achieving constructor calling by using this keyword.
Inside constructor we are able to declare only one this keyword that must be first
statement of the constructor.
class Test
{ Test()
{ this(10);
System.out.println("0-arg cons");
}
Test(int i)
{ this(10,20);
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();
}
}
Example:- Assignment
class Student
{ String sname;
int sid;
String college="SSCET";
60 | P a g e
Durgasoft Mr.Ratan
3)Return type Return type not allowed It allows all valid return
Even void. Types(void,int,Boolean…etc)
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
61 | P a g e
Durgasoft Mr.Ratan
Instance Blocks:-
Instance blocks are used to write the logics of projects & these logics 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 constructors are executed just before constructors instance blocks are
executed.
Instance block syntax
{ //logics here }
Example 1:-
class Test
{ //instance block
{ System.out.println("instance block:logics");
}
Test()
{ System.out.println("constructor:logics");
}
public static void main(String[] args)
{ new Test();
}
}
Example 2:-
Inside the class it is possible to declare multiple instance blocks but the execution order is
top to bottom.
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)
{ new Test();
new Test();
new Test(10);
}
}
Example 3:-
62 | P a g e
Durgasoft Mr.Ratan
Instance block execution depends on object creation but not constructor exaction.
In below example two constructors are executing but only one object is crating hence
only one time instance block is executed.
class Test
{ { System.out.println("instance block-1:logics");
}
Test()
{ this(10);
System.out.println("0-arg constructor:logics"); }
Test(int a)
{ System.out.println("1-arg constructor:logics");
}
public static void main(String[] args)
{ new Test();
}
}
E:\>java Test
instance block-1:logics
1-arg constructor:logics
0-arg constructor:logics
Example 4:-
Case 1:-
When we declare instance block & instance variable the execution order is top to bottom.
In below example instance block is declared first so instance block is executed first.
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)
{ new Test();
}
}
D:\morn11>java Test
instance block
m1() method called by variable
case 2;-
When we declare instance block & instance variable the execution order is top to bottom.
In below example instance variable is declared first so instance block is executed first.
63 | P a g e
Durgasoft Mr.Ratan
class Test
{ int a=m1(); //instance varaibles
int m1()
{ System.out.println("m1() method called by variable");
return 100;
}
{ System.out.println("instance block");
}
public static void main(String[] args)
{ new Test();
}
}
D:\morn11>java Test
m1() method called by variable
instance block
Example-5 :-
Instance blocks are used to initialize instance variables during object creation but just
before constructor execution.
In java it is possible to initialize the values in different ways
o By using constructors
o By using instance blocks
o By using methods
o By using setter methods……..…etc
class Emp
{ int eid;
String ename;
//instance block initializing values
{ ename="ratan";
eid=111;
}
//constructor initializing values
Emp()
{ ename="anu";
eid=222;
}
//method initializing values
void assign()
64 | P a g e
Durgasoft Mr.Ratan
{ ename="aruna";
eid=333;
}
void disp()
{ System.out.println("****Employee Details****");
System.out.println("emp id="+eid);
System.out.println("emp name="+ename);
}
public static void main(String[] args)
{ Emp e = new Emp();
e.disp();
}
};
E:\>java Emp
****Employee Details****
emp id=222
emp name=anu
static block:-
Static blocks are used to write the logics of project that logics are executed during .class
file loading time.
In java .class file is loaded only one time hence static blocks are executed once per class.
Static block syntax,
static
{ //logics here
}
Note : instance blocks execution depends on object creation but static blocks
execution depends on .class file loading.
Example-1 :-
class Test
{ static
{System.out.println("static block");
}
public static void main(String[] args)
{
}
}
Example-2 :-
65 | P a g e
Durgasoft Mr.Ratan
Inside the class it is possible to write multiple static blocks but the execution is top to
bottom.
class Test
{ //static blocks declaration
static{ System.out.println("static block-1");}
static{System.out.println("static block-2");}
//instance blocks declaration
{ System.out.println("instance block-1"); }
{ System.out.println("instance block-2"); }
//constructor declaration
Test()
{ System.out.println("0-arg constructor");
}
Test(int a)
{ System.out.println("1-arg constructor");
}
public static void main(String[] args)
{ new Test();
new Test(10);
}
}
Example-4 :- To execute static blocks inside the class main() method is mandatory or optional.
66 | P a g e
Durgasoft Mr.Ratan
class Test
{ static
{System.out.println("static block");
}
}
When we execute above code up to 1.5 version the code is compiled & executed it will
generate output.
Note : Based on above point up to 1.5 version it is possible to print some statements in output
console without using main method inside the class.
When we execute the above code from 1.6 version onwards the code is not compiled it will
generate compilation error.
Note:- based on above point from 1.6 version onwards it is not possible to print some statements
in output console without using main method inside the class.
Example-5:-
When we execute the .class file manually then to execute static blocks inside the class main() method
mandatory.
When we load the .class file into memory programmatically then to execute the static blocks main()
method is optional.
In below example both files must present in same folder (same location).
67 | P a g e
Durgasoft Mr.Ratan
}
public static void main(String[] args) throws Exception
{ Class c = Class.forName("Demo");
Demo d = (Demo)c.newInstance();
d.m1();
}
}
E:\>java Test
Test class static blocks
Demo class static block
Demo class m1 method
To load the .class file into memory use forName() method & it is a static method of Classclass.
To check the return type & modifiers & arguments check the predefined support by using javap
command.
E:\>javap java.lang.Class
public static Class forName(String class-name) throws java.lang.ClassNotFoundException;
forName() method loads .class file into memory and it return type is class pointing to loaded class.
To created the object for loaded class use newInstance() method & it is a instance method present in
Class class.
public Object newInstance() throws java.lang.InstantiationException, java.lang.IllegalAccessException;
If is taking condition that condition must be Boolean condition. Otherwise compiler will
generate error message.
The curly brasses are optional but without it are possible to take only one statement except
initialization.
68 | P a g e
Durgasoft Mr.Ratan
Example-1:-
class Test
{ public static void main(String[] args)
{ int a=10,b=20;
if (a<b)
{ System.out.println("if body / true body");
}
else
{ System.out.println("else body/false body ");
}
}
}
Example -2:- For the if the condition it is possible to provide Boolean values.
class Test
{ public static void main(String[] args)
{ if (true)
{ System.out.println("true body");
}
else
{ System.out.println("false body");
}
}
}
Example-3:-in c-language 0-false & 1-true but these conventions 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");
}
}
}
Example-4:-
class Test
{ public static void main(String[] args)
{ if (true)
System.out.println("true body");
else
System.out.println("false body");
69 | P a g e
Durgasoft Mr.Ratan
}
}
Switch statement:-
Switch statement is used to declare multiple selections.
Inside the switch It is possible to declare any number of cases but one default case.
Switch is taking the argument, the allowed arguments are
o Byte,short,int,char (primitives) 1.4 version
o Byte, Short,Inegert,Character,enum(1.5 version)
o String(1.7 version).
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).
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 : statements;
break;
case label2 : statements;
break;
| |
| |
default : statements;
break;
}
Example-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;
case 30:System.out.println("samantha"); break;
default:System.out.println("ubanu"); break;
}
}
}
Example-2:Inside the switch the case labels must be unique; if we are declaring duplicate case labels
the compiler will raise compilation error “duplicate case label”.
class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{ case 10:System.out.println("anushka"); break;
70 | P a g e
Durgasoft Mr.Ratan
Example-3:Inside the switch for the case labels it is possible to provide expressions(10+10+20 , 10*4 , 10/2).
class Test
{ public static void main(String[] args)
{ int a=100;
switch (a)
{ case 10+20+70:System.out.println("anushka"); break;
case 10+5:System.out.println("nazriya"); break;
case 30/6:System.out.println("samantha"); break;
default:System.out.println("ubanu"); break;
}
}
}
Example-4:- Inside the switch the case label must be constant values. If we are declaring variables
as a case labels the compiler will show compilation error “constant expression required”.
class Test
{ public static void main(String[] args)
{ int a=10,b=20;
switch (a)
{ case a:System.out.println("anushka"); break;
case b:System.out.println("nazriya"); break;
default:System.out.println("ubanu"); break;
}
}
}
71 | P a g e
Durgasoft Mr.Ratan
}
};
Example 7:- inside the switch both cases and default Is optional.
public class Test
{ public static void main(String[] args)
{ int a=10;
switch(a)
{
}
}
}
Example -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");
}
}
}
72 | P a g e
Durgasoft Mr.Ratan
}
}
};
Example -11:-
Inside the switch statement beak is optional.
If we are not providing break statement then from the matched case onwards up to break
statement will be executed, if there is no break statement then end of the switch will be
executed. This situation is called as fall though inside the switch case.
class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{ case 10:System.out.println("10");
case 20:System.out.println("20");
case 40:System.out.println("40"); break;
default: System.out.println("default"); break;
}
}
};
Example-12:- inside the switch the case label must match with provided argument data type
otherwise compiler will raise compilation error “incompatible types”.
class Test
73 | P a g e
Durgasoft Mr.Ratan
Example-13:-inside the switch we are able to declare the default statement at 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");
}
}
};
Example -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)
74 | P a g e
Durgasoft Mr.Ratan
{ case 126:System.out.println("20");
case 127:System.out.println("30");
case 128:System.out.println("40");
default:System.out.println("default");
}
}
};
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;
}
1 2 5 4 7
for (initialization ;condition ;increment/decrement )
{
Body; 3 6
}
With out for loop By using for loop
class Test class Test
{ public static void main(String[] args) {public static void main(String[] args)
{ System.out.println("ratan"); {for (int i=0;i<5;i++)
System.out.println("ratan"); { System.out.println("Ratan");
System.out.println("ratan"); }
System.out.println("ratan"); }
System.out.println("ratan"); }
}
};
75 | P a g e
Durgasoft Mr.Ratan
Example 3:- compilation error more than one Ex :-declaring two variables are possible.
initialization not possible. class Test
class Test {public static void main(String[] args)
{public static void main(String[] args) { for (int i=0,j=0;i<10;i++)
{ for (int i=0,double j=10.8;i<10;i++) {System.out.println("Rattaiah");
{System.out.println("Rattaiah"); }
} }
} }
}
Increment/decrement:-
Example-1:- Inside the for loop increment/decrement part is optional.
class Test
{ public static void main(String[] args)
{ for (int i=0;i<10;)
{ System.out.println("Rattaiah");
}
}
}
76 | P a g e
Durgasoft Mr.Ratan
Example 2:- Instead of increment/decrement it is possible to take the any number of SOP() statements
and each and every statement is separated by comma(,).
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++;
}
}
}
Example-3 :-
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');
}
}
};
Note : Inside the for loop each and every part is optional.
for(;;)------------represent infinite loop because the condition is always true.
Unreachable statement:-
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("ratan"); { System.out.println("ratan");
} }
System.out.println("rest of the code"); System.out.println("rest of the code");
} }
} }
Note:-
When you provide the condition even thought that condition is represent infinite loop compiler
is unable to find unreachable statements,(because that compiler is thinking that condition may fail).
When you provide Boolean value as a condition then compiler is identifying unreachable
statement because compiler knows that condition never change.
77 | P a g e
Durgasoft Mr.Ratan
While loop:-
Syntax:- while (condition) //condition must be Boolean & mandatory.
{ body; }
Example-1 :-
class Test
{ public static void main(String[] args)
{ int i=0;
while (i<10)
{ System.out.println("rattaiah");
i++;
}
}
}
Syntax:- do
{//body of loop
} while(condition);
Example-1:-
class Test
public static void main(String[] args)
{ int i=0;
do
{ System.out.println("rattaiah");
i++;
}while (i<10);
}
}
78 | P a g e
Durgasoft Mr.Ratan
Example-3 :-
class Test
{ public static void main(String[] args)
{ int i=0;
do
{ System.out.println("rattaiah");
}while (false);
System.out.println("Sravyainfotech");
}
}
Transfer statements:-
By using transfer statements we are able to transfer the flow of execution from one position to
another position.
o Break , Continue , Return, Try
break:-
Break is used to stop the execution. And is possible to use the break statement only two areas.
a. Inside the switch statement.
b. Inside the loops.
if we are using any other place the compiler will generate compilation error message ” break
outside switch or loop”.
79 | P a g e
Durgasoft Mr.Ratan
}
}
Example :-if we are using break outside switch or loops the compiler will raise compilation error “break
outside switch or loop”
class Test
{ public static void main(String[] args)
{ if (true)
{ System.out.println("ratan");
break;
System.out.println("nandu");
}
}
};
Example :-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);
}
}
}
80 | P a g e
Durgasoft Mr.Ratan
Example :-
Object : Car
State : gear,speed,color…etc
Behavior : current speed,current gear,Accelarate…etc
Identity : car number
Object : house
State : location
Behavior : doors open/close.
Identity : house no
Inheritance:-
1. The process of acquiring properties (variables) &methods (behaviors) from one class to another
class is called inheritance.
2. We are achieving inheritance conceptby using extends keyword.Inheritance is also known as is-a
relationship.
3. Extends keyword is providing relationship between two classes..
4. The main objective of inheritance is code extensibility whenever we are extendingthe class
automatically code is reused.
5. In inheritance one class providing properties & another class is acquiring the properties.
6. In inheritance parent class is giving properties &Child is acquiring properties from Parent.
81 | P a g e
SravyaInfotech Mr. Ratan
Note: - To reduce length of the code and redundancy of the code & to improve re-usability of
code sun people introduced inheritance concept.
Important points:-
class A
{ }
class B extends A
{ }
class C extends B
{ }
1) in java if we are extending the class then it will be parent class , if we are not extending the
class then object class will become parent class.
2) In above example A class is direct child class of object & B,C classes are indirect child classes
of object.it represent in java every class is child of object either directly(A) or indirectly(B,C).
3) The root class of all java classes is “object” class.
82 | P a g e
SravyaInfotech Mr. Ratan
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 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.
83 | P a g e
SravyaInfotech 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.
Hierarchical inheritance :-
More than one sub class is extending single Parent is called hierarchical inheritance.
84 | P a g e
SravyaInfotech Mr. Ratan
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 inheritances 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 Parent1
{ void money() {System.out.println("parent1 money");}
};
class Parent2
{ void money() {System.out.println("parent2 money");}
};
class Child extends Parent1,Parent2
{ public static void main(String[] args)
{ Child c = new Child();
c.money(); //ambiguity problems
}
};
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 modifier.
If a parent class declared as final we can’t create sub class for that class.
final class Parent
{ }
class Child extends Parent
{ }
compilation error:- cannot inherit from final Parent
85 | P a g e
SravyaInfotech Mr. Ratan
Instanceof operator:-
It is used check the type of the object and itreturns Boolean value as a return value.
Syntax:- reference-variable instanceof class-name;
To use the instanceof operator the class name & reference variable must have some relationship
either parent to child or child to parent otherwise compiler will generate error message
“inconvertible types”.
If the relationship is child to parent it returns true& the relationship is parent to child it return
false.
Example :-
class Animal{ };
class Dog extends Animal{ };
class Test
{ public static void main(String[] args)
{ Test t = new Test();
Animal a = new Animal();
Dog d = new Dog();
Object o = new Object();
System.out.println(d instanceof Animal); //true
System.out.println(a instanceof Object); //true
System.out.println(a instanceof Dog); //false
System.out.println(t instanceof Object); //true
System.out.println(o instanceof Animal); //false
//System.out.println(t instanceof Animal); compilation error:inconvertible types
}
}
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:-
In below example student uses Teacher class object services.
class Teacher
{ void course()
{ System.out.println("corejava by ratan");
}
};
class Student
{ public static void main(String[] args)
{ Teacher t = new Teacher();
t.course();
}
};
86 | P a g e
SravyaInfotech Mr. Ratan
Aggregation:-
Class A has instance of class B is called aggregation.
Class A can exists without presence of class B . a university can exists without chancellor.
Take the relationship between teacher and department. A teacher may belongs to multiple
departments hence teacher is a part of multiple departments but if we delete department object
teacher object will not destroy.
Example:-
Address.java
class Address
{ //instance variables
int dno;
String state;
String country;
Address(int dno,String state,String country) //local variables
{ //conversion process
this.dno=dno;
this.state= state;
this.country = country;
}
};
Heroin.java:
class Heroin
{ String hname;
int hage;
Address addr; //reference of address class [dno,state,country]
Heroin(String hname,int hage,Address addr)
{ //conversion process
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);
System.out.println("heroin address-->"+addr.country+" "+addr.state+" "+addr.hno)
}
public static void main(String[] args)
{ Address a1 = new Address("india","banglore",111);
Heroin h1 = new Heroin("anushka",30,a1);
h1.display();
Address a2 = new Address("US","california",333);
Heroin h2 = new Heroin("AJ",40,a2);
h2.display();
87 | P a g e
SravyaInfotech Mr. Ratan
}
}
The above Project level main method code:-
public static void main(String[] args)
{ new Heroin("anushka",30,new Address("india","banglore",111)).display();
new Heroin("AJ",40,new Address("US","california",333)).display();
}
Example:-
Test1.java:- Test2.java:- Test3.java:-
class Test1 class Test2 class Test3
{ 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;
} } }
}; }; };
MainTest.java:-
class MainTest
{ //instance variables
Test1 t1;
Test2 t2;
Test3 t3;
MainTest(Test1 t1 ,Test2 t2,Test3 t3)//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');
MainTest main = new MainTest(t,tt,ttt);
main.display();
//new MainTest(new Test1(10,20),new Test2(true,false),new Test3('a','b'));
}
};
88 | P a g e
SravyaInfotech Mr. Ratan
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
{ this.m1=m1; this.m2=m2; this.m3=m3;
}
};
student.java
class Student
{ 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);
Student s1 = new Student(m1,"ratan",111);
s1.display();
//new Student(new Marks(10,20,30),"ratan",111).display(); project code
Marks m2 = new Marks(100,200,300);
Student s2 = new Student(m2,"anu",222);
s2.display();
//new Student(new Marks(100,200,300),"anu",222).display(); project code
}
}
89 | P a g e
SravyaInfotech Mr. Ratan
Object delegation:-
The process of sending request from one object to another object is called object delegation.
Example :-
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();
}
};
Super keyword:-
“this” keyword is used to represent current class object& “super” keyword is used to represent
super class object.
1. Super class variables.
2. Super class methods.
3. Super class constructors.
4. Super class instance blocks.
5. Super class static blocks.
90 | P a g e
SravyaInfotech Mr. Ratan
class Parent
{ Parent() {System.out.println("parent 0-arg constructor");}
};
class Child extends Parent
{ Child()
{ this(10); //current class 1-arg constructor calling
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ super(); //super class 0-arg constructor calling
System.out.println("child 1-arg constructor--->"+a);
}
public static void main(String[] args)
{ new Child();
}
};
91 | P a g e
SravyaInfotech Mr. Ratan
Example-2:-
Inside the constructor super keyword must be first statement otherwise compiler
generates error message “call to super must be first line in constructor”.
No compilation error:-
Child()
{ this(10); // (this must be first line)
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ super(); //(super must be first line)
System.out.println("child 1-arg constructor--->"+a);
}
Compilation Error:-
Child()
{ System.out.println("Child 0-arg constructor");
this(10); //compilation error
}
Child(int a)
{ System.out.println("child 1-arg constructor--->"+a);
super(); //(compilation Error)
}
Example-3:-
Inside the constructor it is possible to use either this keyword or super keyword but,
Two super keywords are not allowed.
Two this keywords are not allowed.
Both super & this keyword also not allowed.
Compilation Error:-
Child()
{ this(10);
super();
System.out.println("Child 0-arg constructor");
}
Child()
{ super(10);
super();
System.out.println("Child 0-arg constructor");
}
Child()
{ this(10);
this();
System.out.println("Child 0-arg constructor");
}
92 | P a g e
SravyaInfotech Mr. Ratan
Example-4:-
In below example parent class default constructor is executed that is provided by compiler.
class Parent
{ // default constructor
};
class Child extends Parent
{ Child()
{ super()
System.out.println("Child 0-arg constructor");
}
public static void main(String[] args)
{ new Child();
}
};
D:\>java Child
Child 0-arg constructor
Example-5:-
1. Inside the constructorweather it is a 0-argument or parameterized if we are not declaring super
or this keyword then compiler generate super keyword at first line of the constructor.
2. The compiler generated super keyword is always 0-arg constructor calling.
class Parent
{ Parent() { System.out.println("parent 0-arg constructor"); }
};
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)
{ new Child();
}
};
D:\>java Child
parent 0-arg constructor
Child 0-arg constructor
93 | P a g e
SravyaInfotech Mr. Ratan
Example-6:-
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
System.out.println("Child 0-arg constructor");
}
public static void main(String[] args)
{ new Child();
}
};
Example-7:-
In below compiler generate default constructor and inside that default constructor super
keyword is generated.
Application code before compilation:- ( .java ) Application code after compilation:- ( .class )
class Parent class Parent
{ Parent() { { Parent()
System.out.println("parent 0-arg cons"); { System.out.println("parent 0-arg cons");
} }
}; };
class Child extends Parent class Child extends Parent
{ public static void main(String[] args) { /* below code is generated by compiler
{ new Child(); Child()
} { super();
}; } */
public static void main(String[] args)
{ new Child();
}
};
Example-8 :-
In below example in Test class 0-argument constructor compiler generate super keyword it
execute parent class(Object) default constructor.
class Test extends Object
{ Test()
{ // super(); generated by compiler
System.out.println("Test class constructor");
}
public static void main(String[] args)
{ new Test();
}
};
94 | P a g e
SravyaInfotech Mr. Ratan
Example-9:-
In below example in child class 1-argument & 0 argument constructors compiler generate super
keyword hence parent class 0-argument constructor will be executed.
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)
{ new Child();
new Child(10);
}
};
Example-10:-
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(); }
};
95 | P a g e
SravyaInfotech Mr. Ratan
96 | P a g e
SravyaInfotech Mr. Ratan
class Parent
{ static{System.out.println("parent static block");} //static block
{System.out.println("parent instance block");} //instance block
};
class Child extends Parent
{ static{System.out.println("child static block");} //static block
{System.out.println("child instance block");} //instance block
public static void main(String[] args)
{ new Child();
new Child();
}
};
E:\>java Child
parent static block
child static block
parent instance block
child instance block
parent instance block
child instance block
Example-2:-
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()
{ System.out.println("child class 0-arg cons");
}
static {System.out.println("child class static block");}
public static void main(String[] args)
{ new Child();
}
};
97 | P a g e
SravyaInfotech Mr. Ratan
Example-3:-
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.
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);
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();
Child c = new Child();
Child c1 = new Child(100);
}
};
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
child instance block
Child 2-arg cons
Child 1-arg cons
98 | P a g e
SravyaInfotech Mr. Ratan
99 | P a g e
SravyaInfotech Mr. Ratan
Polymorphism:-
The ability to appear in more forms is called polymorphism.
One thing can exhibits more than one form is called polymorphism.
One functionality with different actions is called polymorphisum.
One person with different debaviours is called polymorphisumk.
Polymorphism is a Greek word poly means many and morphism means forms.
b. Same method name & same number of arguments but different data types.
void m1(int a){}
void m1(char ch){}
2) To achieve overloading concept one java class sufficient.
3) It is possible to overload any number of methods in single java class.
Example:-
class Test
{ //below three methods are overloaded methods.
void m1(int i)
{ System.out.println("int-argument method");
}
void m1(int i,int j)
{ System.out.println("int,int argument method=");
}
void m1(char ch)
{ System.out.println("char-argument method");
}
public static void main(String[] args)
{ Test t = new Test();
t.m1(10);
t.m1(10,20);
t.m1('a');
}
}
100 | P a g e
SravyaInfotech Mr. Ratan
Example:-
In method overloading it is possible to have different data types for overloaded method.
While overloading the methods check the signature(methodname+parameters) of the method
but not return type.
class Test
{ //below two methods are overloaded methods
double m1(int a,int b)
{ System.out.println("int,int arguments method");
return 20.5;
}
int m1(float f)
{ System.out.println("float argument method");
return 100;
}
public static void main(String[] args)
{ Test t=new Test();
double d = t.m1(10,20);
System.out.println("return type="+d);
int x = t.m1(10.5f);
System.out.println("return type="+x);
}
}
101 | P a g e
SravyaInfotech Mr. Ratan
Example:-
class Test
{ 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);
}
void sum(int a,long b)
{ System.out.println("int,long arguments method");
System.out.println(a+b);
}
void sum(long a,int b)
{ System.out.println("long,int arguments method");
System.out.println(a+b);
}
public static void main(String[] args)
{ Test t=new Test();
t.sum(1,2);
t.sum(10L,20L);
t.sum(100,200L);
t.sum(1000L,2000);
}
}
Types of overloading:-
There are three types of overloading in java,
a. Method overloading explicitly by the programmer
b. Constructor overloading
c. Operator overloading implicitly by the JVM(‘+’ addition& concatenation)
Constructor Overloading:-
If the class contains more than one constructors with same name but different arguments or
same number of arguments with different data types those constructors are called overloaded
constructors.
a. Same constructor name but different number of arguments.
Test(int a){ } //assume Test is java class
Test(int a,int b){ }
b. Same constructor name & same number of arguments but different data types.
Test(int a){ }
Test(char ch){ }
102 | P a g e
SravyaInfotech Mr. Ratan
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("char,int argument constructor");
}
Test(char ch)
{ System.out.println("char argument constructor");
}
public static void main(String[] args)
{ new Test();
new Test(10);
new Test('a',100);
new Test('r');
}
}
Operator overloading:-
One operator with different behaviors is called Operator overloading .
Java is not supporting operator overloading but only one overloaded in java language is ‘+’.
If both operands are integer then “+” performs addition.
If at least one operand is String then “+” perform concatenation.
Example:-
class Test
{ public static void main(String[] args)
{ int a=10;
int b=20;
System.out.println(a+b); //30 [addition]
System.out.println(a+"ratan"); //10Ratan [concatenation]
System.out.println("ratan"+"anu"+2+2+"kids");
System.out.println(2+2+"kids"+"ratan"+"anu");
}
}
103 | P a g e
SravyaInfotech Mr. Ratan
Example :-
In below example marry method present in parent class with some implementations but child
class overriding marry method to provide child specific implementation is called overriding.
class Parent
{ void property()
{ System.out.println("money+land+hhouse");
}
void marry() //overridden method
{ System.out.println("black girl");
}
};
class Child extends Parent
{ void marry() //overriding method
{ System.out.println("white girl/red girl");
}
public static void main(String[] args)
{ Child c=new Child();
c.property();
c.marry();
}
};
E:\>java Child
money+land+hhouse
white girl/red girl
104 | P a g e
SravyaInfotech Mr. Ratan
105 | P a g e
SravyaInfotech Mr. Ratan
106 | P a g e
SravyaInfotech Mr. Ratan
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 long float double
char
down-casting:-
byte short
Int long 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.
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
107 | P a g e
SravyaInfotech Mr. Ratan
108 | P a g e
SravyaInfotech Mr. Ratan
Example:- in java it is possible to override methods in child classes but it is not possible to
override variables in child classes.
class Parent
{ int a=100;
};
class Child extends Parent
{ int a=1000;
public static void main(String[] args)
{ Parent p = new Child();
System.out.println("a vlues is :--->"+p.a);//100
}
};
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
109 | P a g e
SravyaInfotech 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.
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
110 | P a g e
SravyaInfotech Mr. Ratan
111 | P a g e
SravyaInfotech Mr. Ratan
Example :-
class Animal
{void eat(){System.out.println("animal eat");}
};
class Dog extends Animal
{void eat(){System.out.println("Dog eat");}
};
class Cat extends Animal
{ void eat(){System.out.println("cat eat");}
};
class Test
{ public static void main(String[] args)
{ Animal a1,a2;
a1=new Dog(); //creates object of Dog class
a1.eat(); //compiletime:Animal runtime : Dog
a2=new Cat(); //creates object of Cat class
a2.eat(); //compiletime:Animal runtime : Cat
}
};
Example-:-method overriding vs. multilevel inheritance.
class Person
{ void eat(){System.out.println("4-idly");}
};
class Ratan extends Person
{ void eat(){System.out.println("10-idly");}
};
class RatanKid extends Ratan
{ void eat(){System.out.println("2-idly");}
};
class Test
{ public static void main(String[] args)
{ Person p = new Ratan();
p.eat(); //compiletime: Person runtime:Ratan
Ratan r = new RatanKid();
r.eat(); //compiletime: Ratan runtime:RatanKid
Person p1 = new RatanKid();
p1.eat(); //compiletime: Person runtime:RatanKid
}
};
112 | P a g e
SravyaInfotech Mr. Ratan
static method cannot be overridden because static method bounded with class where as
instance methods are bounded with object.
In java it is possible to override only instance methods but not static methods.
The below example seems to be overriding but it is method hiding concept.
class Parent
{ static void m1(){System.out.println("parent m1()");}
};
class Child extends Parent
{ static void m1(){System.out.println("child m1()");}
public static void main(String[] args)
{ Parent p = new Child();
p.m1();//output : parent m1()
}
};
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.
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]
113 | P a g e
SravyaInfotech Mr. Ratan
}
};
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
}
};
114 | P a g e
SravyaInfotech Mr. Ratan
115 | P a g e
SravyaInfotech 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 String toString()
{ return ename+" "+eid+" "+esal;
}
public static void main(String[] args)
{ Employee e1 = new Employee("ratan",111,60000);
Employee e2 = new Employee("aruna",222,70000);
Employee e3 = new Employee("nandu",222,80000);
//whenever we are printing reference variables internally it calls toString() method
System.out.println(e1);//e1.toString() [our class toString() executed output printed]
System.out.println(e2);//e2.toString() [our class toString() executed output printed]
System.out.println(e3);//e3.toString() [our class toString() executed output printed]
}
};
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
116 | P a g e
SravyaInfotech Mr. Ratan
}
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.
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
case 4:-
for the static variables JVM will provide default values.
class Test
{ static int a;
public static void main(String[] args)
117 | P a g e
SravyaInfotech Mr. Ratan
final variables always needs initialization, if you don’t initialize compiler will generate compilation error.
class Test
{ final static int a;
public static void main(String[] args)
{ System.out.println("static variable value="+Test.a);
}
}
Compilation error:
variable a might not have been initialized
118 | P a g e
SravyaInfotech Mr. Ratan
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
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();
}
119 | P a g e
SravyaInfotech Mr. Ratan
};
class Test
{ //overriding finalize()
public void finalize()
{ System.out.println("ratan sir object is destroyed");
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(); }
} };
};
120 | P a g e
SravyaInfotech Mr. Ratan
Abstraction:-
There are two types of methods in java
a. Normal methods
b. Abstract methods
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”
121 | P a g e
SravyaInfotech 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
}
};
122 | P a g e
SravyaInfotech 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.
123 | P a g e
SravyaInfotech Mr. Ratan
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
void m2(){System.out.println("m2 method");} //m2() normal method
};
abstract class Test1 extends Test
124 | P a g e
SravyaInfotech Mr. Ratan
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 creating object by using “new” then
only constructor executed.
Note :- in below example abstract class constructor is executed but object is not created.
Inside the abstract class it is possible to declare the constructor.
125 | P a g e
SravyaInfotech 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.
126 | P a g e
SravyaInfotech Mr. Ratan
Encapsulation:-
The process of binding the data and code as a single unit is called encapsulation.
Or
The process of hiding the implementation details to user is called encapsulation. And
we are achieving this concept by declaring variables as a private modifier because it is
possible to access private members with in the class only.
Example:-
If the variables are declared as a private it is possible to access those variables only with
in the class but it possible to set(update) the data by using setter methods and it is possible to
get(read) the data by using getter methods.
The data of the private field can be accessed only by using public setter & getter method
In this way we are hiding implementation to other classes. The setter and getter methods are
userdefined methods.
Syntax:-
setXXX() where xxx=property name
getXXX() where xxx=property name
The setter method return type is always void & getter method return type is always
property return type.
File-1:-
class Encapsulation
{ private int sid;
private int sname;
public void setSid(int x)
{ this.sid=sid;
}
public void setSname(String sname)
{ this.sname=sname;
}
public int getSid()
{ return sid;
}
public String getSname()
{ return sname; }
};
To access encapsulated use fallowing code:-
class Test
{ public static void main(String[] args)
{ Encapsulation e=new Encapsulation();
e.setSid(100);
e.setSname("ratan");
System.out.println(e.getSid());
System.out.println(e.getSname());
}
};
127 | P a g e
SravyaInfotech Mr. Ratan
Main Method:-
128 | P a g e
SravyaInfotech Mr. Ratan
Example:-
class Test
{ final strictfp synchronized static public void main(String...ratan)
{ System.out.println("hello ratan sir");
}
};
129 | P a g e
SravyaInfotech Mr. Ratan
}
}
E:\>java Test
String[] main method
char main method
int main method
note:- it is not possible to override main method because main is a static method.
Example-1 :-
class Test
{ public static void main(String[] ratan)
{ System.out.println(ratan[0]+" "+ratan[1]);//printing command line arguments
System.out.println(ratan[0]+ratan[1]);
//conversion of String-int String-double
int a = Integer.parseInt(ratan[0]);
double d = Double.parseDouble(ratan[1]);
System.out.println(a+d);
}
};
D:\>java Test 100 200
100 200
100200
300.0
Example-2:-
To provide the command line arguments with spaces then take that command line argument
with in double quotes.
class Test
{ public static void main(String[] ratan)
{ //printing commandline arguments
System.out.println(ratan[0]);
System.out.println(ratan[1]);
}
};
D:\>java Test corejava ratan
corejava
ratan
D:\>java Test core java ratan
core
java
D:\>java Test "core java" ratan
130 | P a g e
SravyaInfotech Mr. Ratan
core java
ratan
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
131 | P a g e
SravyaInfotech Mr. Ratan
132 | P a g e
SravyaInfotech 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
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:-
133 | P a g e
SravyaInfotech Mr. Ratan
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.*;
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)
134 | P a g e
SravyaInfotech 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
135 | P a g e
SravyaInfotech Mr. Ratan
5) It improves understandability.
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
{}
D:\>javac -d . Test.java
Step-4:-execution process.
Execute the .class file by using fully qualified name(class name with complete package structure)
136 | P a g e
SravyaInfotech Mr. Ratan
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.
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");}
}
137 | P a g e
SravyaInfotech Mr. Ratan
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
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.
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 indirect child classes& it is not possible to call even in indirect child
classes.
But in outside package we can access protected members only by using child reference. If we try
to use parent reference we will get compile time error.
138 | P a g e
SravyaInfotech Mr. Ratan
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);
}
};
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
139 | P a g e
SravyaInfotech Mr. Ratan
};
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();
140 | P a g e
SravyaInfotech Mr. Ratan
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 Sravya.trainer();
package com.tcs.course.coursedetails; }
import com.dss.java.corejava.*; }
class Tcs
{ public static void main(String[] args) with static import
{ System.out.println(Sravya.fee); package com.tcs.course.coursedetails;
Sravya.course(); import static com.dss.java.corejava.Sravya.*;
Sravya.duration();
141 | P a g e
SravyaInfotech 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.
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 Package structure:-
{ public void m1() jav
{System.out.println("core java World!"); |-->corejava
} |--->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)
142 | P a g e
SravyaInfotech Mr. Ratan
{ new A().m1();
new B().m1();
new C().m1();
}
}
Example :-
in java it is not possible to use predefined package names as a user defined packages. If we
are trying to use predefined package names as a user defined packages at runtime JVM will generate
securityException.
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
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
143 | P a g e
SravyaInfotech Mr. Ratan
o Admin
These type of objects are called singleton objects.
file-1:-
package com.dss.st;
class Test
{ public static Test t=null;
private Test(){}
public static Test getInstance()
{ if (t==null)
{ t = new Test();
}
return t;
}
public void disp()
{ System.out.println("this is ratan singleton class");
}
};
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
}
};
144 | P a g e
SravyaInfotech 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 interface allows to declare only abstract methodsand these methods are by default public &
abstract if we are declaring or not.
3. The interface is highlighting set of functionalities but implementations are hiding.
4. For the interfaces also compiler will generates .class files after compilation.
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
{ *****
}
if you don’t no the anything about implementation just we have the requirement specification
then declare that requirements by using interface.
If u know the implementation but not completely then we should go for abstract classes.
if you know the implementation completely then we should go for concrete classes.
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 “.
Interface contains abstract method for these methods provide the implementation in the
implementation classes.
Implementation class is nothing but the class which 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”.
interface it1
{ Void m1(); //abstract method by default [public abstract]
Void m2(); //abstract method by default [public abstract]
145 | P a g e
SravyaInfotech Mr. Ratan
Example :-
interface It1 //abstract
{ void m1(); //public abstract
void m2();
void m3();
}
class Test implements It1
{ public void m1(){System.out.println("m1 method");}
public void m2(){System.out.println("m2 method");}
public void m3(){System.out.println("m3 method");}
Example-2:-
Interface contains abstract method for these 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& complete the remaining abstract method
implementation in next created child classes.
146 | P a g e
SravyaInfotech Mr. Ratan
If the child class also unable to provide implementation then declare the child class with abstract
modifier & take one more child class to complete the implementations.
In java it is possible to take any number of child classes but at final complete the
implementation of all abstract methods.
interface It1
{ 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");}
public static void main(String[] args)
{ Test2 t = new Test2();
t.m1();
t.m2();
t.m3();
}
};
Example:- 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()
147 | P a g e
SravyaInfotech Mr. Ratan
{ 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();
}
interface It3 extends It1,It2
{ void m3();
}
class Test implements It1
{ 1 method
};
class Test implements It1,It2
{ 2 methods
};
class Test implements It1,It2,It3
{ 3 methods
};
148 | P a g e
SravyaInfotech Mr. Ratan
149 | P a g e
SravyaInfotech Mr. Ratan
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.
150 | P a g e
SravyaInfotech 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();
}
151 | P a g e
SravyaInfotech Mr. Ratan
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
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");}
}
152 | P a g e
SravyaInfotech Mr. Ratan
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();
}
}
153 | P a g e
SravyaInfotech Mr. Ratan
{ provide the implementation of 6 methods m1() & m2() & m3() & m4() & m5() & m6()
};
Case 4:-
class Test implements it4
{ provide the implementation of 7 methodsm1() & m2() & m3() & m4() & m5() & m6() & m7()
};
Case 6:-
class Test implements it1,it2 //one class is able to implements multiple interfaces
{ provide the implementation of 4 methods m1() & m2() & m3() & m4()
};
Case 7:-
class Test implements it1,it3
{ provide the implementation of 6 methods m1() & m2() & m3() & m4() & m5() & m6
};
Case 8:-
class Test implements it2,it3
{ provide the implementation of 6 methods m1() & m2() & m3() & m4() & m5() & m6
};
Case 9:-
class Test implements it2,it4
{ provide the implementation of 7 methodsm1() & m2() & m3() & m4() & m5() & m6 & m7()
};
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
154 | P a g e
SravyaInfotech Mr. Ratan
{ 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
{ public void m1()
{ System.out.println("m1 method"); }
public void m2()
{ System.out.println("m2 method"); }
public static void main(String[] args)
{ Test2 t=new Test2();
t.m1(); t.m2();
}
};
Marker interface :-
An interface that has no members (methods and variables) is known as marker interface or
tagged interface or ability interface.
In java whenever our class is implementing marker interface our class is getting some
capabilities that are power of marker interface. We will discuss marker interfaces in detail in
later classes.
Ex:- serializable , Cloneable , RandomAccess…etc
Note: - user defined empty interfaces are not a marker interfaces only, predefined empty interfaces
are marker interfaces.
155 | P a g e
SravyaInfotech 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(){}
;;;;;;;;
156 | P a g e
SravyaInfotech Mr. Ratan
157 | P a g e
SravyaInfotech Mr. Ratan
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:-
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");
}
}
158 | P a g e
SravyaInfotech Mr. Ratan
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
{ public static void main(String[] args)
{ String str="ratan";
System.out.println(str);
char[] ch={'r','a','t','a','n'};
String str3=new String(ch);
159 | P a g e
SravyaInfotech Mr. Ratan
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);
}
}
We are able to create StringBuffer object only one approach by using new operator.
StringBuffer sb = new StringBuffer(“sravyainfotech”);
Creating a string object without using new When we create object without using
operator :- new operator then just before object
When we create String object without creation it is always checking previous
using new operator the objects are objects.
created in SCP (String constant pool) o If the previous object is
area. available with the same content
then it won’t create new object
String str1=”rattaiah”; that reference variable pointing
String str2=”Sravya”; to existing object.
String str3=”Sravya”; o If the previous objects are not
available then JVM will create
new object.
SCP area does not allow duplicate
objects.
160 | P a g e
SravyaInfotech Mr. Ratan
Heap area
Example:-
class Test
{ public static void main(String[] args)
{ //two approaches to create a String object
String str1 = "ratan";
System.out.println(str1);
String str2 = new String("anu");
System.out.println(str2);
String str1="ratan";
String str2="ratan";
System.out.println(str1==str2); //true
161 | P a g e
SravyaInfotech Mr. Ratan
Case : toString()
toString( ) method present in object class it returns a string representation of object(class-
name@hashcode).
String is child class of Object and it is overriding toString() to return content of the String object.
StringBuffer is child class of Object and it is overriding toString() to return content of the
StringBuffer object.
Note :- whenever we are printing any type of reference variable in java internally it is calling
toString() method .
class Object
{ public java.lang.String toString()
{ return getClass().getName() + '@' + Integer.toHexString(hashCode()); }
}
class String extends Object
{ //overriding method
162 | P a g e
SravyaInfotech Mr. Ratan
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);//ratan
163 | P a g e
SravyaInfotech Mr. Ratan
sb.append("soft");
System.out.println(sb);//anusoft
}
}
Concat( ) :-
Concat() method is combining two String objects and it is returning new String object.
public java.lang.String concat(java.lang.String);
Example :-
class Test
{ public static void main(String[] args)
{ String str="ratan";
String str1 = str.concat("soft");//concat() method return String object.
System.out.println(str);
System.out.println(str1);
}
}
File-1:Emp.java
class Emp
{ private final String ename;
Emp(String ename)
{ this.ename=ename;
}
public String getName()
{ return ename;
}
};
File 2:Test.java
class Test
{ public static void main(String[] args)
{ Emp e = new Emp("ratan");
System.out.println(e.getName());
164 | P a g e
SravyaInfotech Mr. Ratan
}
}
In above example Emp class immutable class because,
a. Emp class properties are final we are unable to change the value after creating object.
b. Emp class if final we are unable create sub-class & it is not possible to override the methods.
c. We are using constructor it assign the values only once.
d. There is no setter method hence we have no option to change the value of variable.
Case 4:-
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.
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));
165 | P a g e
SravyaInfotech 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
166 | P a g e
SravyaInfotech Mr. Ratan
class Test
{ public static void main(String[] args)
{ String str1 = "hello";
String str2 = "hello";
String str3= new String("hello");
//identity checking
System.out.println(str1==str2); //true
System.out.println(str1==str3); //false
System.out.println(str1==str3); //false
//equality checking
167 | P a g e
SravyaInfotech Mr. Ratan
System.out.println(str1.equals(str2)); //true
System.out.println(str1.equals(str3)); //true
System.out.println(str2.equals(str3)); //true
}
}
String str="rattaiah";
System.out.println(str.length()); //8
168 | P a g e
SravyaInfotech Mr. Ratan
class Test
{ public static void main(String[] args)
{ //cahrAt() method
String str="ratan";
System.out.println(str.charAt(1));
//System.out.println(str.charAt(10));StringIndexOutOfBoundsException
char ch="ratan".charAt(2);
System.out.println(ch);
//split() method
String s="hi rattaiah how r u";
String[] str1=s.split(" ");
for(String str2 : str1)
{ System.out.println(str2);
}
//trim()
String ss=" ratan ";
System.out.println(ss.length());//7
System.out.println(ss.trim());//ratan
System.out.println(ss.trim().length());//5
}
}
169 | P a g e
SravyaInfotech Mr. Ratan
170 | P a g e
SravyaInfotech Mr. Ratan
}
};
Insert():-
By using above method we are able to insert the string any location of the existing string.
class Test
{ public static void main(String[] args)
{ StringBuffer sb=new StringBuffer("ratan");
sb.insert(0,"hi ");
System.out.println(sb);
}
}
indexOf() and lastIndexOf():-
Ex:-
class Test
{ public static void main(String[] args)
{ StringBuffer sb=new StringBuffer("hi ratan hi");
int i;
i=sb.indexOf("hi");
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.
171 | P a g e
SravyaInfotech 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());
}
}
}
172 | P a g e
SravyaInfotech 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
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).
173 | P a g e
SravyaInfotech Mr. Ratan
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());
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)
174 | P a g e
SravyaInfotech Mr. Ratan
{ 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);
System.out.println(i1);
Integer a2 = Integer.valueOf("1000");
System.out.println(a2);
}
}
175 | P a g e
SravyaInfotech Mr. Ratan
Integer a2 = Integer.valueOf("1000");
System.out.println(a2);
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
SravyaInfotech 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());
177 | P a g e
SravyaInfotech Mr. Ratan
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);
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:-
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);
178 | P a g e
SravyaInfotech Mr. Ratan
System.out.println(str1);
String s1="sravyainfotech";
String s2 = s1.substring(0,6);
System.out.println(s2);
I/O Streams:-
An I/O stream represents input source or an output destination. A stream represent many kind of
source and destination like disk files & devices & memory arrays.
Streams support different kind of data
Simple bytes.
Primitive data types
Localized characters
Objects …..etc
Stream is a communication channel between source and destination & A stream is a sequence of data.
Input stream:-
Program uses Input stream to read the data from a source one item at a time.
179 | P a g e
SravyaInfotech Mr. Ratan
Output stream:-
Program uses output stream to write the data to a destination one item at a time.
Byte streams:-
Program uses byte stream to perform input & output of byte data. All byte stream classes
developed based on InputStream & OutputStream.
To demonstrate how the byte stream works file I/O provided two main classes
FileInputStream
o It is used to read the data from source one item at a time.
o To read the data from source use read() method of FileInputStream class.
public int read() throws java.io.IOException;
read() method returns first character Unicode value in the form of integer value.
FileOutputStream
o It is used to write the data to destination one item at a time.
o To write the data to destination use write() method of FileOutputStream class.
public void write(int unicode) throws java.io.IOException;
write() method is taking Unicode value of the character as a parameter.
Example :-
import java.io.*;
class Test
180 | P a g e
SravyaInfotech Mr. Ratan
While working with streams we will get two exceptions mainly FileNotFoundException ,
IOException & these two exceptions are checked exceptions so must handle these exception by using try-
catch blocks or throws keyword.
Character streams:-
Program uses character stream to perform input & output of character data. All character
stream classes developed based on Reader & Writer classes.
To demonstrate how the character stream works file I/O provided two main classes
FileReader
o It is used to read the data from source one item at a time.
o To read the data from source use read() method of FileInputStream class.
public int read() throws java.io.IOException;
read() method returns first character Unicode value in the form of integer value.
FileWriter
o It is used to write the data to destination one item at a time.
o To write the data to destination use write() method of FileOutputStream class.
public void write(int unicode) throws java.io.IOException;
write() method is taking Unicode value of the character as a parameter.
Example :-
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test
{ public static void main(String[] args) throws IOException
{ FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("abc.txt");
outputStream = new FileWriter("characteroutput.txt");
181 | P a g e
SravyaInfotech Mr. Ratan
int c;
while ((c = inputStream.read()) != -1)
{ outputStream.write(c);
}
}
finally
{ if (inputStream != null)
{ inputStream.close();
}
if (outputStream != null)
{ outputStream.close();
}
}
}
}
Note : In CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int
variable holds a byte value in its last 8 bits.
Example :-
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
182 | P a g e
SravyaInfotech Mr. Ratan
Buffered Streams:-
In previous examples we are using un-buffered I/O.This means each read and write request is
handled directly by the underlying OS.
In normal streams each request directly triggers disk access it is relatively expensive &
performance is degraded.
To overcome above limitations use buffered streams.
Bufferd input stream read the data from buffered memory and it interacting with hard disk only
when buffered memory is empty.
Buffered output stream write the data to buffer memory.
Example:-
import java.io.*;
class Test
183 | P a g e
SravyaInfotech Mr. Ratan
Example:-
import java.io.*;
class Test
{ public static void main(String[] args)
{ BufferedInputStream bis;
BufferedOutputStream bos;
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");
}
}
}
184 | P a g e
SravyaInfotech Mr. Ratan
Example:-Scanning
package com.tcs;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = null;
try { scanner= new Scanner(new BufferedReader(new FileReader("E:\\abc.txt")));
while(scanner.hasNext())
{ System.out.println(scanner.next());
}
} catch (FileNotFoundException e) {e.printStackTrace();}
finally
{ if(scanner!=null)
{ scanner.close();
}
}
}
}
Example :- formatting
Stream objects that implement formatting are instances of either PrintWriter, a character
stream class, or PrintStream, a byte stream class.
both PrintStream and PrintWriter implement the same set of methods for converting internal
data into formatted output. Two levels of formatting are provided:
o print and println format individual values in a standard way.
o format formats almost any number of values based on a format string, with many
options for precise formatting.
public class Test
{ public static void main(String[] args)
{ int i = 2;
double r = Math.sqrt(i);
System.out.print("The square root of ");
System.out.print(i);
System.out.print(" is ");
System.out.print(r);
System.out.println(".");
i = 5;
r = Math.sqrt(i);
System.out.println("The square root of " + i + " is " + r + ".");
}
}
E:\>java Test
The square root of 2 is 1.4142135623730951.
The square root of 5 is 2.23606797749979.
185 | P a g e
SravyaInfotech Mr. Ratan
System.out.println("enter password");
char[] ch = c.readPassword();
System.out.println("password is="+ch);
String pwd = String.valueOf(ch);
System.out.println("password is="+pwd);
}
};
Data Streams:-
Data Streams supports binary I/O primitive data type
value(byte,short,int,long,float,double,char,boolean) as well as String data.
186 | P a g e
SravyaInfotech Mr. Ratan
Order
Data Data Sample
in Output Method Input Method
type description Value
record
1 double Item price DataOutputStream.writeDouble DataInputStream.readDouble 19.99
2 int Unit count DataOutputStream.writeInt DataInputStream.readInt 12
Item "Java T-
3 String DataOutputStream.writeUTF DataInputStream.readUTF
description Shirt"
Example:-
import java.util.*;
import java.io.*;
public class Test
{ public static void main(String args[])throws Exception
{ final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
final int[] units = { 12, 8, 13, 29, 50 };
final String[] descs = {"Java T-shirt","Java Mug","Duke Juggling Dolls","Java Pin","Java Key
Chain"};
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new
FileOutputStream("ratan")));
for (int i = 0; i < prices.length; i ++)
{ out.writeDouble(prices[i]);
out.writeInt(units[i]);
out.writeUTF(descs[i]);
}
out.close();
Object Streams:-
187 | P a g e
SravyaInfotech 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");
188 | P a g e
SravyaInfotech Mr. 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.
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
introduction:-
Dictionary meaning of the exception is abnormal termination.
189 | P a g e
SravyaInfotech Mr. Ratan
An exception is an event that occurs during execution of the program, that disturb normal flow
of the program instructions.
If the application contains exception then the program terminated abnormally then the rest of
the application is not executed.
To overcome above limitation in order to execute the rest of the application & to get normal
termination 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.
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 &to get normal termination of the application.
Types of Exceptions:-
As per the sun micro systems standards The Exceptions are divided into three types
1) Checked Exception
2) Unchecked Exception
3) Error
Checked Exception:-
The Exceptions which are checked by the compiler at the time of compilation is called Checked
Exceptions.
190 | P a g e
SravyaInfotech Mr. Ratan
Examples:-IOException,SQLException,InterruptedException,ClassNotFoundException……..etc
If the application contains checked Exception the compiler is able to check it and it will give
intimation to developer regarding Exception in the form of compilation error.
Handle the checked Exception in two ways
o By using try-catch block.
o By using throws keyword.
There are two types of predefined methods
Exceptional methods
public static native void sleep(long) throws java.lang.InterruptedException
public boolean createNewFile() throws java.io.IOException
public static Class forName(String str) throws ClassNotFoundException
Normal methods
public long length();
public java.lang.String toString();
In our application whenever we are using exceptional methods the code is not compiled because
these methods throws checked exception hence must handle the exception by using try-catch or throws
keywords. And no need to remember the methods just use the method compile it then compiler is saying
exception information handle it.
Note: -If application contains checked Exception then compile time just compiler is displays exception
information for handling but the exception raised at runtime if the required resources are not available.
191 | P a g e
SravyaInfotech Mr. Ratan
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.
Note-1:-
Whether it is a checked Exception or unchecked exception exceptions are raised at
runtime but not compile time.
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& to execute rest of the application.
Note 3:-
For the checked exception when we write try-catch blocks or throws keyword then only
code is compiled but for un-checked exceptionstry-catch or throws keyword optional.
Error:-
Exceptions are caused to several reasons like developer mistakes, end user input mistakes ,
network problems.
But error is caused due to lack of system resources.
Heap memory full, Stack memory problem, AWT component problems…..etc
Example: - StackOverFlowError, OutOfMemoryError, AssertionError…………etc
We are handle the exceptions by using try-catch blocks or throws keyword but it is not possible
to handle the errors.
Error is a un-checked type exception.
Example:-
class Test
{ public static void main(String[] args)
{ Test[] t = new Test[100000000];
}
};
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
192 | P a g e
SravyaInfotech Mr. Ratan
In above tree Structure RuntimeException its child classes& Error its child classes are Unchecked
remaining all exceptions are checked Exceptions.
The root class of exception handling is Throwable class.
The root class& all its child class are checked then that root class is called fully checked exception.
Example :- IOException,SQLException….etc
The root class contains some class are checked exceptions & some classes are un-checked exception
then that root class is called partially checked exception.
Example :- Exception , Throwable..etc
Exception handling key words:-
1) try
2) catch
3) finally
4) throw
5) throws
Exception handling by using Try –catch blocks:-
193 | P a g e
SravyaInfotech Mr. Ratan
Syntax:-try
{exceptional code;
}
catch (ExceptionName reference_variable)
{Code to run if an exception is raised (alternate code);
}
Example-1 :-
Application without try-catch blocks
class Test
{ public static void main(String[] args)
{ System.out.println("ratan");
System.out.println(10/0);
System.out.println("rest of the application");
}
}
E:\>java Test
ratan
Exception in Thread “main” java.lang.ArithmeticException: / by zero
194 | P a g e
SravyaInfotech Mr. Ratan
Whenever the exception is raised in the try block JVM won’t terminate the program immediately
it will search corresponding catch block.
a. If the catch block is matched then that block will be executed & rest of the application
executed & program is terminated normally.
b. If the catch block is not matched program is terminated abnormally.
In below example catch block is not matched hence program is terminated abnormally.
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");
}
}
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 corresponding 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 4:-
195 | P a g e
SravyaInfotech Mr. Ratan
In Exception handling independent try blocks declaration 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 5:-
In between try-catch blocks it is not possible to declare any statements, if we are declaring
statements compiler will generate error message.
In exception handling must declare try with immediate catch block.
class Test
{ public static void main(String[] args)
{ try
{ 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 6:-
If the exception raised in try block jvm will search corresponding catch block but if the exception
raised other than try-catch blocks 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");
}
}
Example 7:-
196 | P a g e
SravyaInfotech Mr. Ratan
If the exception raised in try block the remaining code of try block is not executed.
Once the control is out of the try block the control never entered into try block once again.
Don’t take normal code inside try block because no guarantee all statements in try-block
executed or not.
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");
}
}
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);
System.out.println("ratan".charAt(10));
}
catch (ArithmeticException ae)
{ System.out.println("good boys");
}
catch (StringIndexOutOfBoundsException se)
{ System.out.println("good girls");
}
System.out.println("rest of the code");
}
}
Output:- provide the division value: 5 Output:- provide the division value: 0
Write the output Write the output
Example 9:-By using Exception class catch block it is possible to hold any type of exceptions.
197 | P a g e
SravyaInfotech Mr. Ratan
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);
System.out.println("ratan".charAt(10));
}
catch (Exception ae)
{ System.out.println("good boys");
}
System.out.println("rest of the code");
}
}
Output:- provide the division value: 5 Output:- provide the division value: 0
Write the output Write the output
Example 10:-
When we declare multiple catch blocks then the catch block order must be child-parent but if we
are declaring parent to child compiler will generate error message.
No compilation error
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("provide the division val");
int n=s.nextInt();
try
{ System.out.println(10/n);
String str=null;
System.out.println(str.length());
}
//catch block order is child to parent
catch (ArithmeticException ae)
{ System.out.println("Exception"+ae);
}
catch (Exception ne)
{ System.out.println("Exception"+ne);
}
System.out.println("rest of the code");
}
}
Compilation error
198 | P a g e
SravyaInfotech Mr. Ratan
Example 12:- Internally JVM uses printStackTrace() method to print exception information.
199 | P a g e
SravyaInfotech Mr. Ratan
class Test
{ void m3()
{ System.out.println(10/0);
}
void m2()
{ m3();
}
void m1()
{ m2();
}
public static void main(String[] args)
{ new Test().m1();
}
};
E:\>java Test
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.m3(Test.java:3)
at Test.m2(Test.java:6)
at Test.m1(Test.java:9)
at Test.main(Test.java:12)
Example 13:-It is possible to combine more than one exceptions in single catch block.
Syntax:-this is introduced In 1.7 version the code is compiled & executed in above 1.7 version.
catch(ArithmeticException | StringIndexOutOfBoundsException a) .
catch(NumberFormatException | NullPointerException | StringIndexOutOfBoundsException a)
import java.util.Scanner;
import java.io.*;
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 | ClassCastException a)
{ System.out.println("exception info="+a);
}
catch(NumberFormatException | NullPointerException | StringIndexOutOfBoundsException a)
{ System.out.println("exception info="+a);
}
System.out.println("Rest of the application");
}
}
Output:- provide the division value: 5 Output:- provide the division value: 0
Write the output Write the output
Example14:- multiple exception in single catch for checked Exception.
200 | P a g e
SravyaInfotech Mr. Ratan
import java.util.Scanner;
import java.io.*;
public class Test
{ public static void main(String[] args)
{ try {
FileInputStream f = new FileInputStream("abc.txt");
Thread.sleep(2000);
}
catch(FileNotFoundException | InterruptedException a)
{ System.out.println("exception info="+a);
}
System.out.println("Rest of the application");
}
}
Observation :-
try { FileInputStream f = new FileInputStream("abc.txt");
Thread.sleep(2000);
}
catch(FileNotFoundException | ClassCastException a)
{ System.out.println("exception info="+a);
}
catch(InterruptedException | ClassNotFoundException a)
{ System.out.println("exception info="+a);
}
E:\>javac Test.java
error: exception ClassNotFoundException is never thrown in body of corresponding try statement
catch(InterruptedException | ClassNotFoundException a)
Possibilities of try-catch:-
Case-1
201 | P a g e
SravyaInfotech Mr. Ratan
Finally block:-
1) Finally block code 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 ---> valid
b. try-catch ---> valid
c. catch-finally ---> invalid
d. try-catch-catch-finally ---> valid
e. try-finally ---> valid
f. catch-catch-finally ---> invalid
g. Try ---> invalid
h. Catch ---> invalid
i. Finally ---> invalid
Syntax:-
202 | P a g e
SravyaInfotech Mr. Ratan
try
{ risky code;
}
catch (Exception obj)
{ code to be run if the exception raised (handling code);
}
finally
{ Clean-up code;(database connection closing , streams closing……etc)
}
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
case 5:-
try
203 | P a g e
SravyaInfotech Mr. Ratan
{ System.out.println("try");
}
catch(ArithmeticException ae)
{ System.out.println("catch"); case 6:-it is possible to provide try-finally.
} try
finally { System.out.println("try");
{ System.out.println(10/0); }
} finally
System.out.println("rest of the code"); { System.out.println("finally");
D:\>java Test }
try System.out.println("rest of the code");
Exception in thread "main" D:\>java Test
java.lang.ArithmeticException: / by zero try
at Test.main(Test.java:15) finally
rest of the code
204 | P a g e
SravyaInfotech Mr. Ratan
statement 2
try
{ statement 3
statement 4
try
{ statement 5
statement 6
}
catch ()
{ statement 7 Case1:there is no Exception in the above
statement 8 example.
} 1, 2, 3, 4, 5, 14, 15 Normal Termination
} Case 2:- if the exception is raised in statement 2.
catch () 1 , Abnormal Termination
{ statement 9 Case 3:-if the exception is raised in the
statement 10 statement 3 the corresponding
try catch block Is not matched.
{ statement 11 1,2,15,16Abnormal termination
statement 12 Case 4:- if the exception is raise in the
} statement-4 the corresponding
catch () catch block is matched.
{ statement 13 1,2,15,16Abnormal termination
statement 14 Case 5:-If the exception is raised in the
} statement 5 and corresponding
} catch block is matched.
Finally{ 1,2,3,4,8,9,10,11,14,15 normal termination
statement 15 Case 6:-If the exception is raised in the
statement 16 statement 6 and corresponding
} catch block is notmatched but
Statement -17 outer catch block is matched.
Statement -18 1,2,3,4,8,9,10,11,14,15 normal termination
Case 7:- If the exception is raised in the statement 5 and the corresponding catch block is
matched but while executing catch block exception raised in statement-7, the outer
catch block is matched while executing outer catch exception raised in statement-11,
the inner catch block is matched but while executing inner catch the exception raised in
statement-13.
1,2,3,4,8,9,12,13,14,15 normal termination.
Case 8:- If the exception is raised in the statement 6 and the corresponding catch block is
matched but while executing catch block exception raised in statement-8, the outer
catch block is matched while executing outer catch exception raised in statement-12,
the inner catch block is matched but while executing inner catch the exception raised in
statement-14.
1,2,3,4,8,9,12,13,14,15 normal termination.
Case 9:- If the exception raised in statement 15.
1,2,3,4,5 abnormal termination.
Case 10:- if the Exception raised in statement 18.
205 | P a g e
SravyaInfotech Mr. Ratan
Throws keyword:-
There are two approaches two handle the exceptions in java
a. By using try-catch blocks.
b. By using throws keyword.
Example 1:-
in below example exception raised in studentDetails() method but it delegating responsibilities of
exception handling to hod() method by using throws keyword.
But hod() method delegating responsibilities of exception handling to principal() method by
using throws now principal handing this exception by using try-catch blocks.
class Test
{ void studentDetails() throws InterruptedException
{ System.out.println("suneel babu is sleeping");
Thread.sleep(3000);
System.out.println("do not disturb sir......");
}
void hod()throws InterruptedException
{ studentDetails();
}
void principal()
{ try{
hod();}
catch(InterruptedException ie)
{ ie.printStackTrace(); }
}
void officeBoy()
{ principal();
}
public static void main(String[] args)
{ Test t = new Test();
t.officeBoy();
}
}
206 | P a g e
SravyaInfotech Mr. Ratan
Example 2:-
In below example method-by-method using throws keyword to delegate responsibilities of
exception handling to caller method.
At final main() method uses throws keyword to delegate the responsibilities of exception
handling to JVM.
class Test
{ void studentDetails() throws InterruptedException
{ System.out.println("suneel babu is sleeping");
Thread.sleep(3000);
System.out.println("do not disturb sir......");
}
void hod()throws InterruptedException
{ studentDetails();
}
void principal()throws InterruptedException
{ hod();
}
void officeBoy()throws InterruptedException
{ principal();
}
public static void main(String[] args) throws InterruptedException
{ Test t = new Test();
t.officeBoy();
}
}
Example 3:-
import java.io.*;
class Test
{
void m2()throws FileNotFoundException,InterruptedException
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()
{ try{
m2();}
catch(FileNotFoundException f){f.printStackTrace();}
catch(InterruptedException ie){ie.printStackTrace();}
}
public static void main(String[] args) throws InterruptedException
{ Test t = new Test();
t.m1();
}
}
207 | P a g e
SravyaInfotech Mr. Ratan
Example 4:-
import java.io.*;
class Test
{
void m2()throws Exception //FileNotFoundException,InterruptedException
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()throws Exception
{ m2();
}
public static void main(String[] args) throws Exception
{ Test t = new Test();
t.m1();
}
}
208 | P a g e
SravyaInfotech Mr. Ratan
Throw keyword:-
All methods use the throw statement to throw an exception. The throw statement requires a
single argument a throwable object. Throwable objects are instances of any subclass of the
Throwable class.
It is possible to throw user defined exceptions or predefined exceptions by using throw keyword.
Here's an example of a throw statement
throw someThrowableObject;
Note: - throw keyword is used to handover user created exception object to JVM whether it is predefined
exception class or user defined exception class.
import java.util.*;
class Test
{ static void validate(int age)
{ if (age<18)
{ 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 ");
validate(s.nextInt());
System.out.println("rest of the code");
}
}
E:\>java Test E:\>java Test
please enter your age please enter your age
45 10
Check the output Check the output
209 | P a g e
SravyaInfotech Mr. Ratan
210 | P a g e
SravyaInfotech Mr. Ratan
211 | P a g e
SravyaInfotech Mr. Ratan
Example: -creation of user defined un-checked exception by using parameterized constructor approach
Step1:- create user defined un-checked exception classs.
Normal java class will become un-checked exception class when we exetends RuntimeException
class.
//InvalidAgeException.java
package com.tcs.userexceptions;
public class InvalidAgeExcepiton extends RuntimeException
{ public InvalidAgeExcepiton(String str)
{ super(str);
}
};
212 | P a g e
SravyaInfotech Mr. Ratan
Test.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
{ //using user created Exception
throw new InvalidAgeExcepiton("not eligible for mrg");
}
}
public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("enter u r age");
int age = s.nextInt();
Test.status(age);
}
}
String str1="abc";
int b=Integer.parseInt(str1);
System.out.println(b);//NumberFormatException
NullPointerException:-
String str="rattaiah";
System.out.println(str.length());//8
String str1=null;
System.out.println(str1.length());//NullPointerException
t=null;
t.m1(); //NullPointerException
ArithmeticException:-
213 | P a g e
SravyaInfotech Mr. Ratan
int b=10/0;
System.out.println(b);//ArithmeticExceptiom
IllegalArgumentException:-
Thread priority range is 1-10
1--->low priority
10--->high priority
Thread t=new Thread();
t.setPriority(11);//IllegalArgumentException
IllegalThreadStateException:-
Thread t=new Thread();
t.start();
t.start();//IllegalThreadStateException
StringIndexOutOfBoundsException:-
String str="rattaiah";
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
214 | P a g e
SravyaInfotech Mr. Ratan
class Test
{ public static void main(String[] args)
{ int[] a=new int[100000000]; //OutOfMemoryError
}
}
java.lang.NoClassDefFoundError vs java.lang.ClassNotFoundException:-
215 | P a g e
SravyaInfotech Mr. Ratan
class Test1
{ void m1()
{ System.out.println("Test1 class m1()");
}
}
class Test
{ public static void main(String[] args) throws ClassNotFoundException
{ Test1 t = new Test1();
t.m1();
Class.forName("Emp");
}
}
Observation-1:-
In Test class we are hard coding Test1 object but in target location Test1.class file is not available
it will generate java.lang.NoClassDefFoundError.
Observation-2:-
In java to load .class file dynamically at runtime we are using forName() method but if runtime
the class is not available it generate java.lang.ClassNotFoundException.
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.
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:-
216 | P a g e
SravyaInfotech Mr. Ratan
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.
217 | P a g e
SravyaInfotech Mr. Ratan
System.out.println("hello Sravyasoft");
}
} end
In the above program only one thread is available is called main thread to know the name of
the thread we have to execute the fallowing code.
The main important application areas of the multithreading are
1. Developing video games
2. Implementing multimedia graphics.
3. Developing animations
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");
}
218 | P a g e
SravyaInfotech Mr. Ratan
}
};
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.
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.
219 | P a g e
SravyaInfotech Mr. Ratan
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.
220 | 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");
}
};
Thread t2 = new Thread() //anonymous inner class
{ public void run()
{System.out.println("user thread-2");
}
};
t1.start();
t2.start();
}
};
Creating two threads by implementing Runnable interface using anonymous inner classes:-
class ThreadDemo
{ public static void main(String[] args)
{
Runnable r1 = new Runnable()
{ public void run()
{System.out.println("user Thread-1");
}
};
221 | P a g e
SravyaInfotech Mr. Ratan
222 | P a g e
SravyaInfotech Mr. Ratan
}
};
223 | P a g e
SravyaInfotech Mr. Ratan
}
};
class MyThread2 extends Thread
{ public void run()
{ System.out.println("Sravya task");
}
};
class MyThread3 extends Thread
{ public void run()
{ System.out.println("anu task");
}
};
class ThreadDemo
{ public static void main(String[] args) //1- main Thread
{ MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
t1.start(); //2
t2.start(); //3
t3.start(); //4
}
};
Here Four Stacks are created
Main -----------stack1
t1---------------stack2
t2--------------stack3
t3-------------stack4
Multiple threads are performing single task:-
class MyThread extends Thread
{ public void run()
{ 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
}
}
224 | P a g e
SravyaInfotech Mr. Ratan
t1 --Thread-0
t2 --Thread-1
t3 --Thread-2
2) To set the name use setName() & to get the name use getName(),
Public final String getName()
Public final void setName(String name)
Example:-
class MyThread extends Thread
{ public void run()
{ System.out.println("thread is running");
}
}
class ThreadDemo
{ public static void main(String args[])
{ MyThread t1=new MyThread();
MyThread t2=new MyThread();
System.out.println("t1 Thread name="+t1.getName());
System.out.println("t2 Thread name="+t2.getName());
System.out.println(Thread.currentThread().getName());
t1.setName("ratan");
System.out.println("after changeing t1 Thread name="+t1.getName());
}
}
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.
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
225 | P a g e
SravyaInfotech Mr. Ratan
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.
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++)
226 | P a g e
SravyaInfotech Mr. Ratan
{ 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);
}
}
};
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():-
227 | P a g e
SravyaInfotech Mr. Ratan
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++ )
{ System.out.println("i am sleeping ");
}
}
};
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t=new MyThread();
t.start();
t.interrupt();
}
};
NOTE:- The interrupt() is effected whenever our thread enters into waiting state or sleeping
state and if the our thread doesn’t enters into the waiting/sleeping state interrupted call will
be wasted.
Shutdown Hook:-
228 | P a g e
SravyaInfotech Mr. Ratan
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");
}
};
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
229 | P a g e
SravyaInfotech Mr. Ratan
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
230 | P a g e
SravyaInfotech Mr. Ratan
{ try{
System.out.println(msg);
Thread.sleep(4000);
System.out.println(msg);
Thread.sleep(4000);
}
catch(Exception e)
{e.printStackTrace();}
}
}
class MyThread1 extends Thread
{ public void run(){Test.x("ratan");} };
class MyThread2 extends Thread
{ public void run(){Test.x("anu");} };
class MyThread3 extends Thread
{ public void run(){Test.x("banu");} };
class TestDemo
{ public static void main(String[] args)//main thread -1
{ MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
t1.start(); //2-Threads
t2.start(); //3-Threads
t3.start(); //4-Threads
}
}
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)
231 | P a g e
SravyaInfotech Mr. Ratan
{ 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();
MyThread1 t1 = new MyThread1(h);
MyThread2 t2 = new MyThread2(h);
t1.start();
t2.start();
}
};
Daemon threads:-
The threads wchich are executed at background is called daemon threads.
Ex:- garbage collector,ThreadSchedular.default exceptional handler.
Non-daemon threads:-
The threads which are executed fore ground is called non-daemon threads.
Ex:- normal java application.
When we create a thread in java that is user defined thread and f it is running JVM will not
terminate that process.
If a thread is marked as a daemon thread JVM does not wait to finish and as soon as all the user
defined threads are finished then it terminates the program and all associated daemon threads.
Set the daemon nature to thread by using setDaemon() method
o MyThread t = new Mythread();
232 | P a g e
SravyaInfotech Mr. Ratan
t.setDaemon(true);
To know whether a thread is daemon or not use isDaemon() method
o Thread.currentThread().isDaemon();
class MyThread extends Thread
{ void message(String str)
{ try {
System.out.println("message="+str);
Thread.sleep(1000); }
catch (InterruptedException e)
{e.printStackTrace(); }
}
public void run()
{ if (Thread.currentThread().isDaemon())
{ while (true)
{ message("print hi ratan");
}
}
}
};
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t = new MyThread();
t.setDaemon(true);//setting daemon nature to Thread
t.start();
try{Thread.sleep(5000);}
catch(InterruptedException e)
{e.printStackTrace();}
System.out.println("main thread completed");
}
};
Note :- in above example make the setdaemon() is comment mode then the program never terminates
even main thread finished it’s execution.
233 | P a g e
SravyaInfotech Mr. Ratan
synchronized(t)
{ System.out.println("MyThrad total is waiting for MyThread completion...");
try{
t.wait();}
catch(InterruptedException ie){System.out.println(ie);}
}
System.out.println("MyThrad total is ="+t.total);
}
};
Volatile:-
Volatile modifier is also applicable only for variables but not for methods and classes.
If the values of a variable keep on changing such type of variables we have to declare
withvolatile modifier.
If a variable declared as a volatile then for every Thread a separate local copy will be created.
Every intermediate modification performed by that Thread will take place in local copy instead
of master copy.
Once the value got finalized just before terminating the Thread the master copy value will be
updated with the local stable value. The main advantage of volatile modifier is we can resolve
the data inconsistency problem.
But the main disadvantage is creating and maintaining a separate copy for every Thread
Increases the complexity of the programming and effects performance of the system.
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.
The nested classes are divided into two categories
1. Static nested classes(nested class declared with static modifier)
2. Non static nested classes( these are called inner classes)
a. Normal inner classes
b. Method local inner classes
c. Anonymous inner classes
Static nested classes:- The nested classes declare as a static modifier is called static nested classes.
Nested classes
234 | P a g e
SravyaInfotech Mr. Ratan
235 | P a g e
SravyaInfotech Mr. Ratan
};
};
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
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();
236 | P a g e
SravyaInfotech Mr. Ratan
237 | P a g e
SravyaInfotech 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();
}
};
Example:-
class Outer
{ private int a=100;
void m1()
{ class Inner
{
void innerMethod()
238 | P a g e
SravyaInfotech Mr. Ratan
239 | P a g e
SravyaInfotech Mr. Ratan
240 | P a g e
SravyaInfotech Mr. Ratan
241 | P a g e
SravyaInfotech Mr. Ratan
};
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();
}
}
Functional interface:-
It is introduced in jdk1.8 version & it has exactly one abstract method.
This interface is also known as single abstract method interface (SAM interface).
Note that instances of functional interfaces can be created with lambda expressions, method
references, or constructor references.
Java 8 introduced @FunctionalInterface annotation which can be used for compilation errors
when the interface you annotated violates the contracts of functional interface.
Example : @FunctionalInterface
interface Greetings
{ void morning();
}
Example : if we declare @functionalInterface annotation but if we are declaring more than one
abstract method then compiler will generate error message.
@FunctionalInterface
interface Greetings
{ void morning();
void m1();
}
E:\>javac Durga.java
Test.java:1: error: Unexpected @FunctionalInterface annotation @FunctionalInterface
Greetings is not a functional interface
242 | P a g e
SravyaInfotech Mr. Ratan
Functional interface allows only one abstract method it is not allowed second abstract method
in functional interface. If we remove @functionalInterface annotation then we are allowed to
add second abstract method but it is not a functional interface.
http://howtodoinjava.com/2014/04/05/functional-interface-tutorial/
https://www.youtube.com/watch?v=q5i_O4Uj_O8
xample :-
interface Executable
{ void execute();
}
class Runner
{ public void run(Executable e)
{ System.out.println("run method code....");
e.execute();
}
};
public class Test
{ public static void main(String[] args)
{ Runner r = new Runner();
//anonymous inner class
r.run(new Executable(){
public void execute()
{ System.out.println("execute method block of java code.....");
}
});
//lambda expression
System.out.println("=============");
r.run(() -> System.out.println("execute method block of code....."));
}
};
E:\>java Test
run method code....
execute method block of java code.....
=============
run method code....
execute method block of code.....
243 | P a g e
SravyaInfotech Mr. Ratan
Example :-
interface Executable
{ int execute();
}
class Runner
{ public void run(Executable e)
{ System.out.println("run method code....");
int x = e.execute();
System.out.println("return value="+x);
}
};
public class Test
{ public static void main(String[] args)
{ Runner r = new Runner();
//anonymous inner class
r.run(new Executable(){
public int execute()
{ System.out.println("execute method anonymous block of java code.....");
return 10;
}
});
//lambda expression code
System.out.println("=============");
r.run(() -> {System.out.println("execute method lambda expression code.....");
return 20;
});
}
}
E:\>java Test
run method code....
execute method anonymous block of java code.....
return value=10
=============
run method code....
execute method lambda expression code.....
return value=20
Observation:-
If you don’t write any code just you want return value use below code
r.run(() -> 20);
E:\>java Test
run method code....
244 | P a g e
SravyaInfotech Mr. Ratan
Example :-
interface Executable
{ int execute(int a,int b);
}
class Runner
{ public void run(Executable e)
{ System.out.println("run method code....");
int x = e.execute(100,200);
System.out.println("return value="+x);
}
};
public class Test
{ public static void main(String[] args)
{ Runner r = new Runner();
//anonymous inner class code
r.run(new Executable(){
public int execute(int a,int b)
{ System.out.println("execute method anonymous block of java code.....");
return 10+a;
}
});
//lambda expression code
System.out.println("=============");
r.run((int a,int b) -> 20+a+b);
}
};
E:\>java Test
run method code....
execute method anonymous block of java code.....
return value=110
=============
run method code....
return value=320
Observation :-
r.run((a,b) -> 20+a);
E:\>java Test
run method code....
execute method anonymous block of java code.....
return value=110
=============
245 | P a g e
SravyaInfotech Mr. Ratan
246 | P a g e
SravyaInfotech Mr. Ratan
Example :-
interface Executable
{ int execute(int a,int b);
}
class Runner
{ public void run(Executable e)
{ System.out.println("run method code....");
int x = e.execute(100,200);
System.out.println("return value="+x);
}
};
public class Test
{ public static void main(String[] args)
{ int c=10;
//c=c+10; must be comments
Runner r = new Runner();
//anonymous inner class
r.run(new Executable(){
public int execute(int a,int b)
{ System.out.println("execute method anonymous block of java code.....");
return a+b+c;
}
});
//lambda expression
System.out.println("=============");
r.run((int a,int b) -> a+b+c);
}
};
E:\>java Test
run method code....
execute method anonymous block of java code.....
return value=310
=============
run method code....
return value=310
Observation:-
If we remove comments on c=c+10 then we will get fallowing two errors,
E:\>javac Test.java
Test.java:20: error: local variables referenced from an inner class must be final or effectively final
return a+b+c;
247 | P a g e
SravyaInfotech Mr. Ratan
Test.java:25: error: local variables referenced from a lambda expression must be final or effectively final
r.run((int a,int b) -> a+b+c);
2 errors
248 | P a g e
SravyaInfotech Mr. Ratan
Meta annotations:-
it specify information about annotation.
These annotations are present in java.lang.annotation package.
The meta annotations are
o @Retention
o @Target
o @Documented
o @Inherited
o @Repeatable
249 | P a g e
SravyaInfotech Mr. Ratan
Syntax:-
Annotation can be declared using ‘@’ character as prefix of annotation name.
@Annotation
public void annotatedMethod()
{ //logics here
}
Annotations has elements in the form of key=value ,the elements are properties of annotation.
@Annotataion(name="ratan",age="28")
public void annotatedMethod()
{ //logics here
}
If the annotation contains single we can use like this.
@Annotataion(“I am hero”)
public void annotatedMethod()
{ //logics here
}
It possible to declare multiple annotations at class-level
@Annotataion1(name="ratan")
@Annotataion2
public void annotatedMethod()
{ //logics here
}
Uses of annotations:-
Information for the compiler
Annotations are used by the compiler to detect suppress warnings or errors based on rules.
Example :- @Override this one makes the compiler to check the method correctly override or not
@FunctionalInterfacethis one makes the compiler to validate annotated interface is
functional interface or not.
Documentation
Annotations can be used in software applicationsto ensure the quality of the code like bug
finding, report generation…etc
Code generation
Annotations used to generate the code or xml files using meta data information present in the
code.
Runtime processing
Annotations that are used in runtime objectives like unit testing, dependency injection…etc
@Override - Checks that the method is an override. Causes a compile error if the method is not found
in one of the parent classes or implemented interfaces.
250 | P a g e
SravyaInfotech Mr. Ratan
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@override :-
It instructs the compiler to check parent class method is overriding in child class or not if it is not
overriding compiler will generate error message.
In below example if are not declaring @override annotation a new method of marry(int a)
created in child class.
class Parent
{ void marry(String name)
{ //logics-here }
};
class Child extends Parent
{ @Override
void marry(int n)
{ //logics here }
};
E:\>javac Test.java
error: method does not override or implement a method from a supertype
@Override
@Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used.
This annotation represent the marked element is no longer be used. The compiler generates
warning message when we used that marked element.
Example :-
@Deprecated
class Test
{ @Deprecated
void m1()
{//logics here
}
}
class Demo
{ public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
};
E:\>javac Test.java
Note: Test.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
251 | P a g e
SravyaInfotech Mr. Ratan
252 | P a g e
SravyaInfotech Mr. Ratan
al.add("sravya");
System.out.println(al);
}
};
@SafeVarargs - Suppress warnings for all callers of a method or constructor with a generics varargs
parameter, since Java 7.
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface SafeVarargs { }
@Inherited –
Marks another annotation to be inherited to subclasses of annotated class (by default
annotations are not inherited to subclasses).
Example :-
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation
{ }
In above example your annotation can be applied only on methods & constructors because you
specified this information by using @Target annotation.
This annotation is used by JVM at runtime because we specified this information by using
@Retention.
Basically parent class annotation is not visible in child classes but it is possible to inherit parent call
annotation in child class by using @Inherited annotation.
we can create documentation by using javadoc tool because we declared annotation by using
@Documented annotation.
@Repeatable - Specifies that the annotation can be applied more than once to the same declaration,
since Java 8.
253 | P a g e
SravyaInfotech Mr. Ratan
Customized Annotations:-
Annotations can be created by using @interface fallowed by annotation name.
public @interface MyAnnotation
{
}
Every annotation is extending java.lang.annotation.Annotation interface hence annotation can’t
include extend clause.
public interface MyAnnotation extends Annotation
{
}
Example :
Step 1: create the annotation
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation
{ int value();
}
Step-2: Apply the annotation
class Test
{ @MyAnnotation(value=100)
public void m1()
{ System.out.println("m1 method");
}
}
Step 3: Accessing annotation
import java.lang.reflect.*;
class TestClient
{ public static void main(String[] args) throws NoSuchMethodException
{ Test t = new Test();
Method m = t.getClass().getMethod("m1");
MyAnnotation mm = m.getAnnotation(MyAnnotation.class);
System.out.println("value is="+mm.value());
}
}
254 | P a g e
SravyaInfotech Mr. Ratan
Example :-
File-1: ProjectInfo.java
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface ProjectInfo
{ int pid();
String pname() default "bank";
int pteamsize();
String pstatus();
}
File-2:- Emp.java
import java.lang.annotation.*;
@ProjectInfo(pid=111,pstatus="not released",pteamsize=5)
class Emp
{ int eid;
String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
void disp()
{ System.out.println("***Employee details***");
System.out.println("emp id="+eid);
System.out.println("emp name="+ename);
}
public static void main(String[] args)
{ Emp e = new Emp(111,"ratan");
e.disp();
Class c = e.getClass();
Annotation a = c.getAnnotation(ProjectInfo.class);
ProjectInfo p = (ProjectInfo)a;
System.out.println("***project details details***");
System.out.println("project id="+p.pid());
System.out.println("project name="+p.pname());
System.out.println("project status="+p.pstatus());
System.out.println("project teamsize="+p.pteamsize());
}
}
Observation :-
E:\>javadoc Emp.java
Loading source file Emp.java...
255 | P a g e
SravyaInfotech Mr. Ratan
Observation :-
@Target({ElementType.METHOD}) //method level we can use
E:\>javac Emp.java
Emp.java:2: error: annotation type not applicable to this kind of declaration
@ProjectInfo(pid=111,pstatus="not released",pteamsize=5)
Observation :-
@Retention(RetentionPolicy.SOURCE) // ignored at source file level or
@Retention(RetentionPolicy.CLASS) //ignored at class level
E:\>java Emp
***Employee details***
emp id=111
emp name=ratan
***project details details***
Exception in thread "main" java.lang.NullPointerException
Observation :-
@Documented //if we removed this annotation the documentation is not performed
256 | P a g e
SravyaInfotech Mr. Ratan
257 | P a g e
SravyaInfotech Mr. Ratan
Example :
enum EnumMail
{ INBOX,COMPOSE,SENT;
}
class ClassMail
{ public static final int INBOX=1;
public static final int COMPOSE=2;
public static final int SENT=3;
}
class Test
{ static void classConstants(int i)
{ if (i==ClassMail.INBOX)
{ System.out.println("mail inbox operation");
}
else if (i==ClassMail.COMPOSE)
{ System.out.println("mail compose operation");
}
else
{ System.out.println("mail sent operation");
}
}
static void enumConstants(EnumMail e)
{ if (e==EnumMail.INBOX)
{ System.out.println("mail inbox operation"); }
else if (e==EnumMail.COMPOSE)
{ System.out.println("mail compose operation"); }
else
{ System.out.println("mail sent operation"); }
}
public static void main(String[] args)
{ Test.classConstants(1);
Test.classConstants(2);
258 | P a g e
SravyaInfotech Mr. Ratan
Test.classConstants(3);
Test.classConstants(10); //no type safety we can pass any value
Test.enumConstants(EnumMail.COMPOSE);
Test.enumConstants(EnumMail.INBOX);
Test.enumConstants(EnumMail.SENT);
//here were providing type safety it means it is not possible to pass any other values
}
}
In above example classConstants methods it is possible to provide any value as a input but we
can pass fixed values to enumconstants method, so it provides the type safety.
When we change the constants value the program will not generate any error messages the
program might not work as expected. But when we change the enum constants we will get
compiler error which removes runtime error possibilities.
Example :- Inside the enum toString() method overridden to return the name of the constant.
public enum Heroin
{ SAMANTHA,TARA,ANU;
}
class Test
{ public static void main(String... ratan)
{ Heroin s=Heroin.SAMANTHA;
System.out.println(s);
Heroin t=Heroin.TARA;
System.out.println(t);
Heroin a=Heroin.ANU;
System.out.println(a);
}
};
Internal implementation of above example :- (.class file code)
public final class Heroin extends Enum
{ public static Heroin[] values()
{ return (Heroin[])$VALUES.clone();
}
public static Heroin valueOf(String s)
{ return (Heroin)Enum.valueOf(Heroin, s);
}
private Heroin(String s, int i)
{ super(s, i);
}
public static final Heroin SAMANTHA;
public static final Heroin TARA;
public static final Heroin ANU;
private static final Heroin $VALUES[];
static
{ SAMANTHA = new Heroin("SAMANTHA", 0);
TARA = new Heroin("TARA", 1);
ANU = new Heroin("ANU", 2);
$VALUES = (new Heroin[] {
259 | P a g e
SravyaInfotech Mr. Ratan
260 | P a g e
SravyaInfotech Mr. Ratan
{ Beer[] b = Beer.values();
for (Beer bb :b)
{ System.out.println(bb); }
}
}
G:\>java Test
Beer class constructor
Beer class constructor
Beer class constructor
KF
RC
KALYANI
In above example every constant is object three times the constructor will be executed & it is a static
hence it will be executed during .class file loading.
Example :- Inside the enum it is possible to declare parameterized constructors.
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());
}
}
};
int rating;
private Heroin(int rating)
{ this.rating=rating;
}
}
class Test
{ public static void main(String[] arhss)
{ Heroin[] h = Heroin.values();
for (Heroin hh : h)
{ System.out.println(hh+"--Rating--"+hh.rating);
}
}
};
261 | P a g e
SravyaInfotech Mr. Ratan
G:\>java Test
ANUSHKA--Rating--10
UBANU--Rating--1
DEEPIKA--Rating—5
Example :
Inside the enum it is possible to declare the main method but to execute this main method just
execute the .class file.
enum Heroin
{ ANUSHKA,UBANU,DEEPIKA;
public static void main(String[] args)
{ System.out.println("enum class main method");
}
}
G:\>java Heroin
enum class main method
Example :-
enum Heroin
{ //group of constants
ANUSHKA(10),UBANU(20),DEEPIKA(5);
//variable declaration
int value;
//contructor declaration
Heroin(int value)
{ this.value=value;
}
//enum main method
public static void main(String[] args)
{ System.out.println("enum main method");
}
}
class Test
{ public static void main(String[] arhss)
{ //accessing enum constants
Heroin[] h = Heroin.values();
for (Heroin hh : h)
{ System.out.println(hh+"----"+hh.value);
}
262 | P a g e
SravyaInfotech Mr. Ratan
}
};
G:\>java Test
ANUSHKA----10
UBANU----20
DEEPIKA----5
G:\>java Heroin
enum main method
class Gmail
{ enum Mail{ INBOX,COMPOSE,SENT; } //; semicolan optional here
public static void main(String[] args)
{ //class room code
Mail[] mm = Mail.values();
for (Mail mmm : mm)
{ System.out.println(mmm);
}
//project level code
for (Mail m : Mail.values())
{ System.out.println(m);
}
}
}
263 | P a g e
SravyaInfotech Mr. Ratan
}
In above example all case labels are must be enum constants otherwise compiler will generate error
message . case XXX: System.out.println("monday"); //error XXX not a enum type
Example :-
Every enum is final by default hence it is not possible to extends other classes.
Every enum is a final by default hence it is not possible to create child enums.
Example :Every enum internally extends java.lang.Enumhence it is not possible to extends other classes.
class Test
{******}
enum Day extends Test
{*******}
package pack2;
import static pack1.Fish.*;
class Test2
{ public static void main(String[] args)
{ System.out.println(GOLD);
}
}
package pack3;
import pack1.*;
class Test3
{ public static void main(String[] args)
{ Fish f = Fish.STAR;
System.out.println(f);
}
}
264 | P a g e
Durgasoft Mr. Ratan
package pack4;
import pack1.*;
import static pack1.Fish.*;
class Test4
{ public static void main(String[] args)
{ Fish f = Fish.STAR;
System.out.println(GOLD);
}
}
Collectionsframework (java.util)
Pre-requisite topics for Collections framework:-
1) Arrays
2) toString() method.
3) type-casting.
4) interfaces.
5) for-each loop.
6) implementation classes.
7) compareTo() method.
8) Wrapper classes.
9) Marker interfaces advantages.
10) Anonymous inner classes.
11) For-each loop
12) Auto-boxing
Importance of collections:-
The main objective of collections framework is to represent group of object as a single entity.
In java Collection framework provide very good architecture to store and manipulate the group
of objects.
Collection API contains group of classes and interfaces that makes it easier to handle group of
objects.
Collections are providing flexibility to store, retrieve, and manipulate data.
265 | P a g e
Durgasoft Mr. Ratan
9. Java.util.NavigableMap
10. Map.Entry
11. Java.util.Enumeration
12. Java.util.Iterator
13. Java.util.ListIterator
14. Java.lang.Comparable
15. Java.util.Comparator
All collection framework classes and interfaces are present in java.util package.
The root interface of Collection framework is Collection.
Collection interface contains 15 methods so all collection implementation classes are able
to use these methods because collections is a root interface.
266 | P a g e
Durgasoft Mr. Ratan
Collection vs Collections:-
Collection is interface it is used to represent group of objects as a single entity.
Collections is utility class it contains methods to perform operations.
Arrays vs Collections:-
Both Arrays and Collections are used to represent groupof objects as a single entity but the differences
are as shown below.
267 | P a g e
Durgasoft Mr. Ratan
268 | P a g e
Durgasoft Mr. Ratan
Arrays are does not contains underlying data structure hence it is not supporting
predefined methods.
Every collection class contains underlying data structure hence it supports predefined
methods.
Based on underlying data structure the element will be stored.
List interface:-
extends
Stack(c)
1.0 version
Legacy classes:-
The java classes which are introduced in 1.0 version are called legacy classes and java.util
package contains 5 legacy classes.
1) Dictionary 4) Stack
2) HashTable 5) Vector
3) Properties
269 | P a g e
Durgasoft Mr. Ratan
Legacy interfaces:-
The java interfaces which are introduced in 1.0 version are called legacy interfaces and java.util
package contains only one interface is Enumeration.
Java.util.ArrayList:-
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) In ArrayList it is possible to insert Null objects.
4) Duplicate objects are allowed.
5) ArrayList preserved Insertion order it means whatever the order we inserted the data in the
same way output will be printed.
6) ArrayList methods are non-synchronized methods.
7) The under laying data structure is growable array.
8) By using cursor we are able to retrieve the data from ArrayList : Iterator , ListIterator
Example :-
Collections vs Autoboxing
270 | P a g e
Durgasoft Mr. Ratan
Up to 1.4 version we must create wrapper class object then add that object into 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);
}
}
From 1.5 version onwards add the primitive data into ArrayList that data is automatically
converted into wrapper object format is called Autoboxing.
Example-2:-ArrayList vs toString()
Emp.java:- Student.java
class Emp class Student
{ int eid; { int sid;
String ename; String sname;
Emp(int eid,String ename) Student(int sid,String sname)
{ this.eid=eid; { this.sid=sid;
this.ename=ename; this.sname = sname;
} }
} }
Case 1:-
In java when we print reference variable internally it calls toString() method on that object.
271 | P a g e
Durgasoft Mr. Ratan
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()
al.add('a'); //toString()
al.add(e1); //toString()
al.add(s1); //toString()
System.out.println(al); //[10, a, Emp@d70d7a, Student@b5f53a]
System.out.println(al.toString()); //[10, a, Emp@d70d7a, Student@b5f53a]
}
}
Case2:-
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);
al.add('a');
al.add(e1);
al.add(s1);
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);
}
}
}
}
272 | P a g e
Durgasoft Mr. Ratan
add() to add the objects into ArrayList & bydefault it add the data at last but it is possible to insert the
data at specified index.
remove()it removes Objects from ArrayList based on Object & index.
(for the remove(10) method if we are passing integer value that is always treted as index )
size() to find the size of ArrayList.
isEmpty()to check the objects are available or not.
Clear()to remove all objects from ArrayList.
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList al =new ArrayList();
al.add(10);
al.add("ratan");
al.add("anu");
al.add('a');
al.add(10);
al.add(null);
System.out.println("ArrayList data="+al);
System.out.println("ArrayList size-->"+al.size());
al.add(1,"A1"); //add the object at first index
System.out.println("after adding objects ArrayList size-->"+al.size());
System.out.println("ArrayList Data="+al);
al.remove(1); //remove the object index base
al.remove("A"); //remove the object on object base
System.out.println("after removeing elemetns arrayList size "+al.size());
System.out.println("ArrayList data="+al);
System.out.println(al.isEmpty());
al.clear();
System.out.println(al.isEmpty());
}
}
E:\>java Test
ArrayList data=[10, ratan, anu, a, 10, null]
ArrayList size-->6
after adding objects ArrayList size-->7
ArrayList Data=[10, A1, ratan, anu, a, 10, null]
after removeing elemetns arrayList size 6
ArrayList data=[10, ratan, anu, a, 10, null]
false
true
observation:-
in above example when we remove the data by passing numeric value that is by default
treated as a indexvalue.
ArrayList al = new ArrayList();
al.add(10);
al.add("ratan");
273 | P a g e
Durgasoft Mr. Ratan
al.add('a');
System.out.println(al);
al.remove(10); // 10 is taken as index value
whenever we are executing above code then JVM treats that 10 is index value but 10th position
value is not available hence it is generating exception java.lang.IndexOutOfBoundsException: Index:
10, Size: 3
The main purpose of the generics is to provide the type safety to avoid type casting problems.
Arrays [Type safety]:-
Arrays are always type safe it means we can give guarantee for the type of
element present in arrays.
For example if we want to store String objects create String[]. By mistake if we are trying to add any
other data compiler will generate compilation error.
Example:-
String[] str= new String[50];
str[0]="ratan";
str[1]="anu";
str[2]=new Integer(10);
E:\>javac Test.java
incompatible types
str[2]=new Integer(10);
required: String
found: Integer
Based on above error we can give guarantee String[] is able to store only String type of objects. Hence
with respect to the type arrays are recommended to use because it is type safe.
274 | P a g e
Durgasoft Mr. Ratan
275 | P a g e
Durgasoft Mr. Ratan
276 | P a g e
Durgasoft Mr. Ratan
a1.add(e2);
System.out.println(a2.contains(e1));
System.out.println(a2.containsAll(a1));
a2.remove(e1);
System.out.println(a2.contains(e1));
System.out.println(a2.containsAll(a1));
//printing the data
for (Emp e:a2)
{ System.out.println(e.eid+"---"+e.ename);
}
}
}
E:\>java Test
true
true
false
false
222---Sravya
333---aruna
444---anu
Example :-
removeAll(Obj):-
a2.removeAll(a1); // it removes all a1 data.
retainAll(Obj):-
a2.retainAll(a1); // it removes all a2 data except a1
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<Emp> a1 = new ArrayList<Emp>();
a1.add(new Emp(111,"ratan"));
a1.add(new Emp(222,"Sravya"));
a2.removeAll(a1);
a2.retainAll(a1);
for (Emp e:a2)
277 | P a g e
Durgasoft Mr. Ratan
{ System.out.println(e.eid+"---"+e.ename);
}
}
}
//java.lang.IndexOutOfBoundsException: toIndex = 7
//ArrayList<String> a4 = new ArrayList<String>(a1.subList(1,7));
System.out.println("before swapping="+a1);//[ratan, anu, Sravya, yadhu]
Collections.swap(a1,1,3);
System.out.println("after swapping="+a1);// [ratan, yadhu, Sravya, anu]
}
}
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");
278 | P a g e
Durgasoft Mr. Ratan
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
279 | P a g e
Durgasoft Mr. Ratan
al.add("anu");
al.add("Sravya");
System.out.println(al);
}
}
Case 4:-
ArrayList<Type> obj = new ArrayList<Type>(Collections.nCopies(count, object));
import java.util.*;
class ArrayListDemo
{ public static void main(String[] args)
{ Emp e1 = new Emp(111,"ratan");
ArrayList<Emp> al = new ArrayList<Emp>(Collections.nCopies(5,e1));
for (Emp e:al)
{ System.out.println(e.ename+"---"+e.eid);
}
}
}
Case 5:-adding Objects into ArrayList by using addAll() method of Collections class.
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
String[] strArray={"ratan","anu","Sravya"};
Collections.addAll(al,strArray);
System.out.println(al);
}
}
Q. How to get synchronized version of ArrayList?
Ans:- by default ArrayList methods are synchronized but it is possible to get synchronized version of
ArrayList by using fallowing method.
To get synchronized version of List interface use fallowing Collections class static method
public static List synchronizedList(List l)
To get synchronized version of Set interface use fallowing Collections class static method
public static Set synchronizedSet(Set s)
To get synchronized version of Map interface use fallowing Collections class static method
public static Map synchronized Map(Map m)
to get synchronized version of TreeSet use fallowing Collections class static method
Collections.synchronizedSortedSet(SortedSet<T> s)
to get synchronized version of TreeMap use fallowing Collections class static method
Collections.synchronizedSortedMap(SortedMap<K,V> m)
Example:-
ArrayList al = new ArrayList(); //non- synchronized version of ArrayList
List l = Collections.synchronizedList(al); // synchronized version of ArrayList
280 | P a g e
Durgasoft Mr. Ratan
Example-1:
Conversion of String array to ArrayList (by using asList() method):-
import java.util.*;
class ArrayListDemo
{ public static void main(String[] args)
{ String[] str={"ratan","Sravya","aruna"};
ArrayList<String> al = new ArrayList<String>(Arrays.asList(str));
al.add("newperson-1");
al.add("newperson-2");
//printing data by using enhanced for loop
for (String s: al)
{ System.out.println(s);
}
}
}
Example-2:-
Conversion of ArrayList to String array by using toArray( T )
public abstract <T extends java/lang/Object> T[] toArray(T[]);
import java.util.*;
class ArrayListDemo
{ public static void main(String[] args)
{ //interface ref-var & implementaiton class Object
List<String> al = new ArrayList<String>();
281 | P a g e
Durgasoft Mr. Ratan
al.add("anu");
al.add("Sravya");
al.add("ratan");
al.add("natraj");
String[] a = new String[al.size()];
al.toArray(a);
//for-each loop to print the data
for (String s:a)
{System.out.println(s);
}
}
}
Example-3:-
Case-1 :- conversion of ArrayList to Array
public abstract java.lang.Object[] toArray();
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(10);
al.add('c');
al.add("ratan");
//converison of ArrayList to array
Object[] o = al.toArray();
for (Object oo :o)
{ System.out.println(oo);
}
}
}
Case-2 :-
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");
282 | P a g e
Durgasoft Mr. Ratan
283 | P a g e
Durgasoft Mr. Ratan
Cursors in Collections:
Property
1. Purpose
7. Operations
2. Legacy or not
8. Cursor moment
3. Applicable for which type of classes
9. Class or interface
4. Universal cursor or not
10. Versions supports
284 | P a g e
Durgasoft Mr. Ratan
Enumeration
1) Used to retrieve the data from 9) Interface
collection classes.
10) It supports both normal and generic
2) Introduced in 1.0 version it is legacy version.
Iterator
1) Used to retrieve the objects from 6) It contains two methods
collection classes. hasNext(): to check the objects available or not.
Next() : to retrieve the objects.
2) Introduced in 1.2 version it is not a
legacy 7) read & remove operations are possible.
285 | P a g e
Durgasoft Mr. Ratan
Example application:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al =new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("sravya");
//1st appraoch to print Collection data
for (String a : al )
{ System.out.println(a);
}
286 | P a g e
Durgasoft Mr. Ratan
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al =new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("sravya");
ListIterator<String> lstr = al.listIterator();
lstr.add("suneel");
while(lstr.hasNext())
{ if ((lstr.next()).equals("anu"))
{ lstr.set("Anushka");
}
}
lstr.add("aaa");
for (String str:al)
{ System.out.println(str); }
}
}
E:\>java Test
287 | P a g e
Durgasoft Mr. Ratan
suneel
ratan
Anushka
sravya
aaa
if we want remove the data:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al =new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("sravya");
ListIterator<String> lstr = al.listIterator();
while(lstr.hasNext())
{ if ((lstr.next()).equals("ratan"))
{ lstr.remove();
}
}
for (String str:al)
{ System.out.println(str);
}
}
}
E:\>java Test
anu
sravya
Example:-printing data in forward and backward directions.
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al =new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("sravya");
ListIterator<String> lstr = al.listIterator();
System.out.println("printing data forward direction");
while(lstr.hasNext())
{ System.out.println(lstr.next());
}
System.out.println("printing data backward direction");
while(lstr.hasPrevious())
{ System.out.println(lstr.previous());
}
}
}
E:\>java Test
printing data forward direction
288 | P a g e
Durgasoft Mr. Ratan
ratan
anu
sravya
printing data backword direction
sravya
anu
ratan
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("Sravya");
289 | P a g e
Durgasoft Mr. Ratan
}
}
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("Sravya");
Collections.sort(al);
System.out.println("ArrayList data after sorting");
for (String str1 :al)
{ System.out.println(str1);
}
}
}
in above example to perform the sorting of data by using natural sorting order then your objects
must be homogeneous and must implements comparable interface.
The default natural sorting order internally uses compareTo() method to perform sorting and it
compare to objects and it return int value as a return value.
“ratan”.compareTo(“anu”) ==> +ve ==>change the order
“ratan”.compareTo(“ratan”) ==> 0 ==>no change
“anu”.compareTo(“ratan”) ==> -ve ==>no change
290 | P a g e
Durgasoft Mr. Ratan
Example:-
The sorting object(Emp) Not implementing Comparable interface hence it does not perform sorting.
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(new Emp(111,"ratan"));
Collections.sort(al);
}
}
When we execute the above example JVM will generate Exception,
”java.lang.ClassCastException: Emp cannot be cast to java.lang.Comparable”
Example :-
If the Class contains Heterogeneous data sorting is not possible.
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add("ratan");
al.add(10);
Collections.sort(al);//java.lang.ClassCastException
System.out.println(al);
}
}
To overcome above two cases exception use Comparable or Comparator interfaces to perform sorting.
Comparable vs Comparator :-
If we want to perform default natural sorting order then your objects must be
homogeneous & comparable.
Comparable objects are nothing but the objects which are implements comparable
interface.
All wrapper classes & String objects are implementing Comparable interface hence it is
possible to perform sorting.
If we want to sort user defined class like Emp based on eid or ename with
default natural sorting order then your class must implements Comparable
interface.
Comparable interface present in java.lang package it contains only one
method compareTo(obj) then must override that method to write the sorting
logics.
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.
Normal version of comparable:-
Emp.java:-
291 | P a g e
Durgasoft Mr. Ratan
292 | P a g e
Durgasoft Mr. Ratan
Java.utilComparator :-
For the default sorting order use comparable but for customized sorting order we can
use Comparator.
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);
}
Normal version of Comparator:-
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;
293 | P a g e
Durgasoft Mr. Ratan
return (e1.ename).compareTo(e2.ename);
}
}
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
294 | P a g e
Durgasoft Mr. Ratan
Java.lang.Comparable vs java.util.Comparator:-
Property 3. Method calling to 2) Int compareTo(Object o1)
This method compares
1. Sorting logics perform sorting
this object with o1
object and returns
a integer.Its value has
following meaning
4. package positive – this object
is greater than o1
2. Sorting method 5. which type of zero – this object
equals to o1
sorting
negative –this object
is less than o1
Comparable 3) Collections.sort(List)
1) Sorting logics must Here objects will be
be in the class sorted on the basis of
whose class objects CompareTo method.
are sorting.
4) Java.lang
295 | P a g e
Durgasoft Mr. Ratan
java.util.LinkedList:-
public class java.util.LinkedList extends java.util.AbstractSequentialList
implements java.util.List<E>,
java.util.Deque<E>,
java.lang.Cloneable,
java.io.Serializable
1) Introduced in 1.2 version.
2) Heterogeneous objects are allowed.
3) Null insertion is possible.
4) Insertion order is preserved.
5) LinkedList methods are non-synchronized.
6) Duplicate objects are allowed.
7) The under laying data structure is double linkedlist.
8) cursors :- Iterator,ListIterator
constructors:-
LinkedList(); it builds a empty LinkedList.
LinkedList(java/util/Collection<? extends E>);
it builds a LinkedList that initialized with the collection data.
Example:- LinkedList basic operations.
import java.util.*;
class Test
{ public static void main(String[] args)
{ LinkedList<String> l=new LinkedList<String>();
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
296 | P a g e
Durgasoft Mr. Ratan
297 | P a g e
Durgasoft Mr. Ratan
E:\>java Test
Actual LinkedList:[First, Second, Third, Random]
Cloned LinkedList:[First, Second, Third, Random]
Vector constructors:-
Vector();
Vector(int initialCapacity);
Vector(int intialCapacity, int increment);
Vector(java/util/Collection<? extends E>);
Constructor 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
Constructor 2:-
It is possible to create vector with specified capacity by using fallowing constructor. in
this case once vector reaches its maximum capacity then size is double based on provided initial
capacity.
Vector v = new Vector(int initial-capacity);
Vector<String> vv = new Vector<String>(3);
System.out.println(vv.capacity());//3
vv.add("aaa");
vv.add("bbb");
vv.add("ccc");
vv.add("ddd");
298 | P a g e
Durgasoft Mr. Ratan
System.out.println(vv.capacity()); //6
System.out.println(vv.size()); //4
Constructor 3:-
It is possible to create vector with initial capacity and providing increment capacity by
using fallowing constructor.
Vector v = new Vector(int initial-capacity, int increment-capacity);
Vector<String> v = new Vector<String>(2,5);
System.out.println(v.capacity()); //2
v.add("ratan");
v.add("aruna");
v.add("Sravya");
System.out.println(v.capacity()); //7
System.out.println(v.size()); //3
Constructor 4:-
Vector(java/util/Collection<? extends E>);
It creates the Vector that contains another Collection data.
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("no1");
al.add("no2");
Example:-
In below example Vector class removeElement() method removes the data
always based on object but not index.
Vector v=new Vector(); v.removeElement("ratan");
v.addElement("ratan"); System.out.println(v);//[] empty output
299 | P a g e
Durgasoft Mr. Ratan
v.removeElement(0);
Vector v=new Vector(); System.out.println(v); //[ratan]
v.addElement("ratan");
The List interface remove() method removes the data based on index and object.
Vector v=new Vector();
v.addElement("ratan");
v.remove(0);
System.out.println(v);//[] empty output
import java.util.*;
class Test
{ public static void main(String[] args)
{
Vector<Integer> v=new Vector<Integer>();//generic version of vector
for (int i=0;i<5 ;i++ )
{ v.addElement(i);
}
v.addElement(6);
v.removeElement(1); //it removes element object based
Enumeration<Integer> e = v.elements();
while (e.hasMoreElements())
{ Integer i = e.nextElement();
System.out.println(i);
}
v.clear(); //it removes all objects of vector
System.out.println(v);
}
}
E:\>java Test
01246[]
Copying data from Vector to ArrayList:-
To copy data from one class to another class use copy() method of Collections class.
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);
}
300 | P a g e
Durgasoft Mr. Ratan
}
D:\vikram>java Test
[ten, twenty, 30]
301 | P a g e
Durgasoft Mr. Ratan
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();
for (int i=0;i<str.length();i++)
{ stack.push(str.charAt(i));
}
while (!stack.isEmpty())
{ reverse=reverse+stack.pop();
}
if (str.equals(reverse))
{ System.out.println("the input String palindrome");
}
else
{ System.out.println("the input String not- palindrome");
}
}
}
EmpBean.java:-
public class EmpBean implements Comparable<EmpBean>
{ private int eid;
private String ename;
public void setEid(int eid)
{ this.eid=eid;
302 | P a g e
Durgasoft Mr. Ratan
}
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;}
}
};
Set interface:-
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
Java.util.HashSet:-
public class java.util.HashSet extends java.util.AbstractSet
implements java.util.Set<E>,
java.lang.Cloneable,
java.io.Serializable
303 | P a g e
Durgasoft Mr. Ratan
Note:- in entire Collections<E> specifies the type of the Object the Collection
implementation classes will hold.
constructors:-
HashSet(); it creates default HashSet.
HashSet(java/util/Collection<? extends E>);
It initialize the HashSet by passing another collection data.
HashSet(int capacity);
It create the HashSet by specified capacity. And the default capacity of HashSet is 16.
HashSet(int capacity,float fillRatio);
It initialize both capacity and fillratio(also called as load factor) and fillration must be 0.0
to 1.0 after filling this ratio a new HashSet object is created.
The default fill ratio is 0.75.
Note :- The Set interface and HashSet,LinkedHashSet class does not contains new methods it
uses super class methods if you want check the predefined support by using javap command.
Javap java.util.Set
Javap java.util.HashSet
304 | P a g e
Durgasoft Mr. Ratan
Java.util.LinkedHashSet:-
public class java.util.LinkedHashSet extendsjava.util.HashSet
implements java.util.Set<E>,
java.lang.Cloneable,
java.io.Serializable
1. Introduced in 1.4 version and It is a child class of HashSet.
2. Heterogeneous objects are allowed.
3. Duplicate objects are not allowed if we are trying to insert duplicate values then we
won’t get any compilation &Execution errors simply add method return false.
4. Insertion order is preserved.
5. Null insertion is possible only once(because duplication is not possible).
305 | P a g e
Durgasoft Mr. Ratan
Java.util.TreeSet:-
public class java.util.TreeSet extends java.util.AbstractSet<E>
implements java.util.NavigableSet<E>,
java.lang.Cloneable,
java.io.Serializable
<E> specifies the type of the Object the set will be hold.
Constructors:-
TreeSet();
It will create empty TreeSet that will be sorted in ascending order according to natural order of
its elements.
TreeSet(java/util/Collection<? extends E>);
It creates the TreeSet with some collection data.
TreeSet(java/util/Comparator<? super E>);
It will create empty TreeSet with comparator specified sorting order (customization or sorting).
TreeSet(java/util/SortedSet<E>);
It builds the TreeSet that contains the elements of SortedSet.
306 | P a g e
Durgasoft Mr. Ratan
Case 2:-
TreeSet t=new TreeSet();
t.add("ratan");
t.add("anu");
t.add(10); // java.lang.ClassCastException
System.out.println(t);
TreeSet allows homogeneous data, if we are trying to insert heterogeneous data while
performing sorting by using compareTo() JVM will generate java.lang.ClassCastException
(becauseit is not possible to compare integer data with String) .
Case 3:-
TreeSet t=new TreeSet();
t.add("ratan");
t.add(null); //java.lang.NullPointerException
System.out.println(t);
If the TreeSet contains data if we are trying to insert null value at the time of comparison JVM
will generate //java.lang.NullPointerException.
In java any object with comparison of null it will generate java.lang.NullPointerException.
307 | P a g e
Durgasoft Mr. Ratan
308 | P a g e
Durgasoft Mr. Ratan
t.add(30);
System.out.println(t);
}
}
import java.util.*;
class MyComp implements Comparator
{ public int compare(Object o1,Object o2)
{ Integer i1 = (Integer)o1;
Integer i2 = (Integer)o2;
//check all possibilities by placing comments
//return i1.compareTo(i2);
//return -i1.compareTo(i2);
//return i2.compareTo(i1);
//return -i2.compareTo(i1);
//return -1;
//return +1;
//return 0;
}
}
Observation-1:
in above example at line number-1 if we are not passing comparator object then JVM will call
compareTo() method as part of default sorting order .
Based on above line the default sorting will done by using compareTo() method.
Observation-2:-
In above example at line number 1 if we are passing comparator object then JVM will call
compare() method to perform sorting instead of compareTo() method.
Example :-write a program to insert String data into TreeSet to perform sorting in reverse of
alphabetical order.
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeSet<String> t = new TreeSet<String>(new MyComp());
t.add("ratan");
t.add("anu");
t.add("aravya");
t.add("aruna");
System.out.println(t);
}
}
class MyComp implements Comparator<String>
{ public int compare(String s1,String s2)
{ return s2.compareTo(s1);
//return -s1.compareTo(s2);
}
};
309 | P a g e
Durgasoft Mr. Ratan
Example :-write a program to insert StringBuffer data into TreeSet to perform sorting in alphabetical
order.
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeSet<StringBuffer> t = new TreeSet<StringBuffer>(new MyComp());
t.add(new StringBuffer("ccc"));
t.add(new StringBuffer("aaa"));
t.add(new StringBuffer("ddd"));
t.add(new StringBuffer("bbb"));
System.out.println(t);
}
}
class MyComp implements Comparator<StringBuffer>
{ public int compare(StringBuffer sb1,StringBuffer sb2)
{ String s1 = sb1.toString();
String s2 = sb2.toString();
//return s2.compareTo(s1);
return -s1.compareTo(s2);
}
};
Example :- write a program to insert String & StringBuffer object into TreeSet, where sorting is
increasing length order. If two objects are having same length then use alphabetical order.
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeSet t = new TreeSet(new MyComp());
t.add("ratan");
t.add(new StringBuffer("sravya"));
t.add("anu");
t.add(new StringBuffer("suneelbabu"));
t.add("sri");
System.out.println(t);
}
}
class MyComp implements Comparator
{ public int compare(Object o1,Object o2)
{ String s1 = o1.toString();
String s2 = o2.toString();
int l1=s1.length();
int l2=s2.length();
if (l1<l2)
{ return -1;
}
else if (l1>l2)
{ return 1;
}
else
310 | P a g e
Durgasoft Mr. Ratan
{ return s1.compareTo(s2);
}
}
};
Example:- passing sortedset object to TreeSet constructor.
import java.util.*;
class Sravya
{ public static void main(String[] args)
{ TreeSet<Integer> t=new TreeSet<Integer>();
t.add(20);
t.add(40);
t.add(10);
t.add(30);
System.out.println(t); //10 20 30 40
SortedSet s = t.headSet(30);
TreeSet tt = new TreeSet(s);
System.out.println(tt); //10 20
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
311 | P a g e
Durgasoft Mr. Ratan
312 | 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
Java.util.HashMap:-
public class java.util.HashMap extendsjava.util.AbstractMap
implements java.util.Map
java.lang.Cloneable,
java.io.Serializable
1) introducedin 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 it is based on hashcode.
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.
Constructors:-
HashMap();it creates default HashMap.
HashMap(java/util/Map<? extends K, ? extends V> var);
it creates the HashMap by initializing the values specified in var.
HashMap(int capacity);
It creates the hashmap with specified capacity but the default capacity is 16.
HashMap(int capacity, float fillRatio);
It creates the hashMap with specified capacity & fillRatio.(default capacity is 16 & default fill
ratio 0.75)
Entry:-
The each and every key value pair is called Entry.
The Map contains group of entries.
Entry is sub interface of Map interface hence get the entry interface by using Map interface.
interface Map
{ interface Entry
313 | P a g e
Durgasoft Mr. Ratan
Example :-
import java.util.*;
class Test
{ public static void main(String[] args)
{ HashMap h = new HashMap();
h.put(111,"ratan");
h.put(222,"anu");
h.put(333,"banu");
//keySet() to get all keys.
Set s1=h.keySet();
System.out.println("all keys:--->"+s1);
//values() to get all the values.
Collection c = h.values();
System.out.println("all values--->"+c);
//entrySet() to get all the entries.
Set ss = h.entrySet();
System.out.println("all entries--->"+ss);
Iterator itr = ss.iterator();
while (itr.hasNext())
{ Map.Entry m= (Map.Entry)itr.next();
System.out.println(m.getKey()+"----"+m.getValue());
}
}
};
E:\>java Test
all keys:--->[222, 111, 333]
all values--->[anu, ratan, banu]
all entries--->[222=anu, 111=ratan, 333=banu]
222----anu
111----ratan
333----banu
Java.util.LinkedHashMap:-
public class java.util.LinkedHashMap extends java.util.HashMap
implements java.util.Map
1) interdicted in 1.4 version
2) Heterogeneous data allowed.
314 | P a g e
Durgasoft Mr. Ratan
Constructors:-
LinkedHashMap();it creates default HashMap.
LinkedHashMap(java/util/Map<? extends K, ? extends V> var);
it creates the HashMap by initializing the values specified in var.
LinkedHashMap(int capacity);
It creates the hashmap with specified capacity but the default capacity is 16.
LinkedHashMap(int capacity, float fillRatio);
It creates the hashMap with specified capacity & fillRatio.(default capacity is 16 & default fill
ratio 0.75)
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)
{ LinkedHashMap<Emp,Student> h = new LinkedHashMap<Emp,Student>();
h.put(new Emp(111,"ratan"), new Student(1,"budha"));
h.put(new Emp(222,"anu"), new Student(2,"ashok"));
Set s = h.entrySet();
Iterator itr = s.iterator();
while (itr.hasNext())
{ Map.Entry m = (Map.Entry)itr.next();
Emp e = (Emp)m.getKey();
System.out.println(e.ename+"--"+e.eid);
Student ss = (Student)m.getValue();
System.out.println(ss.sname+"--"+ss.sid);
}
}
}
Example:-
315 | P a g e
Durgasoft Mr. Ratan
import java.util.*;
class Test
{ public static void main(String[] args)
{
Map<Integer,String> h1 = new LinkedHashMap<Integer,String>();
h1.put(111,"ratan");
h1.put(222,"sravya");
HashMap vs ConcurrentHashMap:-
HashMap is not Thread safe but concurrentHashMap is Thread-safe that is code can accessed by
single thread at a time
HashMap can be synchronized by using Collections class synchronizedMap() method but
ConcurrentHashMap method are by default synchronized.
HashMap allows only one null key and any number of null values but ConcurrentHashMap does
not allow null for keys & values.
Java.util.HashTable:-
public class java.util.Hashtable extends java.util.Dictionary
implements java.util.Map,java.lang.Cloneable, java.io.Serializable
1. Introduced in the 1.0 version it’s a legacy class.
2. Heterogeneous data allowed for both key & value.
3. Duplicate keys are not allowed but values can be duplicated.
4. Every method is synchronized hence only one thread is allowed to access it is a Thread safe but
performance is decreased.
5. Null is not allowed for both key & Value , if we are trying to insert null values we will get
NullPointerException.
6. HashTable was made generic by JDK5.
7. The underlaying datastructure is hashtable.
Constructors:-
HashTable();it creates default HashMap.
316 | P a g e
Durgasoft Mr. Ratan
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);
}
}
}
Java.util.TreeMap:-
public class java.util.TreeMap extends java.util.AbstractMap
implements java.util.NavigableMap,java.lang.Cloneable, java.io.Serializable
1) This class is introduced in 1.2 version.
2) It allows homogeneous data if we are trying to insert heterogeneous data at runtime while perform
sorting JVM will generate ClassCastException.
317 | P a g e
Durgasoft Mr. Ratan
318 | P a g e
Durgasoft Mr. Ratan
tmain.put("anu","no2");
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);
}
}
Example:-
import java.util.*;
class MyComp implements Comparator
{ public int compare(Object o1,Object o2)
{ String s1 = (String)o1;
String s2 = (String)o2;
return s2.compareTo(s1);
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeMap h = new TreeMap(new MyComp());
h.put("ratan",111);
h.put("anu",222);
319 | P a g e
Durgasoft Mr. Ratan
h.put("zzzz",333);
System.out.println(h);//{zzzz=333, ratan=111, anu=222}
}
}
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeMap h = new TreeMap();
h.put(111,"ratan");
h.put(222,"anu");
h.put(333,"aaa");
h.put(444,"aaa");
System.out.println(h);
Map m = h.subMap(222,444);
System.out.println(m);
System.out.println(h.firstEntry());
System.out.println(h.lastEntry());
System.out.println(h.firstKey());
System.out.println(h.lastKey());
System.out.println(h.lowerKey(222));
System.out.println(h.higherKey(222));
SortedMap s1 = h.headMap(333);
TreeMap t1 = new TreeMap(s1);
System.out.println(t1);
SortedMap s2 = h.tailMap(333);
TreeMap t2 = new TreeMap(s2);
System.out.println(t2);
}
}
Example :-
Ceiling()
it return current provided value or greater value but if treemap does not contains same or grater
value then it returns null .
floor():-
it returns current value or less value but if treemap does notcontains same value or less then it
return null.
pollFirstEntry:- it removes first entry & it prints that entry.
pollLastEntry():- it removes last entry and it prints that entry.
import java.util.*;
class Test
320 | P a g e
Durgasoft Mr. Ratan
System.out.println(h.ceilingKey(222));
System.out.println(h.ceilingEntry(333));
System.out.println(h.floorKey(222));
System.out.println(h.floorEntry(333));
System.out.println(h.ceilingKey(666));
Map.Entry m1 = h.pollFirstEntry();
System.out.println(m1.getKey()+"---"+m1.getValue());
Map.Entry m2 = h.pollLastEntry();
System.out.println(m2.getKey()+"---"+m2.getValue());
System.out.println(h);
}
}
Java.util.IdentityHashMap:-
public class java.util.IdentityHashMap extends java.util.AbstractMap
implements java.util.Map,java.io.Serializable, java.lang.Cloneable
321 | P a g e
Durgasoft Mr. Ratan
E:\>java Test
{10=anu}
{10=anu, 10=ratan}
Java.util.WeakHashMap:-
public class java.util.WeakHashMap extends java.util.AbstractMap
implements java.util.Map
HashMap WeakHashMap
import java.util.*; import java.util.*;
class A class A
{ public String toString() { public String toString()
{ return "A"; { return "A";
} }
public void finalize() public void finalize()
{System.out.println("object destroyed"); {System.out.println("object destroyed");
} }
}; };
class Test class Test
{ public static void main(String[] args) { public static void main(String[] args)
{ HashMap h = new HashMap(); {WeakHashMap h = new WeakHashMap();
A a= new A(); A a= new A();
h.put(a,"ratan"); h.put(a,"ratan");
System.out.println(h); System.out.println(h);
a=null; a=null;
System.gc(); System.gc();
System.out.println(h); System.out.println(h);
} }
} }
E:\>java Test E:\>java Test
{A=ratan} {A=ratan}
{A=ratan} {}
object destroyed
Java.util.Properties:-
In standalone applications(JDBC) or web-applications(web sites)the data is frequently changing
like,
a. Database username
b. Database password
c. url
d. driver …etc
322 | P a g e
Durgasoft Mr. Ratan
in above scenario for every change must perform modifications in all .java files but it is
complex.to overcome this problem use properties file.
Properties file is a normal text file with .properties extension & it contains key=value formatted
data but both key and value is string format.
Once we done modifications on .properties file that modifications are reflected all the .java files.
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();
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");
//use the properties file data
System.out.println("DataBase username="+username);
System.out.println("DataBase password ="+password);
System.out.println("driver ="+driver);
System.out.println("trainer="+trainer);
}
}
Collections:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("Sravya");
//to perform sorting use sort method of collections class
Collections.sort(al);
Iterator itr =al.iterator();
323 | P a g e
Durgasoft Mr. Ratan
while (itr.hasNext())
{System.out.println(itr.next());
}
}
}
Comparable interface :-
Comparable interface used to perform sorting of user defined class objects.
Comparable present in java.lang package and it contains only method
public abstract int compareTo(Object obj-name);
By using comparable We areable sort the object by suing single data member like
sid,sname.
String & all Wrapper classes are implement Comparable interface hence if we are
storing these Objects these are comparable.
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
{ 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"));
324 | P a g e
Durgasoft Mr. 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;
}
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);
325 | P a g e
Durgasoft Mr. Ratan
}
}
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)
{
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.
326 | P a g e
Durgasoft Mr. Ratan
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:-
We are having two types of networks
1) Per-to-peer network.
2) Client-server network.
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.
327 | P a g e
Durgasoft Mr. Ratan
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 ----> Valid
b. 124.654.5.6 ----> Invalid
c. 1.2.3.4.5.6 ----> Invalid
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
Example:-
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.google.com
The IP Address is:www.google.com/74.125.236.176
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.
URL(Uniform Resource Locator):-
1) URL is a class present in the java.net package.
2) By using the URL we are accessing some information present in the world wide web.
328 | P a g e
Durgasoft Mr. Ratan
TCP
IP
Physical Layer
329 | 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.
330 | P a g e
Durgasoft Mr. Ratan
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();
331 | P a g e
Durgasoft Mr. Ratan
Java.awt package
AWT(Abstract Window Tool kit) is an API it supports graphical user interface programming.
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.
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.
332 | P a g e
Durgasoft Mr. Ratan
Java.awt.Frame:-
Frame is a container it contains other components like title bar, Button, Text Field...etc.
333 | P a g e
Durgasoft Mr. Ratan
When we create a Frame class object. Frame will be created automatically with invisible mode,
so to provide the 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 frame is created with initial size 0 pixel heights& 0 pixel
widthhence it is not visible.To provide particular size to the Frame use setSize() method.
public void setSize(int width,int height)
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)
334 | P a g e
Durgasoft Mr. Ratan
2. To set a particular font to the text use Font class present in java.awt package
Font f=new Font(String type,int style,int size);
Font f= new Font("arial",Font.Bold,30);
Example :-
import java.awt.*;
class MyFrame extends Frame
{ public static void main(String[] args)
{ MyFrame t = new MyFrame();
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);
}
}
In above example when we create the MyFrame class object ,jvm will executes MyFrame
classconstructor just before this JVMwill execute Frame class zero argument constructor.
The Frame class zero argument constructor calling repaint() method & this method will access
predefined Frame class paint() method. But as per the requirement overriding paint() method
will be executed.
Preparation of components:-
1. Label: -Label is a constant text which is displayed along with a TextField or TextArea.
335 | P a g e
Durgasoft Mr. Ratan
Example :-
import java.awt.*;
class MyFrame
{ MyFrame()
{ Frame f=new Frame();
f.setVisible(true);
f.setTitle("ratan");
f.setBackground(Color.red);
f.setSize(400,500);
f.setLayout(new FlowLayout()); //information about layout check next page
Label l1=new Label("user name:");
Label l2=new Label("user password:");
f.add(l1);
f.add(tx1);
f.add(l2);
f.add(tx2);
f.add(b);
}
public static void main(String[] args)
{ MyFrame f = new MyFrame();
}
}
5. Choice:-List is allows to select multiple items but choice is allow to select single Item.
Choice ch=new Choice();
336 | P a g e
Durgasoft Mr. Ratan
7. Checkbox: - The user can select more than one checkbox at a time.
Checkbox cb2=new Checkbox(“MCA”);
337 | P a g e
Durgasoft Mr. Ratan
Layout Managers:-
338 | P a g e
Durgasoft Mr. Ratan
When we are trying to add the components into container without using layout manager the
components are overriding hence the last added component is visible on the container instead of all.
To overcome above problem to arrange the components into container in specific manner use
layout manager.
http://java.icmc.usp.br/books/ooc/html/gui_layout_manager.html
Definitions:-
The layout managers are used to arrange the components in a Frame in particular manner.or
A layout manager is an object that controls the size and the position of components in a container
Different layouts in java,
1) java.awt.FlowLayout
2) java.awt.BorderLayout
3) java.awt.GridLayout
4) java.awt.CardLayout
5) java.awt.GridBagLayout
java.awt.FlowLayout
The FlowLayout is used to arrange the components into row by row format. Once the first row is
filled with components then it is inserted into second row. And it is the default layout of the applet.
Java.awt.BorderLayout:-
The BoderLayout is dividing the frame into five areas north,south,east,west,center so we can
arrange the components in these five areas.
To represent these five areas borderlayout is providing the fallowing 5-constans
import java.awt.*;
class MyFrame extends Frame
{ Button b1,b2,b3,b4,b5;
MyFrame()
{ //this keyword is optional because all methods are current class methods only
this.setSize(400,400);
this.setVisible(true);
this.setTitle("BorderLayout");
this.setLayout(new BorderLayout());
b1=new Button("Boys");
b2=new Button("Girls");
b3=new Button("management");
b4=new Button("Teaching Staff");
b5=new Button("non-teaching staff");
this.add("North",b1);
this.add("Center",b2);
this.add("South",b3);
339 | P a g e
Durgasoft Mr. Ratan
this.add("East",b4);
this.add("West",b5);
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
f.add(new Button("NORTH"),BorderLayout.NORTH);
f.add(new Button("SOUTH"),BorderLayout.SOUTH);
f.add(new Button("EAST"),BorderLayout.EAST);
f.add(new Button("WEST"),BorderLayout.WEST);
f.add(new Button("CENTER"),BorderLayout.CENTER);
}
}
340 | P a g e
Durgasoft Mr. Ratan
2. To make static component into dynamic component we have to add some actions to the Frame.
To attach these actions to the Frame component we need event delegation model.
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. Wherever
we are adding listeners to the component the component is able to respond based on the
generated event.
3. java.awt.event package contains listeners and event classes for event handling.
4. The listeners are different from component to component.
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
341 | P a g e
Durgasoft Mr. Ratan
Note: -
To attach a particular listener to the Frame we have to use foll
owing 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);
342 | P a g e
Durgasoft Mr. Ratan
343 | P a g e
Durgasoft Mr. Ratan
344 | P a g e
Durgasoft Mr. Ratan
Note : if our class implements WindowListener interface we must override all the methods of
windowListener interface . But if our class extends windowAdaptor class it is possible to override
application required methods.
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("MyFrame");
this.addWindowListener(new Listenerimpl());
}
};
class Listenerimpl extends WindowAdapter
{ public void windowClosing(WindowEvent we)
{ System.exit(0);
345 | P a g e
Durgasoft Mr. Ratan
}
};
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
346 | P a g e
Durgasoft Mr. Ratan
}
}
class FrameEx
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
********CardLayout*************
import java.awt.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setSize(400,400);
this.setVisible(true);
this.setLayout(new CardLayout());
Button b1=new Button("button1");
Button b2=new Button("button2");
Button b3=new Button("button3");
Button b4=new Button("button4");
Button b5=new Button("button5");
this.add("First Card",b1); this.add("Second Card",b2);
this.add("Thrid Card",b3); this.add("Fourth Card",b4);
this.add("Fifth Card",b5);
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
********GRIDLAYOUT**********
import java.awt.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
347 | P a g e
Durgasoft Mr. Ratan
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();
}
};
Example :-ACTIONLISTENER
The below example we are preforming addition and multiplications when we click add & mul
buttons. So whenever we clicking button the button is able to listen the even to do this add the Listener
to button.
The appropriate listener for button is 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");
348 | P a g e
Durgasoft Mr. Ratan
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();
}
}
};
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()
349 | P a g e
Durgasoft Mr. Ratan
{ 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)
{
Font f=new Font("arial",Font.BOLD,30);
g.setFont(f);
this.setForeground(Color.green);
g.drawString("Status:----"+status,50,300);
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
350 | P a g e
Durgasoft Mr. Ratan
******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);
m1.add(mi3);
}
public void actionPerformed(ActionEvent ae)
{ label=ae.getActionCommand();
repaint();
}
351 | P a g e
Durgasoft Mr. Ratan
*****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();
}
public void mouseEntered(MouseEvent e)
{ msg[3]="mouse entered......("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseExited(MouseEvent e)
{ msg[4]="mouse exited......("+e.getX()+","+e.getY()+")";
repaint();
}
public void paint(Graphics g)
{ int X=50;
int Y=100;
352 | P a g e
Durgasoft Mr. Ratan
for(int i=0;i<msg.length;i++)
{ if (msg[i]!=null)
{ g.drawString(msg[i],X,Y);
Y=Y+50;
}
}
}
};
class Demo
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
*******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");
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);
353 | P a g e
Durgasoft Mr. Ratan
class rc
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
*********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());
}
354 | P a g e
Durgasoft Mr. Ratan
};
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);
ch=new Choice();
ch.add("hyd"); ch.add("chenni"); ch.add("Banglore");
ch.addItemListener(this);
355 | P a g e
Durgasoft Mr. Ratan
}
public void paint(Graphics g)
{ Font f=new Font("arial",Font.BOLD,20);
g.setFont(f);
String utech="";
for(int i=0;i<tech.length ;i++ )
{ utech=utech+tech[i]+" "; }
g.drawString("tech:-------"+utech,50,200);
g.drawString("city---------"+city,50,300);
utech="";
}
}
class Demo
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
*********AdjustmentListener**********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements AdjustmentListener
{ Scrollbar sb;
int position;
myframe()
{ this.setSize(400,400);
this.setVisible(true);
this.setLayout(new BorderLayout());
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)
{ g.drawString("position:"+position,100,200);
repaint();
}
}
class scrollbarex
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
356 | P a g e
Durgasoft Mr. Ratan
SWINGS
1. Sun Micro Systems introduced AWT to prepare GUI applications but awt components not satisfy
the client requirement.
2. An alternative to AWT Netscape Communication Corporation has provided set of GUI
components in the form of IFC(Internet Foundation Class) but IFC also provide less performance
and it is not satisfy the client requirement.
3. In the above context[sun &Netscape] combine and introduced common product to design GUI
applications is called JFS(java foundation classes) then it is renamed as swings.
357 | P a g e
Durgasoft Mr. Ratan
358 | P a g e
Durgasoft Mr. Ratan
Example :-
package swingss;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyFrame extends JFrame{
public MyFrame() {
setVisible(true);
setSize(300, 300);
setTitle("MyFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
JLabel label = new JLabel("Hello World:");
JButton button = new JButton("click me");
add(label);
add(button);
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
}
}
Example 2:-
package swingss;
import java.awt.*;
import javax.swing.*;
class Test2 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;
Test2()
{ setVisible(true);
setSize(150,500);
setTitle("SWING GUI COMPONENTS EXAMPLE");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
getContentPane().setBackground(Color.red);
359 | P a g e
Durgasoft Mr. Ratan
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");
add(l1);
add(tf); add(l2); add(pf);
add(l3); add(cb1); add(cb2); add(cb3);
add(l4); add(rb1); add(rb2); add(l5);
add(l); add(l6); add(cb); add(l7);
add(ta); add(b);
}
public static void main(String[] args)
{ Test2 f=new Test2();
}
};
360 | P a g e
Durgasoft Mr. Ratan
Example 3:
package swingss;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
361 | P a g e
Durgasoft Mr. Ratan
Example 4:-
package swingss;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
public class MyFrame2 extends JFrame implements ActionListener {
JRadioButton button1,button2;
JButton button;
public MyFrame2() {
setVisible(true);
setTitle("MyFrame");
setSize(300, 300);
setLayout(new FlowLayout());
362 | P a g e
Durgasoft Mr. Ratan
Example 5:
package swingss;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class MyFrame3 extends JFrame {
public MyFrame3() {
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[][] data={{"101","ratan","10000"},{"102","anu","20000"},{"101","durga","30000"}};
String[] col={"Eid","Ename","Esal"};
JTable jTable = new JTable(data,col);
add(jTable);
Application 6: - JCOLORCHOOSER
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyFrame extends JFrame implements ChangeListener
{ JColorChooser cc;
Container c;
MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.setTitle("SWING GUI COMPONENTS EXAMPLE");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
363 | P a g e
Durgasoft Mr. Ratan
c=getContentPane();
cc=new JColorChooser();
cc.getSelectionModel().addChangeListener(this);
c.add(cc);
}
public void stateChanged(ChangeEvent c)
{ Color color=cc.getColor();
JFrame f=new JFrame();
f.setSize(400,400);
f.setVisible(true);
f.getContentPane().setBackground(color);
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
Application 7: JFILECHOOSER
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyFrame extends JFrame implements ActionListener
{ JFileChooser fc;
Container c;
JLabel l;
JTextField tf;
JButton b;
MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.setTitle("SWING GUI COMPONENTS EXAMPLE");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=getContentPane();
l=new JLabel("Select File:");
364 | P a g e
Durgasoft Mr. Ratan
tf=new JTextField(25);
b=new JButton("BROWSE");
this.setLayout(new FlowLayout());
b.addActionListener(this);
c.add(l); c.add(tf); c.add(b);
}
public void actionPerformed(ActionEvent ae)
{ class FileChooserDemo extends JFrame implements ActionListener
{ FileChooserDemo()
{ Container c=getContentPane();
this.setVisible(true);
this.setSize(500,500);
fc=new JFileChooser();
fc.addActionListener(this);
fc.setLayout(new FlowLayout());
c.add(fc);
}
public void actionPerformed(ActionEvent ae)
{ File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
tf.setText(path);
this.setVisible(false);
}
}
new FileChooserDemo();
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
365 | P a g e
Durgasoft Mr. Ratan
Java.awt.Applet
The applet is runs on browser window to display the dynamic content on browser window.
The applet does not contains main methods to start the execution but it contains life cycle
methods these methods are automatically called by web browser.
To run the applet in browser window we need to install plugin in.
366 | P a g e
Durgasoft Mr. Ratan
Firstapplet.html
<html>
<body>
<applet code="Test.class" height="300" width="300"/>
</body>
</html>
Execution : appletviewer Firstapplet.html
Running applet:-
It is possible to run the applet in two ways
1) By using html file
Configure the applet in html file then open the html file in browser window.
Click on Firstapplet.html then the applet is displayed on browser window.
367 | P a g e
Durgasoft Mr. Ratan
Application 2:
Test.java:-
import java.awt.*;
import java.applet.*;
public class Test extends Applet
{ String msg="";
public void paint(Graphics g)
{ Font f=new Font("arial",Font.BOLD,20);
g.setFont(f);
g.drawString("Durga Software Solutions "+msg,100,200);
}
public void init()
{ msg=msg+"initialization"+" ";
System.out.println("init()");
}
public void start()
{ msg=msg+"starting"+" ";
System.out.println("start()");
}
public void stop()
{ msg=msg+"stoping";
System.out.println("stop()");
}
public void destroyed()
{ msg=msg+"destroyed";
System.out.println("destroy()");
}
};
Configuration of Applet:-
<html>
<applet code="Test.class" width="500" height="500">
</applet>
</html>
368 | P a g e
Durgasoft Mr. Ratan
Test.java:
import java.awt.*;
import java.applet.*;
public class Test extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"flower.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
Firstapplet.html
<html>
<body>
<applet code="Test.class" height="300" width="300"></applet>
</body>
</html>
369 | 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;
370 | P a g e
Durgasoft Mr. Ratan
371 | 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
372 | 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
373 | 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
??????
? ???? ???
? ??? ?
374 | 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.
375 | 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);
}
}
376 | 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"));
377 | 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
378 | 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:-
379 | 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));
}
};
380 | P a g e
Durgasoft Mr. Ratan
JVM Architecture:-
381 | 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.
382 | 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”.
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
proof 2:- in eclips IDE shows information like this.
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
Without creation of object we are able to achieve application requirement by using static methods.
class Test
{ static void m1()
{ System.out.println("hi ratan");
}
383 | 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:-
384 | P a g e
Durgasoft Mr. Ratan
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;
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");
385 | P a g e
Durgasoft Mr. Ratan
a[i]=s.nextInt();
}
for (int a1:a)
{ System.out.println(a1);
}
}
}
386 | P a g e
Durgasoft Mr. Ratan
387 | P a g e
Durgasoft Mr. Ratan
388 | P a g e
Durgasoft Mr. Ratan
389 | P a g e
Durgasoft Mr. Ratan
390 | P a g e
Durgasoft Mr. Ratan
System.out.println(a[0][0]);//10
System.out.println(a[1][0]);//40
System.out.println(a[1][1]);//50
}
} 0 1
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]);
}
}
391 | P a g e
Durgasoft Mr. Ratan
392 | P a g e
Durgasoft Mr. Ratan
System.out.println(a); //9
//post decrement
int b=20;
System.out.println(b); //20
System.out.println(--b); //19
System.out.println(b); //19
System.out.println(a-- + --a + a-- + --a);
//9 7 7 5
}
}
393 | P a g e
Durgasoft Mr. Ratan
394 | P a g e
Durgasoft Mr. Ratan
395 | P a g e
Durgasoft Mr. Ratan
15) What do you mean by transfer statements and what are transfer statements present in
java?
16) for (; ;) representing?
17) When we will get compilation error like “unreachable statement “?
18) Is it possible to declare while without condition yes -what is default condition
nowhat is error?
19) What is the difference between while and do-while?
20) While declaring if , if-else , switch curly braces are optional or mandatory?
Oops
1) What are the main building blocks of oops?
2) What do you mean by inheritance?
3) How to achieve inheritance concept and inheritance is also known as?
4) How many types of inheritance in java and how many types of inheritance not
supported by java?
5) How to prevent inheritance concept?
6) If we are extending the class then your class will become parent class but if we are not
extending what is the parent class?
7) One class able to extends how many classes at a time?
8) What is the purpose of extends keyword?
9) What do you mean by cyclic inheritance java supporting or not?
10) What is the difference between child class and parent class?
11) Which approach is recommended to create object either parent class object or child class
object?
12) Except one class all class contains parent class in java what is that except class?
13) What is the purpose of instanceof keyword in java?
14) What is the root class for all java classes?
15) How to call super class constructors?
16) Is it possible to use both super and this keyword inside the method?
17) Is it possible to use both super and this keyword inside the constructor?
18) Inside the constructor if we are not providing this() and super() keyword the compiler
generated which type of super keyword?
19) What is the execution process of constructors if two classes are there in inheritance
relationship?
20) What is the execution process of instance blocks if two classes are there in inheritance
relationship?
21) What is the execution process of static blocks if two classes are there in inheritance
relationship?
22) What is the purpose of instanceof operator in java & what is the return-type?
23) If we are using instanceof both reference-variable & class-name must have some
relationship otherwise compiler generated error message is what?
24) If the child class and parent class contains same variable name that situation how to call
parent class variable in child class?
25) What do you mean by aggregation and what is the difference between aggregation and
inheritance?
26) What do you mean by aggregation and composition and Association?
27) Aggregation is also known as?
396 | P a g e
Durgasoft Mr. Ratan
397 | P a g e
Durgasoft Mr. Ratan
71) How many ways area there to set some values to class properties (variables)?
72) What do you mean by javaBean class?
73) The javabean class is also known as?
74) In java program execution starts from which method & who is calling that method?
75) Can we inherit main method in child class?
76) The applicable modifiers on main method?
77) While declaring main method public static modifiers order mandatory or optional?
78) What is the argument of main method?
79) What is the return type of main method?
80) What are the mandatory modifiers for main method and optional modifiers of main
method?
81) Why main method is public &static?
82) What do you by command line arguments& command line arguments are stored in
which format(type)?
83) Is it possible to pass command line arguments with space symbol nowhy yeshow ?
84) What is the purpose of strictfp modifier?
85) What is the purpose of native modifier?
86) What do you mean by native method and it also known as?
87) Is it possible to overload the main method or notyes=how no=why?
88) Is it possible to override the main method or not yes=how no=why?
89) What is the purpose of variable argument method & what is the syntax?
90) If the application contains both normal argument & variable argument then which one
executed first?
91) The java method allows both variable argument & normal argument in single method?
92) Is it possible to overload the variable argument methods are not?
93) What is the difference between method overloading & variable argument method.
94) What are the modification are allowed on main method?
95)
Packages
1. What do you mean by package and what it contains?
2. How many pre-defined packages in java?
3. What is the default package in java?
4. Is it possible to declare package statement any statement of the source file?
5. What is the difference between user’s defined package and predefined package?
6. What are coding conventions must fallow while declaring user defined package names?
7. Is it possible to declare multiple packages in single source file?
8. What do you mean by import?
9. What is the location of predefined packages in our system?
10. How many types of imports present in java explain it?
11. How to import individual class and all classes of packages and which one is recommended?
12. What do you mean by static import?
13. What is the difference between normal and static import?
14. I am importing two packages, both packages contains one class with same name at that situation how
to create object of two package classes?
398 | P a g e
Durgasoft Mr. Ratan
15. If we are importing root package at that situation is it possible to use sub package classes in our
applications?
16. What is difference between main package and sub package?
17. If source file contains package statement then by using which command we are compiling that source
file?
18. What do you mean by fully qualified name of class?
19. What is the default modifier in java?
20. What is the public access and default access?
21. The public class members(variables,methods,constructors) are by default public or not?
22. What is private access and protected access?
23. What is most restricted modifier in java?
24. What is most accessible modifier in java?
25. Is it possible to declare pre-defined package names as a user defined package names or not?
26. What are the applicable modifiers for constructors?
27. Is it possible to override private methods or not yes=how no=why?
28. When we will get compilation error like “attempting to assign weaker access privileges” how to
rectify?
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?
12. What is the root class of Exception handling?
13. Can you please write some of checked and un-checked exceptions in java?
14. What are the keywords present in Exception handling?
15. What is the purpose of try block?
16. In java is it possible to write try with out catch or not?
17. What is the purpose catch block?
18. What is the difference between try-catch?
19. Is it possible to write normal code in between try-catch blocks?
20. What are the methods used to print exception messages?
21. What is the purpose of printStackTrace( ) method?
22. What is the difference between printStackTrace( ) & getMessage()?
23. What is the purpose of finally block?
24. If the exception raised in catch block what happened?
399 | P a g e
Durgasoft Mr. Ratan
400 | P a g e
Durgasoft Mr. Ratan
63. What is the difference user defined checked and unchecked Exceptions?
64. Is it possible to handle different exceptions by using single catch block yes-->how nowhy?
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?
l. Is it possible to create object of interfaces?
m. What do you mean by abstract class?
n. When we will get compilation error like “attempting to assign weaker access privileges”?
o. What is the difference between abstract class and interface?
p. What do you mean by helper class?
q. Which of the fallowing declarations are valid & invalid?
a. class A implements it1
b. class A implements it1,it2,it3
c. interface it1 extends it2
d. interface it1 extends it2,it3
e. interface it1 extends A
f. interface it1 implements A
r. what is the difference between classes and interfaces?
s. The interface reference variable is able to hold implementation class objects or not?
a. Interface-name reference-variable = new implementation class object(); valid or invalid
t. What is the real-time usage of interfaces?
u. what is the limitation of interfaces how to overcome that limitation?
v. What do you mean by adaptor class?
w. What is the difference between adaptor class interfaces?
x. Is it possible to create user defined adaptor classes?
y. Tell me some of the adaptor classes?
z. What do you mean by marker interface and it is also known as?
aa. Define marker interfaces?
bb. What are the advantages of marker interfaces?
cc. Is it possible to create user defined marker interfaces or not?
dd. Is it possible to declare nested interfaces or not?
401 | 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
10) Non-synchronized methods
11) Overriding method
12) Overridden method
13) Factory method
14) Template method
15) Default method
16) Public method
17) Private method
18) Protected method
19) Final method
20) Strictfp method
21) Native method
Different types of classes in java (must know information about all classes)
1) Normal class /concrete class /component class
2) Abstract class
3) Tightly encapsulated class
4) Public class
5) Default class
6) Adaptor class
7) Final class
8) Strictfp class
9) JavaBean class /DTO(Data Transfer Object) /VO (value Object)/BO(Business Object)
402 | P a g e
Durgasoft Mr. Ratan
403 | P a g e
Durgasoft Mr. Ratan
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 ?
6. How many constructors are there to create Integer Wrapper class?
7. How many constructors are there to create Float Wrapper class?
8. What do you mean by factory method?
9. What is the purpose of valueOf() method is it factory method or not?
10. How to convert wrapper objects into corresponding primitive values?
11. What is the implementation of toString() in all wrapper classes?
12. How to convert String into corresponding primitive?
13. What do you mean by Autoboxing and Autounboxng & introduced in which version?
14. Purpose of parseXXX() & xxxValue() method?
15. Which Wrapper classes are direct child class of Object class?
16. which Wrapper classes are direct child class of Number class?
17. How to convert primitive to String?
18. When we will get compilation error like “int cannot be dereferenced”?
19. Wrapper classes are immutable classes or mutable classes?
20. Perform fallowing conversions int--->String String--->int Integer--->int int--->Integer ?
404 | P a g e
Durgasoft Mr. Ratan
Collections
1) What is collection? What is Collection framework?
2) What is the main objective of collections?
3) What are the advantages of collections over arrays?
4) Collection frame work classes are present in which package?
5) By using collection framework classes is it possible to store primitive data?
6) What is the root interface of collection framework?
7) List out implementation classes of List interface?
8) List out implementation classes of set interface?
9) List out implementation classes of map interface?
10) What is the parent interface of Collection interface?
11) What is the difference between heterogeneous and homogeneous data?
12) What do you mean by legacy class can you please tell me some of the legacy classes present in
collection framework?
13) What are the characteristics of collection classes?
14) What is the purpose of generic version of collection classes?
15) How to provide type safety to the collection?
16) What is the difference between general version of ArrayList and generic version of ArrayList?
17) What is purpose of generic version of ArrayList & arrays?
18) How to convert Collection data to arrays & Arrays data to collection?
19) How to get Array by using ArrayList?
20) What is the difference betweenArrayList and LinkedList?
21) How to decide when to use ArrayList and when to use LinkedList?
22) What is the difference between ArrayList & vector?
23) Which collection classes are synchronized or Threadsafe?
24) Which collection classes are non-synchronized or not Threadsafe?
25) How can ArrayList be synchronized without using vector?
26) Arrays are already used to hold homogeneous data but what is the purpose of generic version of
Collection classes because generic version also used to store homogeneous data?
27) What is the purpose of RandomAccess interface and it is marker interface or not?
28) What do you mean by cursor and how many cursors present in java?
29) How many ways are there to retrieve objects from collections classes what are those?
30) What is the purpose of Enumeration cursor and how to get that cursor object?
31) By using how many cursors we are able to retrieve the objects both forward backward direction
and what are the cursors?
32) What is the purpose of Iterator and how to get Iterator Object?
33) What is the purpose of ListIterator and how to get that object?
34) What is the difference between Enumeration vs Iterator Vs ListIterator?
35) We are able to retrieve objects from collection classes by using cursors and for-each loop what is
the difference?
36) By using which cursor it is possible to read the data from forward and backward directions?
37) All collection classes are commonly implemented some interfaces what are those interfaces?
38) What is the difference between HashSet & linkedHashSet?
39) all most all collection classes are allowed heterogeneous data but some collection classes are not
allowed can you please list out the classes?
40) What is the purpose of TreeSet class?
41) What is the difference between Set & List interface?
42) What is the purpose of Map interface?
405 | P a g e
Durgasoft Mr. Ratan
Garbage Collector
406 | P a g e
Durgasoft Mr. Ratan
Enumeration
1) What is the purpose enum in java?
2) How to declare enum& compiler will generate .class files or not?
3) enum constants are by default modifiers are?
4) What is the difference enum & Enum?
5) What is the difference between java enum & other language enums.
6) Is it possible to declare main method & constructor inside the enum or not?
7) Is it possible to provide parameterized constructor inside the enum?
8) Inside the enum group of constants ends with semicolon is optional or mandatory?
9) What is the difference between java enum and java class?
10) What is the purpose of values() & ordinal() methods?
11) Is it possible to crate object for enum or not?
12) For enum inheritance concept is applicable or not?
13) When enum constants are loaded?
14) Enums are able to implement interfaces or not?
15) One enum is able extends other enum or not?
16) What is the difference between enum& Enumeration & Enum?
17) Can you use enum constants switch case in java?
18) What is the modifier applicable for enum constructor?
19) Is it possible to declare the enum inside the class or not & inside the method or not&outside of
the class or not?
20) When we access enum constants outside of the package directly without using enum name then
normal import required or static import required?
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?
407 | P a g e
Durgasoft Mr. Ratan
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?
4. What is the difference between normal stream & buffered Streams?
5. What is the difference between FileInputStream & BufferedReader?
6. What is the difference between FileOutputStream & printwriter?
7. Println() method present in which class?
8. Out is which type of variable(instance /static ) present in which class?
9. To create byte oriented channel we required two class what are those classes?
10. To create character oriented channel we required two class what are those classes?
11. What is the difference between byte oriented channel and character oriented channel?
12. What is the difference between read() & readLine() method?
13. What is the difference between normal Streams & bufferd streams?
14. Wat is the purpose of write() & println() ?
15. Example classes normal Streams & bufferd streams?
16. What do you mean by serialization?
17. What is the purpose of Serializable interface& it is marker interface or not ?
18. How to prevent serialization concept?
19. What do you mean deserialization?
20. To perform deserialization we required two classes what are those classes?
21. To perform serialization we required two classes what are those classes?
22. What is the purpose of transient modifier?
23. What are advantage of serialization?
24. Serializable interface present in which package?
25. When we will get IOException how many ways are there to handle the exceptions?
26.
27. IOException is checked Exception or unchecked Exception?
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?
408 | 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?
409 | P a g e
Durgasoft Mr. Ratan
Class.forName():-
forName is a static method present in java.lang.Class class having capability to load particular
class or interface e byte code into memory at runtime.
public static java.lang.Class forName(String name) throws java.lang.ClassNotFoundException;
ex : class.forName(“java.lang.System”); //it loades System class byte code into memory
forName() method throws ClassNotFoundException and it is a checked Exception must handle
that exception by using try-catch blocks or throws keyword.
package com.dss;
class Demo
{ static
{System.out.println("Ratan class");}
};
import com.dss.Demo;
class Test
{ public static void main(String[] args) throws Exception
{ Class c = Class.forName("com.dss.Demo");
System.out.println("loaded class name="+c.getName());
}
}
The above application loads com.dss.Demo class into application dynamically at runtime and return
java.lang.Class representing the lorded class com.dss.Demo.
In above application reference variable c is not a Object of com.dss.Demo class it is a Object of
java.lang.Class class.
410 | P a g e
Durgasoft Mr. Ratan
String str=s1.concat("ratan");
Ex 2:-
String s = new String("hello how r u");
String s1 = s.substring(1,3);
The factory method is called by using class name is called static factory method.
Thread t = Thread.currentThread();
String str = String.valueOf("ratan");
Integer i = Integer.valueOf(100);
3) Creation of Object by using newInstance() method of java.lang.Class
package com.dss;
public class Demo
{ public void disp()
{System.out.println("Ratan class");
}
};
import com.dss.Demo;
class Test
{ public static void main(String[] args) throws Exception
{ Class c = Class.forName("com.dss.Demo");
Object o = c.newInstance();
Demo d = (Demo)o;
d.disp();
}
}
411 | P a g e
Durgasoft Mr. Ratan
Note 1: - Every topic Real Time project implementation examples will be provided.
Note 4:- within one week we are able to write examples in classroom .
by Mr. Ratan.
1st class Demo- importance of java.
2nd class Demo-differences between c& cpp& java.
3rd class installation process
4th class first application
5th class first application & data-types
6th class variables
7th class variables & method introduction.
8th class methods examples.
9th class constructors
10th class instance blocks& static blocks
11th class inheritance
12th class inheritance-Aggregation keyword
13th class super keyword
14th class polymorphism-overloading
15th class polymorphism-overriding
16th class polymorphism-overriding rules
17th class packages
19th class abstraction-abstract classes
20th class abstraction-interfaces
21th class encapsulation
22th class main method
412 | P a g e
Durgasoft Mr. Ratan
Example 1:-
class Test
{ 2-instance variables
static void m1()
{ print 2-variables
}
static void m2()
{ print 2-vriables
}
public static void main(String[] args)
{ call m1() method;
call m2() method4;
}
};
Example 2:
class Test
{ 2-static variables
void m1()
{ print 2-variables
}
void m1()
413 | P a g e
Durgasoft Mr. Ratan
{ print 2-variables
}
public static void main(String[] args)
{ call the m1() method
call the m2() method
}
}
class Test
{ 2-instance variables
2-static variables
void m1()
{ print 4-variables
}
static void m2()
{ print 4-vriables
}
public static void main(String[] args)
{ call m1();
call m2();
}
};
Example 3:-
class Test
{ 2-instance variables
2-static variables
arguments return-type
1-instance method(X x,Emp e) Test
1-static method(any 2-args) float
1-instance method(Product p,int a) String
1-static method(any 1-args) char
414 | P a g e
Durgasoft Mr. Ratan
class Test
{ public static void main(String[] args)
{ Integer a=1000,b=1000;
System.out.println(a==b);
Integer n=50,m=50;
System.out.println(m==n);
415 | P a g e
Durgasoft Mr. Ratan
}
}
416 | P a g e