1core Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 322

Q.1 What is Java ?

1) Object Oriented Programming language.


1.1) Java is Object Oriented Programming Language.
2) Computing Platform(J2SE,J2EE and J2ME)
2.1) Java Provides 3 Different Platforms
1. J2SE ( Standard Edition ) for Simple Programs.
2. J2EE (Enterprise Edition) for Advance Programs.
3. J2ME(Micro Edition) for Mobile S/W s.
3) Technology(JDBC,SERVLET,JSP)
3.1) All Advance Java Concepts.
Java = Core + Advance + its Platforms.
Q.1)
1.1)why java is not pure object oriented language ?proof?
1.2)why java have 3 different platforms...why not this 3 platform combine together?
1.2=>ask to James Gosling
NET
1.1)why java is not pure object oriented language ?proof?
*) because in java we use primitive data type ..like int , byte , long .... that's why java is not pure object oriented language
in 100% oops language you cant use data types ... in java we use data types so that is why java is not 100% oop language
you can use wrapper class .. but in wrapper class as far i concern we cant use "character "
* Bhut hi saral shabdo me.. Object oriented ka matlab h... Ki aap object create kr ske,aur uss object se Aas pass ke data
ko.. Access kr ske Aur java me Datatypes me aisa possible nhi h, Example.. Hmne ek integer variable define kiya.. Aur
hum ise directly access kr skte h.. void main(String []args){ int number=123; System.out.println(number); } jese ki above
example me hmne number ko print krne ke liye integer datatype ka object nhi bnaya... Pure object orientd me aisa krna
hoga
*actually object oriented means everything is in object form and object contains address rather then value but still there is
primitive type in java like int float double etc they directly holds value that's the java is not pure object oriented primarily
what i saw and find many people having many opinion but just first try to understand what is object oriented then may be
u find some good logical view .....
Q2. What are the thing ,which we should know to become a J2EE Professional ?
1) (Basic) Java Programming Language (core java)
2) Technology(servlet,jsp,jdbc)(advance java)
3) Frameworks(Spring,Hibernate,Struts)
4) SQL/PLSQL(database Language)
Q.3) Where Java Programming Language used Mostly ?
Java Programming Language is used mostly in Enterprise Application development. and also used in Andriod
Application and Internet Gaming.
Note :- Enterprise Application means Business Organization.
Q.4) What is Enterprise Application ?
Enterprise means Business Organization like banking,insurance, health , financial ,share banking company.
A Computer Application that is used to computeries the activities of an enterprise(Business Organization) is nothing but
an Enterprise Application.
Note :- Application is nothing but (big in size) a Program.
* computeries the activities of an enterprise(Business Organization)*/
Que: what are important components of JVM?
Ans : The important components are:
a) Class loader subsystem - provides the loading mechanism for types(class, interfaces) in java.
b) runtime data areas: constitute of
1)Method Area
2)heap
3) java stacks
4)program counter (registers)
5)Native method stacks
these areas provides memory to store byte-codes , object created, method parameters, return values ,local variables and
intermediate result of computations
c) execution engine: It helps to execute the instruction contained in methods of loaded classes.
Que : what is role of different component of runtime data areas of jvm?
Ans:
Method area:it holds the information about loaded types. For each type it loads, a Java virtual machine must store the
following kinds of information in the method area: types means classes and interfaces.

1) The fully qualified name of the type


2) The fully qualified name of the type's direct superclass (unless the type is an interface or class java.lang.Object, neither
of which have a superclass)
3) Whether or not the type is a class or an interface
4) The type's modifiers ( some subset of` public, abstract, final)An ordered list of the fully qualified names of any direct
superinterfaces
note: All threads share the same method area, so access to the method area's data structures designed to be thread-safe. If
two threads are attempting to find a class named Abc, for example, and Abc has not yet been loaded, only one thread
should be allowed to load it while the other one waits.
Heap : Whenever a class instance or array is created in a running Java application, the memory for the new object is
allocated from a single heap. As there is only one heap inside a Java virtual machine instance, all threads share it.
Java Stacks :
1) When a new thread is launched, the Java virtual machine creates a new Java stack for the thread.
2)A Java stack stores a thread's state in discrete frames. The Java virtual machine only performs two operations directly
on Java Stacks: it pushes and pops frames.
3) As the method executes, it is used to store parameters, local variables, intermediate computations, and other data.
4) Program counter :
1) Each thread of a running program has its own program counter, which is created when the thread is started.
2) The pc register is one word in size, so it can hold both a native pointer and a returnAddress.
3)As a thread executes a Java method, the pc register contains the address of the current instruction being executed by the
thread
5) Native method stack:
1) A running Java application may use other data areas created by or for native methods.
2) When a thread invokes a native method, however, that thread leaves the Java stack behind. Instead of pushing a new
frame onto the thread's Java stack, the Java virtual machine will simply dynamically link to and directly invoke the native
method.
Q.5) What is Architecture of a Java Enterprise Application ?

Q.6) What are the Similarities between C and Java Programming Language ?
1.Both Languages are High Level Programming Language.
2.Both Languages Syntactically Similar in the Folloing area
a)Variable Declaration.
b)Operators.
c)Expressions.

d)Decision Making Control Statements.


e)Iteration Control Statements.
7.1)If applet is threre for web , why java invent JSP and Servlet ?
7.2)What is Client Side and Server Side Programming ?
7.3)why Currently in web application java Programming Language almost not used at
Client Side , instead it is used at server side ?
Give Answer like
answer for 7.1) write answer...please
7.1)
*applet is special type of program they run inside the web browser jsp and servlet is technology they create web
application they also known resquest and response when program is run request server and server perfrom the output they
using response
*)ans for...7.1....there is limitations of data storage with applet...and not comfortable
7.2) the programming which implements at clint side by clint is clnt sidr progr..and the progr. at server side by server is
server side prgrm.there is need to store lots of data at server side which is well provided by java..
7.2). Client side Programming means the representation part on web... how user see the page he made request for. Eg.
Html , jsp Server side programming means logical part to handle data... we cannot let user to see our database or cannot
let him have a direct access. Servlet are used for securety....and our codes and logic...3 hrs
7.3) client side we use html page or jsp page, these both includes how to represent text and data for client.
At server side we have our database and we want to handle that database for incoming requests so we use servlet...
Servlet contains logical part and codes...
Q.8) What is the Evolution(History) of Java Programming Language ?
In 1990 Sun Microsystem started a project by name Green Project to Have a New Programming Language whose
application to Run on any Platform.
Green Project was meant for smart consumer electronic devices. but green project was failed.
" James Gosling " took the role of developing a new Programming Language . it takes 18 months.
He developed a Language Called as Oak. later it renamed with " Java ".
1) JDK 1.0 Released on Jan 23rd 1996
2) JDK 1.1 Released on Feb 19 1997
3) J2SE 1.2 Released on Dec 8 1998
4) J2SE 1.3 Released on May 8 2000
5) J2SE 1.4 Released on Feb 6 2002
6) J2SE 5 Released on Sept 30 2004
7) Java Platform Second Edition 6 Dec 11 2006
8) Java Platform Second Edition 7 July 28 2011
9) Java Platform Second Edition 8 March 18 2014
Q.9) Explain About Java Platform ?
Platform : - Execution Environment or run time infrastructure for the Applications(Computer Programs) is nothing but
Platform for these application. Execution Environment or run time infrastructure for Java Application is nothing but Java
Platform. Standard Edition and Enterprise Edition are Two Major Platforms of Java Given By the Sum Micro system.
and also Micro Edition is available. Note :-Operating System Act as a Platform for C and C++ . therefore they are
platform dependent.
Q.10) What is features of Java Programming Language ?
When Java was 1st created , Sun Micro system described it with a series of BUZZ words to describe the features of java.
Java is a
(1) Simple
(2) Object Oriented
(3) Robust
(4) Secure
(5) portable
(6) High Performance
(7) Architectural Neutral
(8) Interpreted
(9) Multithreaded
(10) Distributed
(11) Dynamic
Programming Language.
(5)Portable :- If the source code of application(program) can be compile & run in any environment(OS+Processor)
without modification or Very less Modification, The Language using which that Application(program) is developed is
said to be Portable.

Java Application(program) can be compiled and run on any environment without any modification to its source code.
Memory allocation for the variable of any data type is the same in any Environment Unlike C Programming
Language.Therefore , Java is Portable
Note :- Assembly Language is not Portable. it is target to particular Processor.
"C language is portable to the maximum extent".
(7)Architecture Neutral :- Sun Micro system Slogan "Write Onces Run Anywhere" is in accordance with
"Architecture Neutrality" feature of Java.
Java Application can be compiled in one Operating System Environment and Resultant File can be Executed on other
Operating System Environment.
This feature is Know as Platform Independent. (unlike C language, source code of C compile on one
environment(OS+Processor) it must run only on that environment, it can not run on other environment )
3 Things Contributes to the Platform Independency
(a)Java Compiler
(b)Class File Format
(c)Platform Dependent(Operating System Dependent) JVM.
(a)Java Compiler (javac) Compiles a Java Application to a Class File In any Operating System Environment , Java
Compiler Produces the Same Class File. "Java Compiler 1st Written in C then it written in Java itself(Oracle)"
(b)Byte code is nothing but Intermediatory instructions that are understand to any kind of JVM(windows JVM,Linux
JVM)
(c)JVM(System Software) 1st written in C then Written in C++.
Which Execute Java Application by interpreting the byte code of .class files into machine instruction that are
understandable to the Operating System to be given to the Processor.
JVM are Operating System Dependent.
(1)Simple :- Being a High Level Language Java is easy to use in application development . Complex features of C/C++
are eliminated or simplified in Java and there by Making it simple.
(3)Robust :- The ability to withstand failure is nothing but robustness. Exception Handling Mechanism and Memory
Management Provided by Java Contributes to it Robustness.
java handles runtime problems very clearly,sweetly => robustness.
(all Compile time, Run time Problem solved very clearly and Best Memory Management is feature of Robustness )
(4)Secure :- Even though Java is Used mostly in Internet Environment Java Platform does not allow Malicious(Virus) in
Application which reading the System information. if Malicious Application try to read System information , Java
Terminates the Application. Java Mostly Used in Financial Application Development without any security threat.
(6)High Performance :-Java provides better performance than any other interpreted language.
but it is not faster than C & C++ (Execution wise) Using JIT(Just In Time Compiler) the Performance gap BetWeen C/C+
+ and Java Application getting reduced.
(8)Interpreted :- Java Application are both Compiled and Interpreted.
Interpreter Contributes to security of Java Application (execute code line by line , so can verify security
after each line execution).
(9)Multithreaded :- Java Contribution towards Multithreaded is that it has brought multitasking to the application level
which is otherwise , a System Level Programming Concept.
(10)Distributed :- Java is excellent in distributed application development. An Application is said to be Distributed if the
Application Component are geographically dispersed (into Multiple Computers of the network ) and still communicating
one Another. Distributed Application Facilities load balancing and High Availability. Java has built in library supports for
distributed computing and two technologies provided for the same. They are RMI and EJB
(11)Dynamic :- Memory Allocation and Library Inclusion is Dynamic in Java Runtime(Program Execution time)
Decision facilitate flexibility.
Q.10)
Q.11) What are the System Requirement to develop a Java Application(Program)(J2EE) ?
We need to Install JDK (Java Development Kit) Software and set Path as well as ClassPath.
note :- JRE(Java RunTime Environment) is nothing but JVM only.
if only JRE is installed , we can execute J2SE Application but we can`t develop Applications
Q.12) Develop a 1st Java program that display simple massage.
Step 1) Create a folder with any name. this folder act as default package for the class file of a application.
Step 2) Launch any text editor (Preferable notepad or vim/vi not even gedit) and save the application into above created
folder with any name (but give some meaningful name) but with ".java" extension.
Step 3) Compile the Application(program). launch the command prompt , go to folder where you save .java file ,
and specify the following command javac FileName.java java ClassNameInWhichClassYouWroteMain.
Note :- Javac is a System Command which received by the Operating System.
Operating System verify the Location of java compiler software installed in that computer in path environment variable
then invokes the Java Compiler and give a .java file as a input file Javac(compiler) process on .java file which is called

by <Compilation Unit> <Compilation Unit >/.java file does not have any syntactical error then Java compiler compiles
into one or more .class file.
Q.13) Make New Java Application Which Display Some Massage !
Note :- "when you compile java code using Javac filename.java that time Oprating System Invokes The JVM
JVM Load finename.java from Secondary Memory(HardDisk) to Primary Memory(RAM)"(is this ryt ?)
JVM Calls Main() Fuction From filename.java to Start Execution Main() calls other Library fuctions like println();
*Main() is UserDefine Function because user define it and Gives Defination. only main name is given by Labrary/JVM*/
class PrintMessage
{
public static void main(String args[])
{
System.out.println("You Can Print Any Massage Using Any Key From KeyBoard To Console ");
}
}
// to compile and run refer q12
//save it with FirstProgram.java
//compile with command "javac FirstProgram.java"
//run with command "java PrintMassage"
// you get result on console.
/* Expalination of Above Code
class PrintMassage :- "class" is a keyword in java. "PrintMassage" is idntifier.
Note:- Name of a Programming element is called as Identifier.
for eg. function name,variable name,class name(user define) In Java class name start with Capital letert if the identifier
cancatination of more than one word , 1st character of every next word must be in upper case.
Entry point into a java application is main() method , here Class is Define to Encapsulate main mathod().
Q.13)
when you compile java code using Javac filename.java that time Oprating System Invokes The JVM
JVM Load finename.java from Secondary Memory(HardDisk) to Primary Memory(RAM)? is this ryt ?
after compile what OS do............?
it invokes javac compiler or jvm ?
JVM encapsulates javac (java compiler) ?
JVM loads .java file or .class file ?
OS or JVM invokes .Java file ?
What actually happens when we give javac filename.java command.......?
Q.13.1.2.3..4.5.6.7.8.9.0)please answer for this question......please when you compile java code using Javac
filename.java that time Oprating System Invokes The JVM JVM Load finename.java from Secondary
Memory(HardDisk) to Primary Memory(RAM)? is this ryt ?
after compile what OS do............? it invokes javac compiler or jvm ?
JVM encapsulates javac (java compiler) ? JVM loads .java file or .class file ? OS or JVM invokes .Java file ?
What actually happens when we give javac filename.java command.......? after that what happens when we give java
classname.
Q 14.) How To Set Path and ClassPath ?
Path :Path is Environment Variable used by the Operating System to locate the software.
Giving value to this Environment Variable is nothing but Setting a Path.
This Environment Variable can have Multiple Values (at same time) with semicolon as a separator.
when "javac" command is given at the command line if Operating System is unable to locate
it. we need be set the path by specifying the location.we set path at the command line as follows
set path = "Give Path Where JDK installed"
eg. set path = E:/java/jdk1.7.0/bin
(graphically :- mycomp.->properties->Advance Setting->Environment Variable->give location to path)
ClassPath :ClassPath is Environment variable used by java compiler(javac) & JVM to locate classfiles(both user define and library)
while compiling the application , if we get the compilation error saying "Package Not Found"
we need to set ClassPath .
Similarly , while execution time if "No Class Def Found Error" or "ClassNotFoundExecption" error come , set ClassPath
set classpath = .;D:/java/jdk1.7.0/jre/lib/rs.jar; "."(dot) means search class files in current directory.
D:/java/jdk1.7.0/jre/lib/rs.jar; means search class files as well as packages in this folder.

Q.15) Talk On Main Method .


Main() Method Is Executed Fisrt From The Class.
In Core Java Every Program Must Have Main() Method.
Q.16 ) Why Main Method Is Declared Public ?
To Provide Access Permission To JVM To Call
The Main Method; Main Is Declared As Public.
(PUBLIC gives permission to call "main" that method or acess that method or variable TO ALL , who are in java
environment)
(public -> java environment accessibility)
Q.17 ) Why Main Method Is Declared Static ?
To facilitated The JVM To Call The Main Method Without The Need Of Creating The Object Of Class,
Main Declared Static. (to call any method we must have to use object to call that method but if You use static keyword it
means that method or variable is class level means it can call by classname no need to call by object name)
for eg. class classname
{ static veriables;
static methodCall(){}
}
classname.methodCall();
classname.variables;
after java ClassName command :----> JVM call ClassName.main(); emplicitly.
Q.18) What is the signature of method in Java ?
Method Name Plus its Parameter list is nothing but the signature of a java method. Modifiers and return type (Exception
Specification) are not all the part of the method signature.
18.1)what is signature of any method ?
Q.19) What Should Be Signature of main method in java ?
"Main" Should be the name of method "String Array" Should be the parameter of the main method.(Not String arrays or
only one String array)
Syntax:- main(String [])
main(String a[],String b[]) => INVALID,its work as instance method
main() => INVALID,its work as instance method
main(int a) => INVALID,its work as instance method
main(String a) => INVALID,its work as instance method
Q.20) Explain about the return type of main method ?
main should not return any value to JVM.
JVM is designed to provide execution environment for
The Java Application but not for accepting any values from the application therefore main return type should be "void".
Q.21) can main method be Overloaded in a Java Application(Program) ?
Yes .
we can have multiple main methods within the same class with different signature but JVM can recognize only main with
String Array as parameter "main(String [])". other overloaded methods like simple instance(object) methods.
public static void main(String args[])//main method which call by jvm as a entry point of class
public static void main(String args[],int a)//instance method
public static void main(String args[][])//instance method
public static void main(int a)//instance method
Q.22) Can we have multiple main methods in a Single Java Application that can be recognized by the JVM ?
Yes .
in a java application we can have any number of main methods as per JVM identification.
program execution time , at command line , which class is specified that main is called by JVM. other main are ignored.
Q.23) Explain the Following Method Call ?
System.out.println(""+);
"out" is a Static Reference Variable in System Class of Type PrintStream.
/*class PrintStream
{
..................
.....println(....)
{
}
.................
}*/

/*
class System
{
static PrintStream out=new PrintStream();//reference variable can be static
............
}
*/
23.1)System and PrintStream class is public ?i think yes becoz they can use in another package.....
23.1)System and PrintStream class is public ?i think yes becoz they can use in another package.....
Q.24) What is the main purpose of any computer Application ?
Data Processing.
Q.25) What are Major Element of an Application ?
Application = Data + Code (which Acts Upon The That Data)
"Data+Functions"
11.1)What is JRE,it does provide "Development of Java Application Facilaty" to user ?
Q.26) What are the Programming style/methodologies/principles/paradigm used in application development ?
There are two programming styles used in the s/w industry to develop application.
1) Procedural (Structure) Oriented Methodologies.
2) Object Oriented Methodologies.
A Programming Methodology is means "way of organizing the application data & code."
Q.27) Procedure (Structural) Oriented Methodology .
*it is a programming principle, in which an application is organized on the basis of "How To Process Data"
Procedure (Structural) Oriented Methodology meants that the application was divided into a number of procedures.
(Counting Function)
*Procedural Oriented Programming (POP) involves the following things :a) Choosing appropriate way to store data.(choosing dataStructure)
b) Designing the algorithm.
c) Translating algorithm into code(Function).
*Characteristics of procedural oriented programming :1)Algorithm based.
2)It Focuses on process rather than data.
3)It taken a problem as a sequence of things to be alone such as reading , calculating & printing hence , a number of
procedure (functions) are written to solve a problem.
4)A Program is dividend into a number of function/procedure has a clearly defined purpose.
5)Most of the function share global data.
6)Data moves openly around the System(application) from function to function.
7)treats data & and Functions as a separate things.
*Limitations of POP :POP Emphasis on doing things. data is given a second class status even through data is very reason for the existence of to
the program. It concentrates only one, "How to process data". It don`t think about who (Which code) is processing whom
(which data).
**Major limitations in POP, is Lack of Proper Organization of data & code that acts upon data. It leads to the following
problems
1)data is not secure(from whom all other applicatio`s methods(finctions))
2)complexity can`t be handled properly.
3)can`t model the real world entities properly.
Q.28) Object Oriented Programming(OOP) Overcome this limitation of POP ?
*Object Oriented is a programming Style using which application are organized :around it`s data & a set of well defined interface(Interacter) to that data.
OOP meant that the application was divided into a number of objects.
OOP is a programming principle , using which an application is organized using
encapsulation, inheritance , polymorphism.(who is processing whom)
*Features of OOP :1.Encapsulation
2.Inheritance
3.Polymorphism

Q.29) Encapsulation :*Encapsulation :The Mechanism/Process of combining/wrapping the data & Eligible code that acts upon the data into a single unit of
organization is nothing but encapsulation.
*Result of Encapsulation :Data & Code that acts upon the data is secure from the other ineligible code of the same Application.
Encapsulation leads to abstraction that reduces the complexity
abstraction means hiding with encapsulation, not only data but also code is secure from outside interface.
*Encapsulation Implementation :Combining variable & function in single unit & Organize the programmatically.
Using Class and Object [class & object is not oo feature]
Q.30) What is a "Class" in an object oriented application ?
A class is a blueprint(template) of (a proposed ) an object.
eg. House plan -> class
created house--->object
People -> data
A class describes the structure & behaviour of an object.
A class containing`s variables and methods [data & code is combining unit is encapsulation]
class=(data+code)=>concept name is encapsulation
eg :- class is the basis of encapsulation
class is the programmtical means of achieving encapsulation in an object oriented system.
Account Class Name
accno Attributes/instance variable/properties
name Attributes/instance variable/properties
balance Attributes/instance variable/properties
getBalance() Instance Method/behaviours/operations
displayAccountDetails() Instance Method/behaviours/operations
withdraw() Instance Method/behaviours/operations
deposite() Instance Method/behaviours/operations
Q.31) What is an Object ?
An Instance of a class is nothing but an Object.
(actual memory of class structure, one class can have many objects)
A Fundamental unit of data storage in an object oriented System
To store some data in a secured fashion is nothing but an object.
*An object contains data & associative code that acts upon the data.
*Therefore object implements Encapsulation.
instance variable/properties of an object is nothing but it`s structure(bone Structure), instance method are nothing but
object behaviour.
An Object has three things
1. State
2. Behaviour
3. Identity
1. State :Data stored in the properties(instance Variable) of an object is nothing but its State.
2. Behaviour :Instance Methods of an object is nothing but its behaviour.
3. Identity :The Name of the object with which, it is uniquely identified is nothing but the identity of an Object. (reference variable
used identify object)
/*
Q.32) What is O/P(output) of the following Application ?
output1.java
*/
class output1
{
public static void main(String args[])
{
int a;
System.out.println(a);

}
}
/*
==> output
"output/output1.java:6: variable a might not have been initialized
System.out.println(a);
^
1 error"
the above program causes compilation ERROR.
In main method , variable "a" is of type "int" declared is *Variable "a" is used without Initialization.
Variable is nothing but a named memory location.
*Any Variable declared in a method is called as local variable.
**Rule in java is , local Variable should not be used without initialization.
Note :- If a variable initialized at the place of its declaration , it is called as "Variable Definition"
for eg. int a = 10;(definition)
int a;(declared only)
a=10;(initialization)
System.out.println(""+a);(used)
*/
/*
Q.33) Develop a Java Application that prompt`s the user to enter two numbers & display the Sum.
Addition.java
*/
import java.util.scanner;
class Addition
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the First Number :- ");
int n1 = s.nextInt();
System.out.println("Enter the Second Number :- ");
int n2 = s.nextInt();
int sum = n1+n2;
System.out.println("The Sum of Two Numbers is : "+sum);
}//main
}//Addition class
/* OutPut
riddhi@debian7:~/CoreJava$ java Addition
Enter the First Number :23
Enter the Second Number :43
The Sum of Two Numbers is : 66
riddhi@debian7:~/CoreJava$
* Program Explanation ?*
In java library class files are grouped into packages.
By default to every java application "java.lang.*" package is implicitly available.
We need not explicitly import it.
In the above program, String & System are library classes which belong to "lang" package.
Therefore, without the need of importing them into the application, we can use them.
Other than lang package, without importing we can`t use them in the java Application.
Scanner class is a library class that belong to "java.util" package, therefore we must import
it in order to use it.
In the above program Scanner class object is created with the following Syntax.
" Scanner ObjectOfScanner = new Scanner() "
Scanner class object is used to read data from keyboard into the java application.
In java Variables can be declared at the place of their usage.
*/

Q.34) How To Accept Input From KeyBoard ?


A stream represent flow of data from one place to another place like a water pipe carries water. A stream carries a data
there are 2 type of stream
1)Input Stream :- They read or accept a data.
2)Output Stream :- They send or write a data to another place.
All Stream are represented as a classes in "java.io" Packages "KeyBoard" => "InputStreamReader" => "BufferedReader"
Accepting Input From KeyBoard :1)Connect InputStreamReader to the KeyBoard InputStreamReader obj = new InputStreamReader(System.in);
2)connect InputStreamReader to bufferedReader :- BufferedReader br = new BufferedReader(obj);
3)Read data at br using "read()" or "readLine" methods.
Example:- Accept a single character from a keyboard
*/
/*
1. InputStreamReader obj = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(obj);
char ch = (char) br.read();(for character)
String ch = br.readLine();(for string)
2. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char ch = (char) br.read();(for character)
String ch = br.readLine();(for string)
3.
Scanner s = new Scanner(System.in);
System.out.println("Enter the First Number :- ");
int n1 = s.nextInt();
float n1=s.nextFloat();
.............------------------------------------------------------------------(import java.util.*; package)
*/
import java.io.*;
class AcceptSingleCharacter
{
public static void main(String args[])throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nEnter a Character : ");
//try{
char ch = (char) br.read();
System.out.println("You Entered "+ch+"\n\n");
//}
//catch(Exception e){}
}//main method
}//class AcceptSingleCharacter
// OUTPUT
/*
riddhi@debian7:~/CoreJava$ javac AcceptSingleCharacter.java
riddhi@debian7:~/CoreJava$ java AcceptSingleCharacter
Enter a Character :
v
You Entered v
riddhi@debian7:~/CoreJava$
*/
/*
"char ch = (char) br.read();"
Converting one data type into another data type is called as "Typecasting". or Simple Casting
For this purpose we should write the data typing the simple braces"()" this is called cast operator
Exception is a rin time Error.
read() or readLine() methods rise IOException.
Read String From KeyBoard :String str = br.readLine();
Accept a integer Number :String str = br.readLine();

int n = Integer.parseInt(str);
int n = Integer.parseInt(br.readLine());
Accept a Float Number :String str = br.readLine();
float n = Float.parseFloat(str);
float n = Float.parseFloat(br.readLine());
Accept a Double Number :String str = br.readLine();
double n = Double.parseDouble(str);
double n = Double.parseDouble(br.readLine());
Accepting other Values :short n = Short.parseShort(br.readLine());
boolean n = Boolean.parseBoolean(br.readLine());
long n = Long.parseLong(br.readLine());
Q.35)Accept Employee idno,Gender(single char"M,F"),name and display them.
EmployeeInfoAcceptAndDispay.java
import java.io.*;
class EmployeeInfoAcceptAndDispay
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nEnter The Employee Number/id : ");
int idno = Integer.parseInt(br.readLine());
System.out.println("\nEnter The Employee Name : ");
String name = br.readLine();
System.out.println("\nEnter The Employee Gender : ");
char Gender = (char)br.read();
System.out.println("\nThe Employee id/number is : "+idno);
System.out.println("\nThe Employee name is : "+name);
System.out.println("\nThe Employee Gender is : "+Gender);
}//main method
}//class EmployeeInfoAcceptAndDispay
/* OUTPUT
riddhi@debian7:~$ cd CoreJava/
riddhi@debian7:~/CoreJava$ javac EmployeeInfoAcceptAndDispay.java
riddhi@debian7:~/CoreJava$ java EmployeeInfoAcceptAndDispay
Enter The Employee Number/id :
12
Enter The Employee Name :
RN
Enter The Employee Gender :
M
The Employee id/number is : 12
The Employee name is : RN
The Employee Gender is : M
riddhi@debian7:~/CoreJava$
In above o/p, read() method is leaving '\n' in the BufferedReader object which is read by readLine() method;
Solution 1:Use All readLine() & Change to char c = br.readLine().charAt(0);
Solution 2:We should remove \n from BufferedReder using a skip method
char c = (char) br.read();
br.skip(2);
Q.36) Does Java Support Operator Overloading ?
=> Operator Overloading facility is not given to application developers, so java doesn`t support operator overloading.
[Operator Overloading is Not a feature of Object Oriented, polymorphism is feature of oop]
[Operating Overloading is one way to implements Polymorphism]

However, "+" is the only operator overloaded in java.


1.)It acts as Arithmetic Addition Operator if both the Operants are numberable.
eg. sum=n1+n2(int n1=0,n2=0,sum;)
2.)It acts as a String Concatenations Operator if at least One Operant is a String
eg.System.out.println("Sum Of Given Two numbers is : "+sum);
Q.37) What is Differece BetWeen Instance Variable and Local Variable ?chech Q. 51 also....
INSTANCE Variable
LOCAL VARIABLE
1.form the structure of the 1.Do not contribute to the size Object of the Object
2.Declare in a class but
2.Declared inside the a method outside the method
3.Memory allocated in
3.Memory Allocated in Stack Heap Area area
4.Access Modifiers can
4.Access Modifiers can`t be Applied be Applied
5.life=Object life time
5.life=For the duration of the method execution.
6.class scope(available) 6.only method scope in the method of the (not available in class other execution)
7.JVM gives default
7.JVM doesn`t give values default values.(it must define before used)
8 Local variable have higher precedence than instance variable.......
9 only final modifier(final keyword) can be used with local variable to make that variable constant.....
/*
Q.51) What are Difference between instance variable and class variable ?check Q.37 also...
instance variable
class variable
1.non-static data members 1.static data members of a class of class
2.per object variable i.e . 2.per class (not per objeact) i.e. for each instance one for the whole class only one copy
seperate copy is created is created. irrespective of the object crated.
3.property of an object meant 3.not the property of the object. So for representing the State should not be ment for
representing of the object. the state of an object.
4.owned by an object
4.not owned by any object only shared by every object.
5.memory allocated in heap 5.memory not allocated in heap.
6.contributes to the size
6.does not contrubute size of an object of an object
7.memory is allocated only 7.memory is allocated as soon as the when object is created class is loaded & before any
object of that class is created.
8.should be used to represent 8.should be used to represent class individual object info. levelinformation.
Q.38) Develop a java application to represent one employee information
Give data to Employee & display the same ?
EmployeeInfoGiveAndDisplay.java
class EmployeeInfoGiveAndDisplay
{
int empno;
String name;
float salary;
void giveDataToEmployee()
{
empno = 1001;
name = "Ram";
Salary = 5000;
}//giveDataToEmployee Method(this instance method give some state to the object)
void displayEmployeeDetails()
{
System.out.println("Employee Number : "+empno);
System.out.println("Employee Name : "+name);
System.out.println("Employee Salary : "+Salary);
}//displayEmployeeDetails(this Instance Method Displays State of the Object)
}//class EmployeeInfoGiveAndDisplay
class CallEmployeeInfoGiveAndDisplay
{
public static void main(String args[])
{
EmployeeInfoGiveAndDisplay e = new EmployeeInfoGiveAndDisplay()
e.giveDataToEmployee();
e.displayEmployeeDetails();
}//main method
}//class CallEmployeeInfoGiveAndDisplay

OUTPUT
riddhi@debian7:~$ javac CoreJava/EmployeeInfoAcceptAndDispay.java
riddhi@debian7:~$ cd CoreJava/
riddhi@debian7:~/CoreJava$ java EmployeeInfoAcceptAndDispay
Enter The Employee Number/id :
12
Enter The Employee Name :
we
Enter The Employee Gender :
m
The Employee id/number is : 12
The Employee name is : we
The Employee Gender is : m
riddhi@debian7:~/CoreJava$
*//* what happens in background
When followong command is given to commandLine
" java CallEmployeeInfoGiveAndDisplay "
JVM loads CallEmployeeInfoGiveAndDisplay Application.class file from secondary memory (hard Disk) into Primary
Memory(RAM) , but EmployeeInfoGiveAndDisplay.class file not yet loaded JVM encounters bytecode of the following
source code once it invoked the main method.
" EmployeeInfoGiveAndDisplay e = new EmployeeInfoGiveAndDisplay()"
JVM Loads EmployeeInfoGiveAndDisplay.class into memory as it encoutered the syntax to create the object.
Actual Object creation Systax in that line of code is "new EmployeeInfoGiveAndDisplay()" once JVM receive the above
instructions, it does 4 things in the background
1.JVM Construct the object
2.JVM gives Default Values to the instance variables of the object.
3.JVM calls the constructor.
4.JVM Generates a unique number call "HashCode" by taking the starting byte address of the object as input
& returns the same to the application that is stored in the reference variable.
Note :- "e" is the reference variable or simply reference in the above example.
An Object is uniquley identified through hashcode only and that hashcode is stored in reference only
therefore , reference (reference variable ) acts as the name of the object.
" e.giveDataToEmployee(); "
main method is calling giveDataToEmployee() method on the EmployeeInfoGiveAndDisplay object using the
EmployeeInfoGiveAndDisplay Reference.
Limitation of above (program)application
=> Any number of object we created from the same class, all the object will have same structure and behaviour.
For practical reasons it is not available to have the ""SAME STATE"" to multiple objects.
giveDataToEmployee() method providing same state to every object of Employee class in the application.
This method is a not parameteries method in EmployeeInfoGiveAndDisplay class by making it parameteries,
the above limitation can overcome.
for eg.
void giveDataToEmployee(int eno,String nm,float sal)
{
empno=eno;
name=nm;
Salary=sal;
}//giveDataToEmployee() method
During method Defination, within the method header(i.e. within parenthesis declared variables or) parameters during
method call;
Supplied values call arguments;
Q.39) What are the instance variables ?
non static variable of a class are know as an instance variable.
For each instance(object) of class one copy of instance variables is created and hence the name.
Q.40) What are the Instance Methods ?
non static method of class is nothing but an instance method.
instance method can be created(call?) only once and hence the name.
instance method can be call any number of times in its life.

Q.41) What is OUTPUT of the Following Application ?


ProductApplication.java
class Product
{
int code;
float price;
void displayProductDetails()
{
System.out.println("Product Code : "+code);
System.out.println("Product price : "+price);
}//displayPProductDetails method
}//class Product
class ProductApplication
{
public static void main(String args[])
{
Product p;/*reference variable (refering Product class) of main method; and
whatever declare in method is local for that method, and in java local variable
can`t use before it define or initialized*/
p.displayProductDetails();
}//main method
}//class ProductApplication
/* OUTPUT
riddhi@debian7:~/CoreJava$ javac ProductApplication.java
ProductApplication.java:17: variable p might not have been initialized
p.displayProductDetails();
^
1 error
riddhi@debian7:~/CoreJava$
ERROR : "variable p might not have been initialized" We can Fix the Compilation with 2 ways
1)By initializing "p" to "NULL".
2)By Giving Object hashcode.
1)if the first option is used to fix the compilation error, during program execution, "NullPointerException" will be
Raised.
when a reference variable is holding "NULL Value" i.e. referencing no object,if an instance method is called using that
reference, NullPointerException raised.
2) 2nd Option gives you ERROR FREE output
Q.42) Develop a java application to represent 2 student information
(rollno,name,marks&grade) Ensure that their State is Different.(Method with Parameters)
StudentApplication.java
class Student
{
int rollno;
String name;
int marks;
char grade;
void giveDataToStudent(int rno,String nm,int m)
{
rollno=rno;
name=nm;
marks=m;
}//giveDataToStudent method
void displayStudentDetails()
{
System.out.println("RollNo : "+rollno);
System.out.println("Name : "+name);
System.out.println("Marks : "+marks);
System.out.println("Grade : "+grade);
}//displayStudentDetails method
void calculateGrade()

{
if(marks>=60)
grade='A';
else if(marks<=40)
grade='C';
else grade='B';
}//calculateGrade method
}//Student
class StudentApplication
{
public static void main(String args[])
{
Student s1=new Student();
s1.giveDataToStudent(101,"Ram",87);
s1.calculateGrade();
System.out.println("First Student Details : ");
s1.displayStudentDetails();
Student s2=new Student();
s2.giveDataToStudent(102,"Rajj",78);
s2.calculateGrade();
System.out.println("Second Student Details : ");
s2.displayStudentDetails();
}//main method
}//class StudentApplication
/* OUTPUT
riddhi@debian7:~/CoreJava$ javac StudentApplication.java
riddhi@debian7:~/CoreJava$ java StudentApplication
First Student Details :
RollNo : 101
Name : Ram
Marks : 87
Grade : A
Second Student Details :
RollNo : 102
Name : Rajj
Marks : 78
Grade : A
riddhi@debian7:~/CoreJava$
Q.43) What is a Constructor ?
A Constructor is a Specialzed method of a class whose name and class name is the same and does not have any return
type not even void. constructor is not behaviour of the object.
eg.
class ConstructorDemo
{
ConstructorDemo()
{
//Initialization Code
}//Constructor
}//ConstructorDemo Class
A Constructor is different from an instance method in the following area`s
(1) Name :Constructor Name and class should be the same.
Generally instance method name and class name is not made same.
(but we can,How?=>by giving return type to constructor,it become itstance method with SAME class name and method
name )
(2) Return Type :instance method should have a return type atleast void.
Constructor should not have any return type not even void.
Note :- if return type is specified to a Constructor , it becomes an instance method.

(3) Type of calling :A Constructor implicitly called as well as explicitly.


Instance method called explicitly only.
"can constructor call explicitly,if yes ,how=>super(12),this()/this(22)"
(4) Time of calling :Constuctor is a 1st method that is called on the object in its life time.
after constructor execution instance method can called.In fact after JVM binds the object to the reference variable(i.e.
after the HASHCODE return by JVM to the application), using that instance method
is called on the object.
(5)Frequency of calling :Constructor is called only once in the lifetime of object where , instance method is called any number of times on an
object.
(6)Caller :- JVM calls the constructor.
Any other method(constructor/other instance method) can calls instance method of an object, but not JVM calls instance
method.
(7)purpose(usage) :WHAT IS PURPOSE OF CONSTRUCTOR ?
constructor`s main purpose is to give some initial state to an object. i.e. object initialization is the main puspose of a
Constructor. 1st of all , an object has default State given by the JVM. Constructor provide some valid state to the object
before it is being used.
Any Resources(method,other object,file anyone who ) required for the object soon after its creation but before it is being
used in the constructor for eg.for database connection can done in constructor. image loading,frame creation.
As soon as the object is created whatever task you want to performed in the application, that task performing code can be
placed in the Constructor.
Note :- it is not advisable to have much logic in the Constructor.
A Constructor is not the interface(mediator bitween outside object and object) of an object to the outside world unlike an
instance method.
Note :- there are Scenarios where an object is constructor by the JVM in the heap Memory but its constructor is not
called. similarly constructor is called by JVM but object of the class is not created by JVM(how?Inheritance time).
HOW ARE CONSTRUCTOR CLASSIFIED ?
1. Non-parameteries constructor/Zero Constructor/Default Constructor
2. Parameteries Constructor
Note :- if no Constructor is explicitly placed in a(no constructor created by user) java application, compiler
by default write a Non-parameteries constructor/Zero Constructor/Default Constructor.
therefore ZeroArguments constructor is also called as default constructor.
Default Constructor provide same State to every object of the class.if we want to have defferent initial state
to different objects of the same class, we can go for parameteries Constructor.
/*after constructor execution instance method can called.In fact after
JVM binds the object to the reference variable(i.e. after the HASHCODE return by JVM to the application), using that
instance method is called on the object.?
we can call instance method during the constructor execution and also before assigning reference (hashcode) to reference
variable
instance method can call
class A
{
int aa;
A()
{
this(10);
System.out.println("0 p");
}
A(int a)
{
x();//during execution of constructor and
//before reference given to reference variable instance method can call
System.out.println(a+" p");
}
void x()
{
aa++;

System.out.println("RR"+aa);
// A.main();
}
public static void main(String args[])
{
new A(10).x();
}
}
Q.44) What is outout of following Java Application ?
class A
{
A(int a)
{
System.out.println("Class A is Instantated");
}//Parameteries Constructor
public static void main(Striing args[])
{
A a=new A();
}//main
}//class A
/* OUTPUT
riddhi@debian7:~/CoreJava$ javac ParameteriesConstructor.java
ParameteriesConstructor.java:9: cannot find symbol
symbol : constructor ParameteriesConstructor()
location: class ParameteriesConstructor
ParameteriesConstructor ParameteriesConstructorObject=new ParameteriesConstructor();
^
1 error
riddhi@debian7:~/CoreJava$
*/
/*
The Above Program causes Compilation ERROR
In the object creation syntax,zero-argument constructor is used but , in class A
Zero-argument Constructor is not available.
We can fix this ERROR in three ways
1)create the object with appropriate parameteries constructor syntax
eg. ParameteriesConstructor ParameteriesConstructorObject = new ParameteriesConstructor(10);
2)let compiler provide implicite default constructor.
Remove parameteries constructor.(bad work to remove some thing from already written code)
3)place explicit default constructor in addition to parameteriesed constructor
class A
{
A()
{
}//Parameteries Constructor
A(int a)
{
System.out.println("Class A is Instantated");
}//Parameteries Constructor
}//class A
Q.45) Develop a Java Application in which Constructor overloading is Implemented ?
Whithin the same class having multiple constructors with different signitures is called as Constructor Overloading.
ConstructorOverloading.java
class ConstructorOverloading
{
int price;
String title;
String Author;
ConstructorOverloading()
{

price=20;
Author="Yashawant Kanetkar";
title="Let us C";
}//Zero-Arguments Constructor
ConstructorOverloading(String t,String A,int p)
{
price=p;
title=t;
Author=A;
}//parameteriesConstructor
void displayBookDetails()
{
System.out.println("Title is : "+title);
System.out.println("Author is : "+Author);
System.out.println("Price is : "+price);
}//displayBookDetails
public static void main(String args[])
{
ConstructorOverloading obj1=new ConstructorOverloading();
System.out.println("First Book Details.....");
obj1.displayBookDetails();
ConstructorOverloading obj2=new ConstructorOverloading("Complete Reference","Schildt",300);
System.out.println("Second Book Details.....");
obj2.displayBookDetails();
ConstructorOverloading obj3=new ConstructorOverloading();
System.out.println("third Book Details.....");
obj3.displayBookDetails();
}//main
}//class ConstructorOverloading
OUTPUT
riddhi@debian7:~/CoreJava$ javac ConstructorOverloading.java
riddhi@debian7:~/CoreJava$ java ConstructorOverloading
First Book Details.....
Title is : Let us C
Author is : Yashawant Kanetkar
Price is : 20
Second Book Details.....
Title is : Complete Reference
Author is : Schildt
Price is : 300
third Book Details.....
Title is : Let us C
Author is : Yashawant Kanetkar
Price is : 20
riddhi@debian7:~/CoreJava$
Q.46) When Constructor is giving Some Valid State to the Object , is it advisable to have an instance method to give state
to the object (in the same class)?
Yes, we should have, In Fact Constructor calls only once. it can be used to give only initial state to
the object. if we want to change the state of the object later according to application requirement constructor can`t be
called again only instance method serves the purpose.
Q.47) What is constructor Chainning ?
calling a constructor of an object within the other constructor of the same object is nothing but constructor chaining.
"this" keyword is used for this purpose.
ConstructorChaining.java
class ConstructorChaining
{
int price;
String title;
String Author;
ConstructorChaining()

{
price=20;
Author="Yashawant Kanetkar";
title="Let us C";
}//Zero-Arguments Constructor
ConstructorChaining(String t,String A,int p)
{
price=p;
title=t;
Author=A;
}//parameteriesConstructor
void displayBookDetails()
{
System.out.println("Title is : "+title);
System.out.println("Author is : "+Author);
System.out.println("Price is : "+price);
}//displayBookDetails
void ChangeState(String t,String a,int p)
{
price=p;
title=t;
Author=a;
}//ChangeState
public static void main(String args[])
{
ConstructorChaining obj1=new ConstructorChaining();
System.out.println("First Book Details.....");
obj1.ChangeState("Complete Reference","Schildt",300);
obj1.displayBookDetails();
ConstructorChaining obj2=new ConstructorChaining("Complete Reference","Schildt",300);
System.out.println("Second Book Details.....");
obj1.ChangeState("Let us C","Yashawant Kanetakar",200);
obj2.displayBookDetails();
ConstructorChaining obj3=new ConstructorChaining();
System.out.println("third Book Details.....");
obj1.ChangeState("Complete Reference","Schildt",300);
obj3.displayBookDetails();
}//main
}//class ConstructorChaining
OUTPUT
riddhi@debian7:~/CoreJava$ javac ConstructorChaining.java
riddhi@debian7:~/CoreJava$ java ConstructorChaining
First Book Details.....
Title is : Complete Reference
Author is : Schildt
Price is : 300
Second Book Details.....
Title is : Let us C
Author is : Yashawant Kanetakar
Price is : 200
third Book Details.....
Title is : Complete Reference
Author is : Schildt
Price is : 300
riddhi@debian7:~/CoreJava$
Q.48) What is output of the following application
CarApplication.java
class Car
{
String regno;

float price;
Car(String regno,float price)
{
regno=regno;
price=price;
}//parameteries constructor
void displayCarDetails()
{
System.out.println("Reg No ="+regno+"\nPrice"+price);
}//instance method
}//class Car
class CarApplication
{
public static void main(Sring args[])
{
Car c = new Car("TG119092",400000);
c.displayCarDetails();
}//main
}//class CarApplication
OUTPUT
riddhi@debian7:~/CoreJava$ javac CarApplication.java
riddhi@debian7:~/CoreJava$ java CarApplication
Reg No =null
Price0.0
riddhi@debian7:~/CoreJava$
Reason for the unexpected output is name clash between instance variables and local variables
whatever variables name & parameters name of a constructor or instance variables are matching,
precedence is given to parameter name.
disambiguate the name clash between instance variable and local variable..to solve it, use 'this' Keyword
To overcome the name clash, we make use of "this" keyword.
for eg.
Car(String regno,float price)
{
this.regno=regno;
this.price=price;
}//parameteries constructor
"this" act as the implicit reference to the current object, At that time the constructor or instance method call.
Q.49) What is use of "this" keyWord
1.in constructor chaining
2.to disambiguate the name clash between instance variable and local variable.
About This KeyWord From FB_only .........................
1)
this() refers to same class constructor.
this can be used to call overloaded constructors as follows class Loan{
private double interest;
private String type;
public Loan(){
this(personal loan);
}
public Loan(String type){
this.type = type;
this.interest = 0.0;
}
}
this can be used as return value public - Loan getLoan(){ //do some calculations
return this;
} etc.. etcc..
2)we use this keyword to distinguish or show class members,and local variables while we use same names
3)reference to the object on which you are invoking methods or to which you are currently talking to.
4)used To differentiate from instance variable and local variable

5)This keyword points to the current objects that means it holds the reference of current objects. it is used to avoid data
shadowing. whenever the class level variable and local variable both are having same name then this is known as data
shadowing.
6)
2 access current object in the program
7)
7.1)this keyword can be used to refer current class instance variable.
7.2)this() can be used to invoke current class constructor.
7.3)this keyword can be used to invoke current class method.
7.4)this can be passed as an argument in the method call.
7.5)this can be passed as argument in the constructor call.
7.6)this keyword can also be used to return the current class instance. learn
Please Give Separate Example For Each Usage of "THIS"
7.1)Class Student
Student(int sno)
{this.sno=sno;}
7.2)Class Student
Student()
{
this.Student(12)
}
Student(int sno)
{}
main()
{Student s=new Student();}
7.3)
public String getDescription(){
return this.toString();
}
7.4)
if ( "testString".equals(this))
7.5)
Person p = new Person(this);//where it is used ?
// called from within the Person class, where Person has a constructor which takes an instance of Person (or Object) as
parameter
7.6)
public Person returnCloneOfCurrentPerson(){
return this;
}
Q.50) What is OUTPUT of following Java Application ?
StaticVariable.java
class StudentStatic
{
int rollno;
String name;
int Student_Count;
StudentStatic(int rollno,String name)
{
this.rollno=rollno;
this.name=name;
Student_Count++;
}//parameteries Constructor
void displayStudentCount()
{
System.out.println("No of Student Registered :"+Student_Count);
}//displayStudentCount
}//class StudentStatic
class StudentStaticApplication
{
public static void main(String agrs[])

{
StudentStatic s1=new StudentStatic(1000,"Ram");
s1.displayStudentCount();
StudentStatic s2=new StudentStatic(1000,"Ram");
s2.displayStudentCount();
}
}//class StudentStaticApplication
OUTPUT
riddhi@debian7:~/CoreJava$ javac StudentStaticApplication.java
riddhi@debian7:~/CoreJava$ java StudentStaticApplication
No of Student Registered :1
No of Student Registered :1
riddhi@debian7:~/CoreJava$
Reason for the unexpected output is "Student_count" is ment for representing the class level info.
instance variable are ment for representing one object info. i.e. instance level info.
*"Student_count Should be the class variable rether than instance veriable."* using static keyword it will become class
variable.
Q.51) What are Difference between instance variable and class variable ?check Q.37 also...
instance variable (object level) class variable
1.non-static data members
1.static data members of a class of class
2.per object variable i.e.
2.per class (not per objeact) i.e. for each instance one for the whole class only one copy
seperate copy is created is created. irrespective of the object crated.
3.property of an object meant 3.not the property of the object. So for representing the State should not be ment for
representing of the object. the state of an object.
4.owned by an object
4.not owned by any object only shared by every object.
5.memory allocated in heap
5.memory not allocated in heap.
6.contributes to the size
6.does not contrubute size of an object of an object
7.memory is allocated only
7.memory is allocated as soon as the when object is created class is loaded & before any
object of that class is create.
8.should be used to represent 8.should be used to represent class individual object info. levelinformation.
Q.37) What is Differece BetWeen Instance Variable and Local Variable ?chech Q. 51 also....
INSTANCE Variable
LOCAL VARIABLE(method level)
1.form the structure of the 1.Do not contribute to the size Object of the Object
2.Declare in a class but
2.Declared inside the a method outside the method
3.Memory allocated in
3.Memory Allocated in Stack Heap Area area
4.Access Modifiers can
4.Access Modifiers can`t be Applied be Applied
5.life=Object life time
5.life=For the duration of the method execution.
6.class scope(available)
6.only method scope in the method of the (not available in class other execution)
7.JVM gives default
7.JVM doesn`t give values default values.(it must define before used)
8 Local variable have higher precedence than instance variable.......
9 only final modifier(final keyword) can be used with local variable to make that variable constant.....
Q.52) What are similarities between instance variable and class variable ?
1.both are class scoped variables. i.e. both are available to all the method of the class.
2.JVM give default value for both of them, soon after their creation
3.accessibility mode can be applied for the both of them.
Q.53) what is a class method ?
Static method cab be called on the class aw well as on the object.
eg.(on class)StudentStatic.displayStudentStaticCount(); (on object)s1.displayStudentStaticCount();
but instance method calls on the object only. without need of an object creation, to access class level information,Static
method are used.
Q.54) what is a static initializer ?(static block)
static block is called as static initializer.
To initialize static variable according to application requirement static block is used.
*As soon as the object is created , whatever task we want to perform , that task performing code is written in constructor.
*similarly as soon as the class is loaded whatever task we want to perform that task performing code is written in static
block.
if a class has static block and main method , the following thing hapens in order.
1.)memory is allocated for static variables.
2.)JVM gives default values to static variable.

3.)JVM execute static block.


4.)JVM calls main method.
/* The class is loaded whatever task we want to perform that task performing code is= like database connestion,load
images,load file,etc..
*/
/* class loading time whatever task u want to perform or static variable initialization can do using static block, thats it.
*/
Q.55) What can`t be done in a static method ?
1."this" can`t be used. (because static block called by JVM, you use this means you use JVM and thats not possible in
java)
2.instance variable and methods can not be used without creating the object.
Note :- in an instance method static variables and method can be referenced.
Q.56) develop a java application in which 2 distances(Distance object) are added to get the resultant distance object.
display the state of all the three object ?
expected/application output
---------------------------------------------------------------------------------DistanceApplication.java
1st distance 9 feet 10 inches
2nd distance 10 feet 9 inches
resultant distance 20 feet 7 inches
*/
class Distance
{
int feet;
int inches;
static
{
System.out.println("Distance type is loaded");
}//static initializer/static block//=> actually no use of static block here in this application
Distance(int feet,int inches)
{
this.feet=feet;
this.inches=inches;
}//parametries constructor
void displayDistance()
{
System.out.println(feet+"Feets : "+inches+"Inches.");
}//behaviour and every distance variable
static Distance addTwoDistances(Distance d1,Distance d2)
{
int f=d1.feet+d2.feet;
int i=d1.inches+d2.inches;
while(i>=12)
{
f++;
i=i-12;
}//while
Distance tempObj=new Distance(f,i);
return tempObj;//not object return , only hashcode of objects return
}//static method->not the behaviour of the object
}//class Distance
class DistanceApllication
{
public static void main(String args[])
{
Distance d1=new Distance(10,9);
System.out.print("1st Distance is ");
d1.displayDistance();
Distance d2=new Distance(9,10);
System.out.print("2nd Distance is ");

d2.displayDistance();
Distance d3=Distance.addTwoDistances(d1,d2);//not object send to method, only reference(hashcode) sends
System.out.print("resultant Distance is ");
d3.displayDistance();
}//main
}//class DistanceApplication
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac DistanceApplication.java
riddhi@debian7:~/CoreJava$ java DistanceApllication
Distance type is loaded
1st Distance is 10Feets : 9Inches.
2nd Distance is 9Feets : 10Inches.
resultant Distance is 20Feets : 7Inches.
riddhi@debian7:~/CoreJava$
*/
/*
Q.57)Does Java support Call By Reference ?
Java support only CallByValue but not CallByReference.
CallByReference means sending memory address to called method.
in java you can not point to memory address,because java does not have pointers.
Q.58)Does a method take object as ergument?
No, it take reference of object.(core java level)
Note :- it calling method and called method are running on 2 different JVM
in a distributed application , object are supplied as arguments.
(object is supplied as agrument means "whole" objeect sends to other method) whole object means with all
properties/variable....
whatever change happen in sent object thats permanent , ryt?*/
Q.59)Does a Java method`s returns an object to the calling method ?
NO,only reference is return.
Note:- if calling method and called method are running in two different JVM`s in a distributed application a method
returns as object to the calling method.
ACCESS MODIFIERS
Q.60) What is an access modifier?
Access modifier is an a keyword used to specify(modify) the accessibilitymode/visibility mode to the member(variable
& methods) of class.
In java there are 3 access modifier.
(1)private.
(2)protected.
(3)public
In java there are 4 accessibility mode.
(1)private.
(2)protected.
(3)public.
(4)default.
if no access modifier is applied to a member of a class, that whill be in default accessibility mode.
eg.
class Employee
{
int empno;
protected String name;
private float salary;
public int deptno;
private void calculateSalary();
//protected void calculateSalary();
//public void calculateSalary();
}
empno has default accessibility mode.
name has protected accessibility mode.

salary has private accessibility mode.


deptno has public accessibility mode.
1.private :if "private" modifier is applied to the member of the class, they have class level visibility/accessibility i.e.private
method or private variable can be accessed by other methods of the same object. (class level visibility)
2.Default Aceessibility Mode :if no access modifier is applied to the variable or method of a class. these will be in default accessibility mode.
"Package level visibility" i.e. all the mothods of all the classes of the same package(folder) can be access default
members of the class. (package level visibility)
3.Protected Modifier :- provides package level+child class visibility. (child class can be outside the package)
(package level visibility + sub level)
4.public modifier :- if a member of a class is associated with pubic modifier.
it has entire java environment level visibility(as long as it is available) (java Environment level visibility)
//MESSAGE PASSING.............................
Q.61) what is an object oriented system(application/project) ?
An object oriented System is collection of co-operative object that are mostly polymorphism and related one another
through has-a,use-a and is-a relationship.
Q.62) what is the purpose of message passing ?
To facilated interobject communication, message passing is used.
In an object orinted sysrem ,an object receive the (user/client) request , does some portion of processing and
remaining portion of processing sake it has to communicate
with other object.
Q.63)What are the element of the message passing ?
1.message sender(object)
2.message receiver(object)
3.message (method)
1.)Message sender is in need of assistance from the other objcet. therefore it is also called as service requester.
2.)Message receiver object provide the service to the message Sender. therefore it it the service provider object .
obj(sender)--------(send the message)------------>obj(receiver)
Q.64) What is message passing ?
One object making a method call(passing a message) on another objetc is nothing but message passing.
*Calling method bolong to which object that object is the Message Sender.
*& called method belong to which object that object is that Message Receiver.
*called Method is the Sent Message.
for eg.
class A
{
void x()
{
B b=new B();
b.y();//inter-object communication ...x() calling method...and y() called method
z();//self message ...x() calling method...and z() called method
}
void z()
{
System.out.print("self message");
}
}
class B
{
void y()
{
System.out.print("Inter-Object communication");
}
}
x() is calling method.
y() is called method.
x() belong to class A therefore message sender is the instance of class A.
y() belong to class B therefore message receiver is the instance of class B.
y() is Message.

x() is calling method.


z() is called method.
x() belong to class A therefore message sender is the instance of class A.
z() belong to class A therefore message receiver is the instance of class A.
z() is Message.
Note:- when calling method & called method belong the same object explicit reference is not required. implicit reference
is available(this).
class A
{
void x()
{
this.z();//self message
z();//self message...JVM convert into "this.z();"
}
void z()
{
System.out.print("self message");
}
}
/*
Q.65)Develop a java application in which inter-object communication is implimented ?
MessagePassingApplication.java
class Controller
{
Service Sobj=new Service();
public void handleRequest()
{
System.out.println("Constroller receive client request it needs processed data for the client");
Sobj.processedData();//Controller communicate with Service
}//handleRequest
}//Constroller
class Service
{
Dao Dobj=new Dao();
public void processedData()
{
System.out.println("to provide processed data to controller, service needs database data, it should send the message to
Dao");
Dobj.accessData();
}//processedData
}//Service
class Dao
{
public void accessData()
{
System.out.println("Dao accessing database data and returning to service object");
}
}//class Dao
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac MessagePassingApplication.java
riddhi@debian7:~/CoreJava$ java MessagePassingApplication
Constroller receive client request it needs processed data for the client
to provide processed data to controller, service needs database data, it should send the message to Dao
Dao accessing database data and returning to service object
riddhi@debian7:~/CoreJava$
Q.66) What is method overloading ?
Within the same class defing multiple methods with the same name and Different Signature is nothing but method
overloading.
*Signature of a java method means "Method name + parameter list"

*In the implementation of overloading any how, method name are the same therefore,the signature to be differ.
*Atleast one of the following 3 criteria should not be matching among the methods for the parameters to be different.
1. Number of parameters.
2.type of parameters.
3.order of parameters type.
Q.67) Develop a java Application that implements the concept of method overloading ?
MethodOverloadingApplication.java
*/ class Item
{
int code;
String name;
float price;
void giveDataToItem(int code,String name,float price)
{
this.code=code;
this.name=name;
this.price=price;
}
void giveDataToItem(float price)
{
this.price=price;
}
void display()
{
System.out.println("Code is ="+code);
System.out.println("Name is ="+name);
System.out.println("Price is ="+price);
}
}//ITEM
class MethodOverloadingApplication
{
public static void main(String args[])
{
Item i=new Item();
i.giveDataToItem(100,"UCR",3500);
System.out.println("Item Details....");
i.display();
i.giveDataToItem(3600);
System.out.println("After changing price , details of Item");
i.display();
}//main
}//class MethodOverloadingApplication
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac MethodOverloadingApplication.java
riddhi@debian7:~/CoreJava$ java MethodOverloadingApplication
Item Details....
Code is =100
Name is =UCR
Price is =3500.0
After changing price , details of Item
Code is =100
Name is =UCR
Price is =3600.0
riddhi@debian7:~/CoreJava$
Note :- In Item Class , giveDataToItem() method is overloaded. there are two forms of this method.
one form doing one task. another form doing another task. In fact, method is not overloaded Instead method name is
oveloaded.

Q.68)what is binding in java ?


Associating(linking) the method call with method defination is know as binding.
Binding is of two types
1.) Static/early/Complile time binding.
2.) Dynamic/late/rentime binding.
1.) Static/early/Complile time binding :If the method is resolved(i.e.method call associated with method defination) at compile time is called as
Static binding.
2.) Dynamic/late/runtime binding:If the method is resolved(i.e.method call associated with method defination) at run time is called as
Dynamic binding.
Q.69) According to the behaviour of objects how are polymorphism classified?
1)Monomorphic object
2)Polymorphic object
1)if an object is bevaviour uniquely in all the context(situation) it is said to be monomorphic object.
2)if an object behaves differently, in different context, that object is said to be polymorphic.
Method of an object is nothing but behaviour of that object. An object is behaving means method of that object is
running(under execution) (different behaviour means State of Object should Differe in Different context)
Method is the interface(mediator/communacator) between an object and its surrounding(other object)
Q.70) Explain About Polymorphism ?
"Poly" means many and morphic means "forms"
One Interface(mediator/method) multiple forms (method definations) is the key feature of polymorphism.
An entity behaving differently in different situation is nothing but entity is exhibiting polymorphism.
An object behaving(reacting) differently for the same message in different situation is nothing but polymorphism.
Q.71) how to make java object polymorphic ?
1.)By implemanting method overloading.
2.)......
Q.72) How is polymorphism classified ?
1.Static polymorphism.
2.dynamic polymorphism.
1.Static polymorphism:Method name same,binding is static;
Static polymorphism implemented.
1.Dynamic polymorphism:Method name same,binding is dynamic;
Dynamic polymorphism implemented.
1.static polymorphism(at Compile time) is overloading
2.dynamic polymorphism(at Run time) is overridding(in inheritance )/overloading at Inheritance time.?
2....... When super class reference hold sub class object.....?
Q.73) how to ipmlement static polymorphic in java?
1.) by overloading instance method of a class.
2.) by overloading static method of a class.
3.).....
Q.74) How does polymorphism offer for applications ?
Polymorphism fecilates develop extensible system(application).(Object/Method)
(Object name same but different object store........Name Reusability?
/Method name same but get different definations....same message..different bahav...?
no need to change structure(Object/)..when only defination(behaviour of object when changes requires.... ?
Application struture remains same)) ?
Q.75
Inheritance....................
The mechanism of new entities aquiring features from already existing entities is konw as inheritance.
New entities aquire properties and behaviour from the already existing entities.
The process / mechanism of creating new classes from already existing classes through IS-A relationship is called
inheritance.
Aready existing classes are called as parent class or super class.
Newly created classes are called as child classes or sub classes.
In java, extends keyword is used to create parent-child(IS-A) relationship.

for eg.
class Vehicle
{
}//super class
class Bus extends Vehicle
{
}//sub class
sub classes inherits struture(data members) and behaviour(instance method) form the super class.
Note :- Constructor are never inherited.
super classes are know as generalised classes and sub classes are know as specialised classes.
employee(name,age,empno,salary)---------->person(name,age)<--------student(name,age,rollno,marks)
In a hierarchy of classes the higher the class in the hierarchy, the more generalised it becomes.
Similarly the lower the class in the hierarchy , the more specialized it becomes.
Sub classes(object) are generally meants for substituting the super class in usage.
Q.76) what are different types of inheritance ?
2 types.....
1.) Single inheritance.
2.) Multiple inheritance.
If a super class has multiple subclasses, that form of inheritance is called hierarchical inheritance. hierarchical inheritance
is only a type of single inheritance.
class A
{
}
class B extends A
{
}
class C extends A
{
}
Note :- Single inheritance is that form of inheritance in which , a sub classes have only one super class.
java.lang.Object is the super class of(/for) all classes in java.
if a subclass is acting as a super class of another subclass , that form of inheritance called as multilevel
inheritance.multilevel inheritance is only a type of single inheritance.
eg.
class A
{
}
class B extends A
{
}
class C extends B
{
}
Note :- single inheritance are classified into two type
1.) Hierarchical Inheritance.
2.) Multilevel Inheritance
Q.77) Develop a java application in which , Single Inheritance is implemented .
SingleInheritanceApplication.java
import java.util.*;
class Person
{
Scanner s = new Scanner(System.in);
int age;
String name;
void giveDataToPerson()
{
System.out.println("Enter Age : \t");
age=s.nextInt();
System.out.println("Enter Name : \t");

name=s.next();
}//GiveDataToPerson
void displayPersonDetails()
{
System.out.println("Age : \t"+age+"\nName : \t"+name);
}//displayPersonDetails()
}//class Person
class Employee extends Person
{
float salary;
void giveDataToEmployee()
{
giveDataToPerson();
System.out.println("Enter Salary : \t");
salary=s.nextFloat();
}//GiveDataToEmployee
void displayEmployeeDetails()
{
displayPersonDetails();
System.out.println("Salary \t"+salary);
}//displayEmployeeDetails()
}//class Employee
class SingleInheritanceApplication
{
public static void main(String args[])
{
Employee e = new Employee();
e.giveDataToPerson();
System.out.println("Employee Details......");
e.displayEmployeeDetails();
}//main
}//SingleInheritanceApplication
/* OUTPUT
riddhi@debian7:~/CoreJava$ javac SingleInheritanceApplication.java
riddhi@debian7:~/CoreJava$ java SingleInheritanceApplication
Enter Age :
23
Enter Name :
RN
Employee Details......
Age : 23
Name : RN
Salary 0.0
riddhi@debian7:~/CoreJava$
*/
Note :- instance variables of a super class contributes to the bone structure(size) of the sub class object irrespective of
their accessibility modes.
whenever subclass object is created , super class is not created only superclass constructor is called.
Q.78) Constructors in Inheritance
q.) What is the output of following application.
ConstructorInInheritanceTry.java
*/
class A
{
A(/*int i*/)
{
System.out.println("Super Class Constructor");
}//Constructor
}//A

class B extends A
{
B()
{
//System.out.println("Sub Class Constructor");
//super(10);no need to call super class constructor with zero parameter it called by JVM
System.out.println("Sub Class Constructor");
}//Constructor
}//A
class ConstructorInInheritanceTry
{
public static void main(String args[])
{
B b=new B();
}//main
}//ConstructorInInheritanceTry
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac ConstructorInInheritanceTry.java
riddhi@debian7:~/CoreJava$ java ConstructorInInheritanceTry
Super Class Constructor
Sub Class Constructor
riddhi@debian7:~/CoreJava$
*/
Note :- whenever sub class object is created , JVM calls appropriate constructor of the sub class first and from within the
subclass constructor , an implicitly call is made to the super class zero parameter(argument) constructor.
when object is created for this application only
1.)object get memory
2.)constructor of that object is called...
3.)in sub class constructor JVM wrote super(); at 1st line if any super(with parameter); line is not wrote by user;
4.)constructor execution start...
5.) so 1st line is super();
that means sub class constructor call to super class constructor
6.) then other line execute from super class....after executing super class
7.)reference comes to sub class constructor
8.)remaining code executed from sub class constructor
9.)then......object get reference and it pass to reference variable....and so on
Q.79) output
ConstructorInInheritanceTry1.java
*/
class A
{
A(int a)
{
System.out.println("Super Class Constructor");
}//Constructor
}//A
class B extends A
{
B()
{
//super();no need to call super class constructor with zero parameter it called by JVM
System.out.println("Sub Class Constructor");
}//Constructor
}//A
class ConstructorInInheritanceTry1
{
public static void main(String args[])
{

B b=new B();
}//main
}//ConstructorInInheritanceTry1
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac ConstructorInInheritanceTry1
error: Class names, 'ConstructorInInheritanceTry1', are only accepted if annotation processing is explicitly requested
1 error
riddhi@debian7:~/CoreJava$
*/
/* we can fix the compilation error in 3 ways
1.) ensure that super class has implicit default constructor.(remove parameteriesed constructor)
2.) overload the constructor in super class by specifying explicit default class. (write default constructor in super class)
3.)make an explicite call to the super class parameteries constructor from within the sub class constructor.
(wrote/call super(10); in sub class constructor)
Q.why jvm call super class constructor
Note:- To initialzed private variables of super class which belong to the sub class object from within the subclass
constructor an explicit call is made to the super class parameteries constructor.
Q.80) What is Method OverRiding ?
redefining the "functionality(method)" of super class method in subclass is nothing but method OverRiding.
During the implementation of method OverRiding , super class method is called as OverRidden method and sub class
method is called OverRiding method.
for eg.
class A
{
x()
{
}//OverRidden method
}//A(superclass)
class B extends A
{
x()
{
}//OverRiding method
}//B(subclass)
Note:- X method of parent class is OverRidden here.
Q.81) what are the rules of method OverRiding ?
1) both the methods i.e. OverRidden and OverRiding methods` Signature should be the SAME.
2) both the methods should have "Same Return Type".
3) OverRiding method should have same or Stronger(Should not have weaker) access Privileges than that of OverRidden
method.(equal and more is ok)
4) OverRiding method should not checked exception annouced thows clause that are not announced in the OverRidden
method.()unchecked exception can throws like ArrayOutOfBoundsException)
Note:- OverRiding rules are related to 4 area
1.)Signature.
2.)Return Type.
3.)Accessibility mode.
4.)Exception Specification(Throws clause).
Q.82) what is the purpose of method overRidding ?
1.)super class provided functionality not required for the child but name reusability is required for polymorphic reasons.
2.)parent(super) class provided functionality insufficient.
Note :- whenever , method OverRiding is implemented and the method is invoked on the sub class object version only is
executed.
Q.83) Develop a java application in which Method OverRiding is Implemented .
MethodOverRidingApplication.java
*/
class Vehicle
{
public void stop()
{

System.out.println("To Stop Vehicle");


}//stop
void move()
{
System.out.println("Any Vehicle should move this way");
}//move
}//Vehicle
class Car extends Vehicle
{
void move()
{
super.move();
System.out.println("But i can move Vehicle with own way ");
}//move
}//Car
class MethodOverRidingApplication
{
public static void main(String args[])
{
Car c=new Car();
c.move();
c.stop();
}//main
}//MethodOverRidingApplication
/* OUTPUT
riddhi@debian7:~/CoreJava$ javac MethodOverRidingApplication.java
riddhi@debian7:~/CoreJava$ java MethodOverRidingApplication
Any Vehicle should move this way But i can move Vehicle with own way To Stop Vehicle
riddhi@debian7:~/CoreJava$
Q.84)what are the different usage(uses) of "SUPER" keyword.
1.)To explicitly call super class parameteriesed constructor from within the sub class constructor.
2.)To Invoked OverRidden method From OverRiding Method.
3.)when super class Variable and sub class variable names are same , To refer to super class variable from within
subclass method.
Q.85)Can we OverRide Static Method ?
Instance method of super class can not be overridden with static method of sub class.
static method of super class can not be overridden with instance method of sub class.
By Following the same 4 rules of instance method OverRiding we can redefine superclass static methods in sub class
static method. but it is not called as method OverRiding, its called as Method Hiding.
Q.86)Compare and Contrast method OverRiding and Hiding ?
Method OverRiding Method Hiding
1.)redefining instance method 1.)redefining superClass static of super class in subclass method in subClass
2.)method resolution(method 2.)its based on Reference type dispatch)(which method to be or class type
called)is Based on object type not reference Type or class type
3.)Can participate in 3.)Always Implementats static Dynamic polymorphism Polymorphism. Implementation.
Q.87)Can we OverRide Private instance Method ?
No,
Even though private instance method redefine in subClass, it doesn`t come under method OverRiding as private
Instance Method of super class not directly available to subclass object.
Q.88)What are difference between method overloading and method OverRiding ?
OverLoading OverRiding
1.)Method`s Signature should 1.)Should be SAME be different.
2.)Method return type has 2.)Should be the SAME no role to decide
Overloading of the method 3.)Accessibility Mode does 3.)Plays. not play any role
4.)Exception specification 4.)plays. has no role to decide (Parent accessibility mode OverLoading. can`t decrese in child)
5.)Implements Static 5.)also Can Participate in the Polymorphism. Dnyanamic Polymorphism.
(With "super" keyword, super class , we can implement Dnyanamic Polymophism)

Q.89) Develop a Java Application in which following concept are iplemented


1.)OverRding
2.)Super class reference refering to the subClass Object
3.)Using Super class reference the method is invoked .
*/// DynamiceMethodDispatchApplication.java
import java.util.*;
class DynamiceMethodDispatchApplication
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Which Vehicle rewuired(car/zeep)?");
String choice=s.next();
Vehicle v;
if(choice.equals("car"))
v=new Car();
else
v=new Zeep();
v.move();
}//main
}//DynamiceMethodDispatchApplication
class Vehicle
{
void move()
{
System.out.println("Proving SameTransport service ");
}//move
}//Vehicle
class Car extends Vehicle
{
void move()
{
System.out.println("Proving Exllent Transport service ");
}//move
}//Car
class Zeep extends Vehicle
{
void move()
{
System.out.println("Proving Very Good Transport service ");
}//move
}//Zeep
/* OUTPUT
riddhi@debian7:~/CoreJava$ javac DynamiceMethodDispatchApplication.java
riddhi@debian7:~/CoreJava$ java DynamiceMethodDispatchApplication
Which Vehicle rewuired(car/zeep)?
car
Proving Exllent Transport service
riddhi@debian7:~/CoreJava$ java DynamiceMethodDispatchApplication
Which Vehicle rewuired(car/zeep)?
zeep
Proving Very Good Transport service
riddhi@debian7:~/CoreJava$
Q.90)OUTPUT
class A
{
}//A
class B extends A
{
void x()

{
System.out.println("SubClass");
}//x()
}//B
class Test
{
public static void main(String args[])
{
A a=new B();
a.x();
}//main
}//Test
/* OUTPUT
riddhi@debian7:~/CoreJava$ javac Test.java
Test.java:19: cannot find symbol
symbol : method x()
location: class A
a.x();
^
1 error
riddhi@debian7:~/CoreJava$
*/
/*
Note:- The Above Application causes compilation error.
reason:-using "SUPER CLASS REFERENCES SUB CLASS SPECIFIC (NON-OVERRIDE )METHOD CAN NOT
CALLED" if at all sub class specific method has to be called , type cast to the super reference to sub class.
like...
A a=new A();
B b=(B)a;//type cast to the super reference to sub class
Q.)why array index is started with zero? Why nt 1? ...answer From Net
From @Sushant Prasad Singh ::
1. Actually there are many disadvantage with the index of array starts with one. let suppose we are starting the index with
1 and now the size of the array is 8 so now we need to have number from 1-8 to represent the 8 length array but to
represent number 8 we need to use 4 binary digit (1000).... which we possible with 0-7 and number 7 need only 3 binary
digit. So its a costly in terms of memory.
2. Using index zero as the starting index makes compiler to do internally simply arithmetic like --> *(array + index)
now if we have starting index as 1 then compiler need to do following arithmetic like ---> *(array + (index-1)).....which
is again costly in terms of run-time calculation and hence take more time as compared to previous statement.
So its not like it can only starts with zero, the way compiler is designed which supports zero based indexing as because
one based indexing is little costlier in terms of size and time.
From @Gagan Deep Singh ::
digital electronics is one of the reasons behind this
i Think After Reading ......
At last All Code and All comes Under Electronic ...means Binary
10101 binary form...ryt?
Then see 1 digit binary
1
0
Now see 2 digit binary
00
01
10
11
3 digit binary
000
001
010
011
100
101

110
111
here , we see every where is comes 0,00,000 means ..........
there is something with 0,00,000...like memory, or in "and" "or" and all logical options
like that...................
when we create array , that time obviously there is created memory with 0 place....
because that array is from binary place in RAM....so OS created place like that.......
if Denis Rethie and James Gosling and all Language Creater not Created Array Index with zero then
also
Array Start With zero In RAM......is OS term.......
but All Language Developer could make Changes in Language but its will be costely....
like Above From @Sushant Prasad Singh `s answer....check it......
Image= whyArrayStartWithIndexZero'0'.jpg
Is this Right ?
Q.90) FINAL Modifier..................(final = after defining which can not change )
"final" is keyword that can be associated with variable,method and class.
when final is applied to a variable it becomes a constant. i.e. constants are created using final modifier.
Final variable should not be declare , it should be define.
final int a;//declare,get compilation error
final int a=10;//define
Programatically, final variable value can`t be change after its defination.
i.e. value can`t assigned to a final variable.
Final Methods are inherited i.e. final modifier when is associated with a method it doesn`t prevent inheritance.But a final
method can not OverRidden(i.e. can`t redefine with same name).
for eg.
class A
{
final void x()
{
}//final x()
final void y()
{
}//final y()
}//A
class B extends A
{
void z()
{
x();//valid(because it used only)
y();//valid(because it used only)
}//z()
void x()
{
}//.........Invalid ..Final method can`t OverRidden
}//B
Final class can not be SUBCLASSES.
for eg. final class A
{
}//A
class B extends A//invalid...final class can`t inherits
{
}//B
i think final means :->
1)final variables :- to prevent change them, only use them
2)final methods :- to prevent OverRide Methods, only use them
3)final classes :- to prevent Inheritance, only use them.

Q.92)What is purpose of final class ?


A Final class prevents subclassing,it "apprears(prevent)" that the most useful feature OOP i.e. inheritance. and there by
code reusability is prevented by Final Modifier.
The most generalised class is generally never made final.
The most Specialized class in the hirarchy i.e. leaf class in hirarchy can be mostly declared final to indicate that there is
no use in futher specializing that hirarchy.
Some times, to ensure mutability(non-modification) through prevent substitution, A most generaliqed class also can be
declared final for eg. java.lang.String class is a final class.
it only can use...not inherits and modify.
final class can have non-final methods and variables.but we can not change them because we can not inherit them.
When class have to declare final ? =>Q.92
Why String Class is Final ?
Q.93)Can a Local Variables be declare Final ?
Yes.
Q.94)Abstract Modifier ?//abstract means without defination(behaviour)
//Should not have method defination(body), they have only Declaration(Prototype)
Abstract Modifier can be applied to class and Method only
But not for Variable.
if Abstract Modifier is applied to method is becomes a Abtract Method
Abstract Method Should not have method defination(body), they have only
Declaration(Prototype) in that class.
for eg. x();//Method Defination is not compulsary in java.
Method with body are called as Conctrete method.
for eg. x()
{
}//x()
**if a method is abstract in a class, that class must be declare Abstract.
**vice - vesa not true.i.e. An abstract class need not have to abstract method.
it can have abstract as well as concrete methods.
**If a method is declared abtract in a class all its subclass must be implements
(OverRide) that method. otherwise those subclasses are must become asbtract.
******************Final method prevent method OverRiding where as Abstract Method Enforces
Method OverRiding.*************************
If "abstract" modifier is applied to a class it becomes abstract class.
**abstract class can not be instantiated only conctrete class cab be instantiated
An abstract class can have both conctrete and abstract methods. it even can have constructor
For eg.
abstract class A
{
A()
{
}//constructor
abstract void x();//x
void y()
{
}//y
}//A
Contrete class and abstract class different in only two ares`s
1.)Abstract class can not instantieted unlike contrete class.
2.)Abstract class can have Abstract methods unlike conctrete class.
Similarities........
1.)both are compiled i.e. class file and therefore they act as user define datatype. and consequencly reference can be
created.
2.)both can have instance method , static method and constructor.
3.)both can inherits..etc...
Note:-The Most generalised class in the hirarchy is generally declared as abstract that is too generalised to be physicaly
realiazed.

Q.95) What is purpose of an abstract ?


To provide service specification(method prototype) to the subclass and by enforceing service(giving method defination)
implementation.
Q.96) What is an interface ?
An interface is a class like construct of java programming language.
A java Interface is Created using the keyword "interface"
For eg.
interface I
{
//final variables
//abstract methods
}//interface
An interface contains methods and variables.
An interface compiled to .class file(like class)
An interface act as user define datatype and therefore its reference can created.(like class)
A class can inherits(sub class) from an interface(super class).
vice-versa n`ot true.
An interface can participiate in IS-A,HAS-A and USE-A relationship types in java based object oriented system.
An interface can inherits from another interface by iplements and extends keyword
For eg.
interface I1
{
}I1
interface I2 extends I1
{
}//I2
interface member are implicitly public , no other accessiblity mode is allowed.
(you can give public access modifier to members but no need its by default in public mode.
no other access modifier allowed and if you not given any access modifier to interface members(methods and variables)
its get public accessibility mode(not default accessibility mode unlike class members))
Variable of an interface are by default static and final.(no need to write explicitly)
methods of an interface are implicitly public and abstract only(and it can not changed). i.e. interface can not have
concrete methods.
"implements" keyword is used to create IS-A relationship between a class and interface.
q. *** " interface implements interface ?"no, because implemets means give definations to methods...
but interface methods are abstract only.....?(yes)
Note:-to create IS-A relationship between types in a java based object oriented system.
Java Language Provide Two kaywords to Create IS-A relationship.
1.)extends
2.)implements
interface I1
{
}//I1
interface I2 extends I1
{
}//I2
Reference of an interface can be created but it can`t instantiated i.e.
interface object can not created.
one interface can not implements another interface.........
interface I
{
void x();
}//I
// riddhi@debian7:~/prog$ vim InterfaceDemo2.java
// riddhi@debian7:~/prog$ javac InterfaceDemo2.java
interface A implements I//Error......
{
void x()
{

//body
}//x()
}//A
whenever a class is implementing an interface that class must implements(provide body for all the abstract methods of
that interface)otherwise that class must be declared as abstract.
interface I
{
void x();
}//I
class A implements I
{
void x()
{
//body
}//x()
}//A
Q.97) Can a Class implement multiple interface ?
yes,
for eg.
class A implements I1,I2
{
}//A
Q.98) Can a Class Inherits from Multiple Classes ?
No.
Q.99) Does Java Support Multiple Inheritance ?
No.
Java Support Declarative Multiple Inheritance.
But not Implementation(extends , class) multiple Inheritance.
Interface is considered as declarative fellow within any implementation.
Class is an Implementation Entity.
Q.100) What is an Interface Object ?
Infact, Interfacce Object can`t be created.
Interface Object means reference is interface type and object is implementation class type.
DRIVER..............INTERFEACE (SUN MICROSYSTEM STANDARD)
/\
/\
/ \(IS-A RELATIONSHIP)(IMPLEMENTS INTERFACE)
/\
ORACLE DRIVER JDBC DRIVER(VENDORS)
Driver driver = new OracleDriver();
Driver driver = new JDBCDriver();
Q.101) What are the Similarities between an interface and an abstract class ?
Both are User Define Data type.
Both Can`t be instantiated.
Only Reference Can Created From both of Them.
Both Can Have Abstract Method.
Both May or May Not hava Methods.(both can be empty)
Both are meaningful in the context of Inheritance.
Q.102) What are the Difference between an abstract class and an interface ?
ABSTRACT CLASS
INTERFACE
1.)Can have Concrete Methods also 1.)Can not have Concrete Methods.
2.)Members have Package level
2.)it has public level visibility mode. visibility mode by default.
3.)Methods are not implicitely
3.)Methods are Implicitely abstract. Abstract.
4.)Can hava all kinds of variables.
4.)only static and final variables (default)
5.)Can have a Constructor.
5.)Can`t hava a Constructor.
6.)Can`t provide support for
6.)can provide support for multiple
multiple inheritance. Inheritance.
7.)Partially Abstract.
7.)Fully Abstract.(not completely)
8.)Provides Generaliazation.
8.)Provide Standariazation.

Note :Interface has service specifications, enforcing the implementation classes to provide service implementation.
Q.103) StandardizationApplication.java
interface Fan
{
public abstract void revolve();
//void revolve();
}//Fan
class KhaitanFan implements Fan
{
public void revolve()
{
System.out.println("Provides Very Good Fan Service");
}//public void revolve implements fan interface by giveing defination to abstract methods of this interface.
}//KhaitanFan
class UshaFan implements Fan
{
public void revolve()
{
System.out.println("Provides Exlent Fan Service");
}//public void revolve implements fan interface by giveing defination to abstract methods of this interface.
}//UshaFan
class FanDealer
{
static Fan provideGoodFan()
{
Fan fan = new UshaFan();
// Fan fan = new KhaitanFan();
return fan;
}//provideGoodFan
}//FanDealer
class StandardizationApplication
{
public static void main(String args[])
{
Fan fan = FanDealer.provideGoodFan();
fan.revolve();
}//main
}//class StandardizationApplication
OUTPUT
riddhi@debian7:~/CoreJava$ javac StandardizationApplication.java
riddhi@debian7:~/CoreJava$ java StandardizationApplication Provides Exlent Fan Service
riddhi@debian7:~/CoreJava$
Q.104) What is The Purpose Of Java Interface In Enterprise Application ?
Interface specifies the (service)contract between service requester and service provider.
Service Providered i.e. Implementation class of the interface carries out the contract.
An interface is a specification of services that its implementation instances provide.
In as Object Oriented System , an object as far as possible should Interface(intract) with other object through
interface(java interface).
Interace provides loose coupling between application components.
Reference type writing in object => loose coupling
Object type writing in Object => Tight Coupling
In interface java enterprise applications,controller objects,interface with service object
through service interfaces.sothat loose coupling is facilitated between them. simlarly service objects
use DAO interfaces to intract with DAO objects to facilitated loose coupling.
** with single interface , any vendor`s service can be initiliazed without changing the application source code.
Same Object --------------------->Parent (Interface)------------->Object 1(Class object)
/|\
/|\
/|\

/|\
/|\
/|\
/|\
Object 2 Object 3 Object 4
(Class object) (Class object) (Class object)
Q.105) How to create HS-A relationship between types in java ?
Declare the reference of one type as instance variable in another type in order to create
HAS-A relationship.
*/
class Constroller
{
Service service = ServiceFactory.getService();
}//Controller
class Service
{
DAO dao = DAOFactory.getDAO();
}//service
Constroller has HAS-A relationship Service.
Service has HAS-A relationship with DAO.
Q.106) How to create USE-A relationship between types ?
Declare of another type in order to create USE-A relationship.
for eg.
class LoginServlet
{
public Service(ServletRequest request,SrqvletResponse response)
{
}//Srevice
}//LoginSrevlet
Here,LoginService Object has USE-A relation with ServletRequest Object and Servlet Response.
Servle Config
.
/\
|
|
Generic Servlet
.
/\
| (ServletConfig as a instance)
|
HttpServlet
.
/\
|
|
LoginServlet
{
init(ServletConfig)
}
Here, its meke HAS-A,USE-A and IS-A relationship between LoginServlet and ServletConfig.
Q.107) What is a Package in java ?
"packege" is a grouping mechanism to group related java class files in order to make them available to other applications.
or to other parts of the same application.
Package Concept Provides the following things
1.) create a namespance (logical container in which no two files will have same name)
2.) Orgnising the related files fecilities better maintance
3.) facilated same level of security for data and code.(package level)
4.) fecilites make class files available to ither application or other parts of same application
Note :- Every java class files should belongs to a package.

JAVA package are two types.


1.)Built-in
2.)User-Defined
Q.108) Explain about bouil-in or (predefined) package ?
Library class files are grouped in/into bouilt-in packages.
In java , we have two kinds of built-in packages :
1.)Core Package.
2.)Extension Package.
Core Package Extension Package
||
||
--->Util --->Swing
||
||
--->Lang --->Servlet
|||
|||
--->rmi | --->Http
|||
|||
--->sql | --->jsp
||
||
--->awt -->sql
|||
|||
| --->event -->ejb
|
|
--->applet
|
|
--->net
|
|
--->io
A built-in Package whose root(base) package is "java" is called as core package.similarly,
extension package`s based package is "javax".
To refer to a subPackage, we use .(dot) notation in java.
for eg.
java.awt.event;
By Default lang package is(implicitely) available to all java application.
all library class files of "java.lang.*;" package are implicitely available to any java application.
In a java application if we want to use library class files of other packages , we need to include(import) explicitely.
"import" keyword is used to include library class files into a java application for eg.
import java.awt.event;
import java.io.*;
The above import statement makes all the classfiles of awt.event package to the application but it will not makes
available class files of sub packages.
Library inclusion is static in C, where as it is dynamic in java.
When a package is imported into a java application all the class files of that package are just made available to the
application but not contributes to the size of application.
which class files used in the application that class files only contributes the size of the application.
this is nothing but the very dynamic library inclusion concept in java.
Q.109) Explain about user define package ?
=> Application developer created packages are know as user define packages.
User defined class files are packaged into a user defined package and make available to the other application or other
part of same application.

Q.110) How to create User define package ?


Step.1)
write the package statement as the first non-comment java statement in the application source code.
"package" is a keyword in java.
for eg.
package myPackage;
Step.2)
compile the source code with "-d" opption additionally
When the above command is given at the command line the following things happens :1.)A user defined package is created in the current working folder.
2.).Class file in not placed in the current working folder, instead it is created in the user define package.
Now, the class file does not belong to cirrent working directory , instead is belongs to a user defined package.
Q.111) What is unqualified name of a java class/interface ?
without package name , only class name or interface name is unqualified name.
Q.112) What is fully qualified name of java classes/interface ?
Package Name + Class/interface Name
For eg. Oracle.jdbc.driver.OracleDriver.
Q.113) What is the standard nameing convention for a userdefine Package ?
Reverse Domain Naming Convention is followed for user define java packages.
//BalanceEnquiryController.java
package com.durgasoft.controller;
import com.gurgasoft.Service.AccountService;
public class BalanceEnwuiryController
{
AccountService accountservice;
}//
package com.durgasoft.Service;
import com.gurgasoft.DAO.AccountDAO;
public class AccountService
{
AccountDAO accountdao;
}//
package com.gurgasoft.DAO;
public class AccountDAO
{
}//
Note :- if a class is not declared as public , it can`t be used from other packages. interface members are public. but
interface itself is not public. Therefore onterface also should be declared public when it is in a user define package.
A Combination unit(source file .java) can`t have more than one public type(class/interface) To create user define
packages of the above three compilation units
we say javac -d . *.java (no 1st which file run...import package not available problem solved)
(-d for creating package) (. for current directory)
Note :- We have to compress all the class files of the user define packages into a jar file and placed
that jar file into classPath so that all the userdefine class files are available to other applications.
java -cf banking.jar com
Banking.jar(set classpath=.;Path/Banking.jar;)
|
|
\|/
'
com(package)
|
--->|
|
--->DurgaSoft(package)
|
|
--->DAO(package)
||
||

| --->*dao.class
|
|
--->Service(package)
||
||
| --->*service.class
|
|
--->Controller(package)
||
||
--->*controller.class
EXCEPTION HANDLING
Q.114) What are the different types of errors encountered during development and execution time of a java application ?
1) Syntactical errors raised by java compiler.
2) Runtime errors raised by JVM.
3) Logical errors(bugs) reported during the usage of the application.
Q.115) What is an Exceptions ?
Runtime errors is nothing but an exception.
Object oriented representation of (encapsulation) an abnormal event that occured during the (program) execution of a
application is nothing but Exception.
JVN raises the exception if runtime rules are voilated during the running of the application.
For eg.
Trying to open a file which is non-existing , Trying to connect to a server with wrong user name and password
Trying to divide by zero, Trying to load existing class file, etc................
Q.116) What are the dangers caused by an Exception ?
Application terminates abnormally once exception is raised.
Such abnormal termination of the programs leads to the following Problems (Dangers):1) End-user may lose work/data.
2) End-user Doesn`t have proper info about what went wrong.
3) Resouces allocated to the application can`t be realesed.
Q.117) What is an Exception Handling ?
To make java applications robust.
Exception handling is not meants for preventing the exceptions from occuring.
It is meant for preventing the abnormal temination of the application and there by overcoming the dangers caused by an
exception.
Q.118) How to Ipmlement Exception Handling in java application ?
Java provide support to deal with exceptions in java application in two(2) ways :
1)Language Support
2)Library Support
As Far as language support for exception handling in concurened. We have % keywords in java
1)try
2)catch
3)throw
4)throws
5)finally
To represent defferent abnormal events in the application, java has a hierachy of exception classes.
This is hierachy but library support.
java.lang.Throwable is the super class of all exception classes in java whose parent is java.lang.Object.
Throwable class has two subclasses
1)java.lang.Exception
2)java.lang.Errror
java.lang.Error class representing exception can`t be handled in an application.
java.langRuntimeException and all its subclasses are of types UNCHECKED EXCEPTIONS.
Except RuntimeException class , All other sub classes of java.lang.Exception are checked Exceptions
java.lang.Object
/\
java.lang.Throwable
/\

/\
Exception Error =>unchecked
/|\
RunTime SQL IOException
Exception Exception |
||
||
--->NumberNotFoundException --->FileNotFoundException
|
|
--->NullPointerException
|
|
--->ArrayIndexOutOfBoundsException
Q.119) What are the unchecked exception in java ?
Sub classes of java.lang.RuntimeException and java.lang.Error are considered as unchecked Exceptions.
Unchecked exception are those exceptions for which , compiler doesn`t enforce exception handling in the application.
In the application if there is a chance of unchecked exception raising and even if it is not handled,such non-handling ,
compiler doesn`t treat as syntactical error.
Q.120) develop a java application to prove that application is terminated abnormally if exception is raised but not
handled ?
WithoutHanding.java
*/
class WithoutHandling
{
public static void main(String args[])
{
int n1,n2,q=1;
System.out.println("Division Started");
n1=Integer.parseInt(args[0]);
n2=Integer.parseInt(args[1]);
q=n1/n2;
System.out.println("Result of Division is : "+q);
}//main
}//class WithoutHandling
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac WithoutHandling.java
riddhi@debian7:~/CoreJava$ java WithoutHandling 10 e
Division Started
Exception in thread "main" java.lang.NumberFormatException: For input string: "e"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:514)
at WithoutHandling.main(WithoutHandling.java:8)
riddhi@debian7:~/CoreJava$ java WithoutHandling 10 0
Division Started
Exception in thread "main" java.lang.ArithmeticException: / by zero
at WithoutHandling.main(WithoutHandling.java:9)
riddhi@debian7:~/CoreJava$ java WithoutHandling 10
Division Started
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at WithoutHandling.main(WithoutHandling.java:8)
riddhi@debian7:~/CoreJava$ java WithoutHandling
Division Started
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at WithoutHandling.main(WithoutHandling.java:7)
riddhi@debian7:~/CoreJava$
*/
/*

Values Supplied to main method from the command line are nothing but
commandline arguments. even though numbers are supplied they are considered as String only.
To Convert String representation of an integer into an Integer type we use
"parseInt" which is a static method of java.lang.Integer class.
Q.121) Explain about "try" keyword ?
"try" keyword is used to create a block of statements within the java aplication. which code is doubtful for raising the
exceptions, that code is placed in try block.
placing doubtful code in try block is nothing but we try to handle the exceptions which may be raised in that block during
the application execution.
If exception is not raised within the try block , try block will be executed comlitely.
If execution is raised within the try , instead of program getting terminated, remaining portion of try block gets
terminated. we can nest try blocks.
try block has to be followed by either catch block or finally block.*
Q.122) Explain about "Catch" ?
"catch" keyword is used to create a block of statements. In catch block , exception handling code is implemented
therefore catch block is called as exception handler. Catch is a method block as it appears like a methods.
control comes to catch block if and only if exception is raised in try block. i.e. catch block is not executed if exception is
not raised in try block. One try block can have any number of catch blocks. In a catch block , try and catch blocks can be
nested between try block and catch block. other java statements are not allowed.
Q.123) Develop application which implements exception handling ?
WithException.java
*/
class WithException
{
public static void main(String args[])
{
System.out.println("Division started");
int n1=Integer.parseInt(args[0]);
int n2=Integer.parseInt(args[1]);
try{
int q=n1/n2;
System.out.println("The Result of division is : "+q);
}
catch(ArithmeticException e)
{
System.out.println("Division failed :");
}
}//main
}//WithException
/*
OUTPUT
riddhi@debian7:~/CoreJava$ java WithException 10 2
Division started
The Result of division is : 5
riddhi@debian7:~/CoreJava$ java WithException 10 0
Division started
Division failed :
riddhi@debian7:~/CoreJava$
*/
Note :- If Exception is raised in the try block. JVM...... the kind of abnormality and by wrapping that information. it
constructs an exception object(corresponding exception object) and invokes the catch block by supplying the exception
of checked references as arguments. within the catch block through the exception reference, we can find the details of the
exception.
Q.124) Explain about "finally" ?
"finally" is used to create a block of statements. Nature of "finally" block is that it is executed in both the cases.
i.e. exception raised case and non-raised case. resources releasing code is implemented in fanally block.
for eg.
database connection closing, file closing etc...
Generally , finally block succeed catch blocks.
withing finally block also we may have to write try catch blocks.

getDefaultDatabase
{
getConnection=null;
}
try
{
con=x;
}
catch(Exception e)
{
}
finally
{
try
{
if(con!=null)
{
con.close();
}
}
catch(Exception e)
{
}
}
Q.125) Explain about "throw" ?
"throw" keyword is used to throw the exception explicitely from within the application.
"throw" keyword is not meant for create block of statement unlike try,catch and finally. In a java application, throw is
used with the following syntax : " throw new SomeException(); " some type of exception object has to be created in the
application and then throw it.
To propogate exception from one part of the application to the other part an exception is thrown explicitely.
sometimes input to the application doesn`t violate the java runtime rules therefore JVM doesn`t throw the exception .
but that input is againts the business rules of the application. To stop the further processing of that request with that
input, exception is thrown explicitely.
Q.126) Explain about "throws" ?
"throws" is not meant for throwing the exceptions unlike that of "throw". "throws" keyword is associtaed with method
header(declaration).
for eg.
public void accessData() throws AccountNotFoundException,DatabaseExcaption throws
AccountNotFoundException,DatabaseException =>throws clause throws keyword is used to create exception
specification for a java method.
in the above example , whithin the throws clause of the method multiple exception are announced.
throws is used to announced/declare the callers of the method that its body has doubtful code and might not have been
handled end there by forcing the caller to implement exception handling for that type of exceptions.
To pass on the exception handling duty to the higher level(caller of the method) , we use throws keyword.
Q.127) What is wrong with the following code ?
class A
{
void x()
{
Thread.sleep(20);
}
void m()
{
x();
}
}
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac EHA.java
EHA.java:5: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown

Thread.sleep(20);
^
1 error
riddhi@debian7:~/CoreJava$
*/
/*
The Above Code cause Compilation Error " called method has exception specification and there by passed on exception
handling duty to its caller.Method m() is caller of X() method as per throws cluse of x() method, m() should handle the
exceptions by placing x() in block. We can fix the compilation error in two ways........
1.)By placing X() method call in method in try block and writing corresponding catch block.
2.)By writing exception specification to main();
Q.128) What is wrong with the following code ?
class C
{
void x()
{
int a=10;
int b=0;
int c=a/b;
}
void m()
{
x();
}
}//C
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac EHC.java
riddhi@debian7:~/CoreJava$
No compilation Error comes while m(); is calling x();
In the caller method throws clause in unreachable exception is specified , caller need not handle that ***try** type of
exception. It is Aplicable to only check Exceptions.
Q.129)
class D
{
void x() throws InterruptedException
{
Thread.sleep(10);
}
void m()
{
}
}
class E extends D
{
void m() throws InterruptedException
{
x();
}
}
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac EHD.java
EHD.java:20: m() in E cannot override m() in D; overridden method does not throw java.lang.InterruptedException
void m() throws InterruptedException
^
1 error
riddhi@debian7:~/CoreJava$
*/

In class E, m() is a overRiding method . It is invoking x() that may through a checked exception. we can not futher
pass on that exception in m(). using exception specification as it violates the OverRiding Rule.
i.e. Error of OverRiding Rule.
Note :- throw is used to pass on the (created) exception to the higher level. where as throws is used to pass on exception
handling duty to higher level.
within the method if check exception is thrown explicitely to the callers. is has to be announced (throw)also
i.e. both throw and throws must be used in that method.
Q.130) What are the things to be consider of a method in order to invoke it ?
Before calling a java method, one has to be know the following things about that method.
1.)fully qualified Name of the class or interface to which it belongs.
2.)Signature of the method.
3.)whether it is static or instance method
4.)return type
5.)accesibility mode
6.)ExceptionSpecification of the method. (throws clause).
Q.131) What are the user-define exception ?
Application specific exceptions that are developed by the application deceloper are nothing but user-define exceptions.
or
our own created exceptions are know as user define exceptions.
A user define java class is eligible to act as an exception class if and only if it is Throwable.
i.e. it has to extends a built-in exception class.
Mostely
java.lang.Exception;
or
java.lang.RuntimeException;
for eg.
package com.durgasoft.exception;
public class A extends Exception
{
}
JVM can raise Exception only when the java runtime rules are violated.
To represent application specific abnormality when the sutuation is violating the business rules of the enterprise , we go
for user define Exception.
To propogate exception from one part(layer) of the application to the other part in techonology or framework independent
manner we use user-define Exceptions in order to pramote loose coupling.
Q.132) VotingApplication.java
class VotingException extends Exception
{
VotingException(String msg)
{
super(msg);
}
}
class Voting
{
static void isEligibleToVote(int age)throws VotingException
{
if(age<19)
throw new VotingException("Not Eligible to Vote");
System.out.println("Eligible to Vote");
}
}
class VotingApplication
{
public static void main(String args[])
{
int age=Integer.parseInt(args[0]);
try
{
Voting.isEligibleToVote(age);

}
catch(VotingException e)
{
System.out.println(/*e.getMassage()+*/"Not Eligible for Vot : User-define Exceptions");
}
}
}
OUTPUT
riddhi@debian7:~/CoreJava$ javac VotingApplication.java
riddhi@debian7:~/CoreJava$ java VotingApplication 12
Not Eligible for Vot : User-define Exceptions
riddhi@debian7:~/CoreJava$ java VotingApplication 20
Eligible to Vote
riddhi@debian7:~/CoreJava$
MultiThreading
Q.133) What are the similarities between MultiThreading and MultiTasking ?
1.) Both are meant for performing task at the same time*(concurrently)/parellaly.
2.) Both are meant for optimum utilisation of CPU resourse.
3.)Both need OS support in the area`s of time sharing/clicing and context Switching.
Q.135) What is a single Threaded application ? What are its limitations ?
If a application has a single sequential flow of control , i.e. only one thread . it is called as a single thread application.
Single Threaded application can`t perform Multiple task in parallel.
Q.136) What is Thread ?
An Independent part of execution in an application is a Thread.
OR
an single sequential flow of control in an application is called as Thread.
A Thread is a light weighted sub-process.
in a java application a thread is a object. Object Oriented representation of a single flow of control in a java application is
nothing but Thread.
Q.137) What is MultiThreaded Application ?
if an application has Multiple independent parts of execution, it is called as a MultiThreaded Application.
Whenever a single process has to perform multiple tasks (of same nature or different nature) in parallel,that application
is a right candidate to make MultiThreaded
Q.138) What is the Java Labrary Support in making java Application MultiThreaded ?
java.lang.package has provide one class and one interface to implement MultiTheading in java.
1.)Thread(class)
2.)Runable(interface)
As far as language support for MultiThreading is **concenred** , there are 2 keyword for this
1.)Syncronized
2.)Volatile
Q.139) How to make a java Application MultiThreaded ?
Step 1) Analisemthe application for the number of parallel tasks that it has to perform.
Step 2) Develop a User-Define class that extends java.lang.Thread; class or Implements java.lang.Runnable; interface.
Step 3) Implement(OverRide) method in the user defined class within that "run" method specify the task performing
code directely or indirectely.
Step 4) Create as many Thread objects as there are tasks to run in parallel.
Step 5) Active The Thread.
Q.140) Develop a MultiThreaded Java Application in which the following tasks are performed in parallel
1.)1 to 20
2.)20 to 40
*/
class ThreadOne extends Thread
{
public void run()
{
for(int i=0;i<=20;i++)
System.out.println("Thread 1 : "+i);
}//run
}//ThreadOne

class ThreadTwo extends Thread


{
public void run()
{
for(int i=20;i<=40;i++)
System.out.println("Thread 1 : "+i);
}//run
}//ThreadOne
class ThreadDemo
{
public static void main(String args[])
{
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
t1.start();t2.start();
}//main
}//ThreadDemo
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac ThreadDemo.java
riddhi@debian7:~/CoreJava$ java ThreadDemo
Thread 1 : 0
Thread 2 : 20
Thread 2 : 21
Thread 1 : 1
Thread 2 : 22
Thread 1 : 2
Thread 2 : 23
Thread 1 : 3
Thread 2 : 24
Thread 2 : 25
Thread 2 : 26
Thread 2 : 27
Thread 2 : 28
Thread 1 : 4
Thread 2 : 29
Thread 1 : 5
Thread 2 : 30
Thread 1 : 6
Thread 2 : 31
Thread 1 : 7
Thread 2 : 32
Thread 1 : 8
Thread 2 : 33
Thread 1 : 9
Thread 2 : 34
Thread 1 : 10
Thread 2 : 35
Thread 1 : 11
Thread 2 : 36
Thread 1 : 12
Thread 2 : 37
Thread 1 : 13
Thread 2 : 38
Thread 1 : 14
Thread 2 : 39
Thread 1 : 15
Thread 2 : 40
Thread 1 : 16
Thread 1 : 17

Thread 1 : 18
Thread 1 : 19
Thread 1 : 20
riddhi@debian7:~/CoreJava$
Q.141) Modife : Developed a MultiThreaded Java Application in which the following tasks are performed in parallel
1.)1 to 20
2.)20 to 40
*/
class MyThread extends Thread
{
public void run()
{
String tname = getName();
if(tname.equals("one"))
for(int i=0;i<20;i++)
System.out.println("Thread 1 :"+i);
else
for(int i=20;i<40;i++)
System.out.println("Thread 2 :"+i);
}//run
}//ThreadOne
class ThreadDemo1
{
public static void main(String args[])
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.setName("one");t2.setName("two");
t1.start();t2.start();
}//main
}//ThreadDemo1
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac ThreadDemo1.java
riddhi@debian7:~/CoreJava$ java ThreadDemo1
Thread 1 :0
Thread 2 :20
Thread 1 :1
Thread 2 :21
Thread 1 :2
Thread 2 :22
Thread 1 colonthree emoticon
Thread 2 :23
Thread 1 :4
Thread 2 :24
Thread 1 :5
Thread 2 :25
Thread 1 :6
Thread 2 :26
Thread 1 :7
Thread 2 :27
Thread 1 :8
Thread 2 :28
Thread 1 :9
Thread 2 :29
Thread 1 :10
Thread 2 :30
Thread 1 :11
Thread 2 :31
Thread 1 :12

Thread 2 :32
Thread 1 :13
Thread 2 :33
Thread 1 :14
Thread 2 :34
Thread 1 :15
Thread 2 :35
Thread 1 :16
Thread 2 :36
Thread 1 :17
Thread 2 :37
Thread 1 :18
Thread 2 :38
Thread 1 :19
Thread 2 :39
riddhi@debian7:~/CoreJava$
Q.142) Modife : Developed a MultiThreaded Java Application in which the following tasks are performed in parallel
1.)1 to 20
2.)20 to 40
How to supply already created object to already created Thread(run)
*/
class MyThread extends Thread
{
PrintingNumber p;
MyThread(PrintingNumber p)
{
this.p=p;
}
public void run()
{
String tname=getName();
if(tname.equals("one"))
p.printOneToTwenty();
else
p.printTwentyOneToFourty();
}
}//MyThread
class PrintingNumber
{
void printOneToTwenty()
{
for(int i=0;i<20;i++)
System.out.println("Thread 1 "+i);
}
void printTwentyOneToFourty()
{
for(int i=20;i<40;i++)
System.out.println("Thread 2 "+i);
}
}//PrintingNumber
class PrintingNumberApplication
{
public static void main(String args[])
{
PrintingNumber p = new PrintingNumber();
MyThread t1=new MyThread(p);
MyThread t2=new MyThread(p);
t1.setName("one");
t2.setName("two");

t1.start();t2.start();
}//main
}//class PrintingNumberApplication
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac PrintingNumberApplication.java
riddhi@debian7:~/CoreJava$ java PrintingNumberApplication
Thread 1 0
Thread 2 20
Thread 1 1
Thread 2 21
Thread 1 2
Thread 2 22
Thread 1 3
Thread 1 4
Thread 2 23
Thread 1 5
Thread 2 24
Thread 1 6
Thread 2 25
Thread 1 7
Thread 2 26
Thread 1 8
Thread 2 27
Thread 1 9
Thread 2 28
Thread 1 10
Thread 2 29
Thread 1 11
Thread 2 30
Thread 1 12
Thread 2 31
Thread 1 13
Thread 2 32
Thread 1 14
Thread 2 33
Thread 1 15
Thread 2 34
Thread 1 16
Thread 2 35
Thread 1 17
Thread 2 36
Thread 1 18
Thread 2 37
Thread 1 19
Thread 2 38
Thread 2 39
riddhi@debian7:~/CoreJava$
Q.143) Modify the above application so as make use of java.lang.Runnable interface to make the application
multithreaded ?
Note :- When user define thread class is implementing Runnable interface , create the Thread Object , not by instantiating
the userdefine thread class by instantiating java.lang.Thread class.
In Thread Object creation system we should make use of java.lang.Thread class constructor that takes runnable interface
Object as argument.
*/
class MyThread implements Runnable
{
PrintingNumber p;
MyThread(PrintingNumber p)
{

this.p=p;
}
public void run()
{
String tname = Thread.currentThread().getName();
if(tname.equals("one"))
p.printOneToTwenty();
else
p.printTwentyOneToFourty();
}
public static void main(String args[])
{
PrintingNumber p = new PrintingNumber();
Thread t1=new Thread(new MyThread(p));
Thread t2=new Thread(new MyThread(p));
t1.setName("one");
t2.setName("two");
t1.start();t2.start();
}//main
}//MyThread
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac PrintingNumberApplicationWithRunnable.java
riddhi@debian7:~/CoreJava$ java MyThread
Thread 2 20
Thread 2 21
Thread 2 22
Thread 2 23
Thread 2 24
Thread 2 25
Thread 2 26
Thread 2 27
Thread 2 28
Thread 2 29
Thread 1 0
Thread 2 30
Thread 1 1
Thread 2 31
Thread 1 2
Thread 2 32
Thread 1 3
Thread 2 33
Thread 1 4
Thread 2 34
Thread 1 5
Thread 2 35
Thread 1 6
Thread 2 36
Thread 1 7
Thread 2 37
Thread 1 8
Thread 2 38
Thread 1 9
Thread 2 39
Thread 1 10
Thread 1 11
Thread 1 12
Thread 1 13
Thread 1 14
Thread 1 15

Thread 1 16
Thread 1 17
Thread 1 18
Thread 1 19
riddhi@debian7:~/CoreJava$
*/
class PrintingNumber
{
void printOneToTwenty()
{
for(int i=0;i<20;i++)
System.out.println("Thread 1 "+i);
}
void printTwentyOneToFourty()
{
for(int i=20;i<40;i++)
System.out.println("Thread 2 "+i);
}
}//PrintingNumber
Q.145) What is Thread Priority ?
Thread priority is a number used by Thread Schedular to allocate CPU resourses to a Thread in preference to other active
Thread.
Thread Priority rrange is 1 to 10.
1 lowes , 10 hieghtes
3 Constant Variables in Thread Class
1.) NORM_PRIORITY(5)
2.) MAX_PRIORITY(10)
3.) MIN_PRIORITY(1)
public static class Thread implements Runnable
{
public static final int NORM_PRIORITY=5;
public static final int MAX_PRIORITY=10;
public static final int MIN_PRIORITY=1;
}//class Thread
By calling setPriority() method on the current object priority is set. Priority
setting is useless if it is done after the Thread is activated. By default main
Thread will have a priority of 5. therefore its child Threads will also have same
PRIORITY.
Q.146) Application For Test Priority ?
class MyThread extends Thread
{
public void run()
{
Thread T2=new Thread();//child of T1
System.out.println("Priority of "+T2.getName()+" Thread "+T2.getPriority()+"\tDefault Priority=Parent Priority");
}
}//MyThread
class PriorityApplication
{
public static void main(String args[])
{
System.out.println("Priority of "+Thread.currentThread().getName()+" Thread "+Thread.currentThread().getPriority());
MyThread T1=new MyThread();
System.out.println("Priority of "+T1.getName()+" Thread "+T1.getPriority()+"\tDefault Priority=Parent Priority");
T1.setPriority(8);
System.out.println("Priority of "+T1.getName()+" Thread "+T1.getPriority());
T1.start();
}//main

}//PriorityApplcation
OUTPUT
iddhi@debian7:~/CoreJava$ javac PriorityApplication.java
riddhi@debian7:~/CoreJava$ java PriorityApplication
Priority of main Thread 5
Priority of Thread-0 Thread 5 Default Priority=Parent Priority
Priority of Thread-0 Thread 8
Priority of Thread-1 Thread 8 Default Priority=Parent Priority
riddhi@debian7:~/CoreJava$
Q.147) What are the Daemon Threads ?
A Thread is said to be a Daemon thread if it dies as soon as its parent`s dies. A Thread is said to be a user thread if it
doesn`t dies ecen after its parent`s death. Daemon thread are service threads in general and run in the background.
Garbage collector is a classic example of daemon thread. We can make a Thread to be Daemon Thread by invoking
setDaemon() method onit.
For eg.
t.setDaemon();
Main and Garbage Collector are Daemon Threads.
Q.148) Develop a multithreaded account application that facilated 2 concurrent WithDraw ?
ParallelWithDraw.java
class Account
{
int accno;
float balance;
// Account(){}
Account(int accno,int balance)
{
this.accno=accno;
this.balance=balance;
}
float getBalance()
{
return balance;
}
void setBalance(float balance)
{
this.balance=balance;
}
void withdraw(float amount)
{
System.out.println("Try to WithDraw From Account no. "+accno);
// System.out.println("Try to getBalance From Account no. "+accno);
float bal=getBalance();
System.out.println("Balance in Account no. "+accno+" is Rs. "+bal);//getBalance());
if(bal>amount)
{
bal=bal-amount;
setBalance(bal);
System.out.println("Please collect your Cash of Rs. "+amount);
}
else
{
System.out.println("Insufficient Balance at Account no."+accno);
}
}
}//Account
class AccountThread extends Thread
{
Account acc;
float amount;
AccountThread(Account acc,float amount)

{
this.acc=acc;
this.amount=amount;
}
public void run()
{
acc.withdraw(amount);
}
}//AccountThread
class ParallelWithdrawApplication //throws InterruptedException
{
public static void main(String args[])
{
Account acc1=new Account(1,10000);
Account acc2=new Account(2,14000);
AccountThread T1=new AccountThread(acc1,5000);
AccountThread T2=new AccountThread(acc2,7000);
T1.start();
T2.start();
try{T1.join();
T2.join();
}catch(Exception e){}
System.out.println("Final Balance is Rs. "+acc1.getBalance());
System.out.println("Final Balance is Rs. "+acc2.getBalance());
}//main
}//ParallelWithdrawApplication
/*
OUTPUT
riddhi@debian7:~/CoreJava$ javac ParallelWithdrawApplication.java
riddhi@debian7:~/CoreJava$ java ParallelWithdrawApplication
Try to WithDraw From Account no. 2
Try to WithDraw From Account no. 1
Balance in Account no. 2 is Rs. 14000.0
Balance in Account no. 1 is Rs. 10000.0
Please collect your Cash of Rs. 7000.0
Please collect your Cash of Rs. 5000.0
Final Balance is Rs. 5000.0
Final Balance is Rs. 7000.0
riddhi@debian7:~/CoreJava$
*/
Note :T1 and T2 Thread are not blocked here the how in which , the flow in which these methods are called , that Thread (flow)
is suspended. i.e. main method is suspended until T1 and T2 are dead (because main method is comes in flow in main
thread)
Q.149) Explain about Syncronization in that context of multiThreaded Application ?
To make multiThreaded Application "Thread Safe" ,we go for Syncronization. i.e. To Prevent the data inconsistency
dangers caused by MultiThreading , We use Syncronization Mechanism. Wherever multiple Threads are acting upon the
same Shared resource there is A chance for data inconsistency. Syncronization is a Mechanism of following only one
Thread at a to act upon a resource whenever multiple Threads are trying to act upon the same shared resource.
"Syncronized" keyword is used to implements Syncronization.
We have 2 Type of Syncronization.
1.) Method level.
2.) Blocked level.
If "Syncronized" is apply to a method it becomes Method Level Syncronization.
For eg.
Syncronized void MethodLevel()
{
}
for eg
Syncronized void withdraw(..........){......................}

If block of statement instead of whole method is Syncronized, it is called Blocked Level Syncronization.
For eg.
public void run()
{
Syncronized(acc)
{
acc.withdraw(amount);
}
}
For eg.
public void run()
{
acc.withdraw(amount);
}
public void withdraw(int amount)
{
//code
Syncronized(this)
{
//code that caused data
}
//code
}
Note :In method level or blocked level Syncronization , Object is locked, not method. INTERNALLY Syncronized uses the OS
concept of mutex (mutually exclusive) and monitor. MONITOR is a creitical region of code that is created by OS into
which only one thread at a time can enter. Once a thread enter the monitor it acquires the lock , untill that tread release
the lock no other thread can enter the monitor. i.e. mutually exclusive lock is used.
Q.149) Explain about Syncronization in that context of multiThreaded Application ?
To make multiThreaded Application "Thread Safe" ,we go for Syncronization. i.e. To Prevent the data inconsistency
dangers caused by MultiThreading , We use Syncronization Mechanism.Wherever multiple Threads are acting upon the
same Shared resource there is A chance for data inconsistency. Syncronization is a Mechanism of following only one
Thread at a to act upon a resource whenever multiple Threads are trying to act upon the same shared resource.
"Syncronized" keyword is used to implements Syncronization. We have 2 Type of Syncronization.
1.) Method level.
2.) Blocked level.
If "Syncronized" is apply to a method it becomes Method Level Syncronization.
For eg.
Syncronized void MethodLevel()
{
}
for eg
Syncronized void withdraw(..........){......................}
If block of statement instead of whole method is Syncronized, it is called
Blocked Level Syncronization.
For eg.
public void run()
{
Syncronized(acc)
{
acc.withdraw(amount);
}
}
For eg.
public void run()
{
acc.withdraw(amount);
}
public void withdraw(int amount)
{

//code
Syncronized(this)
{
//code that caused data
}
//code
}
Note :In method level or blocked level Syncronization , Object is locked, not method. INTERNALLY Syncronized uses the OS
concept of mutex (mutually exclusive) and monitor. MONITOR is a creitical region of code that is created by OS into
which only one thread at a time can enter. Once a thread enter the monitor it acquires the lock , untill that tread release
the lock no other thread can enter the monitor. i.e. mutually exclusive lock is used.
Q.134) What are the difference between MultiThreading and MultiTasking ?
1) In case of MultiTasking n process are required to to perform 'n' task in parallel. i.e. MultiTasking is a process based
multiple Concurrent task performing mechanism.
In case of MultiThreading , 1 process is sufficient to perform Multiple Tasks in parallel each sub-process(THREAD) of
that single process performs one task. i.e. MultiThreading is a Thread based Multiple concurrent task performing
Mechanism.
2) Java Application has no role to play in the implementation of MultiTasking.Where as , performing efforts is required
to achive Thread Based MultiTasking. Note :- Thread is light Weighted where as Process is Heavy Weighted.
Weight in terms of Overhead Invoked in Context Switching.
What is language?
A way of communication is known as language. e.g. Hindi, English etc.
What is a Program?
A set of instructions which is used to perform a specific task.
What is a Programming Language?
An artificial language used to write programs which can be translated into machine language and executed by computer
with the help of some special software.
What is a Platform?
Dictionary meaning: A raised level surface on which things can stand.
In programming: Hardware or software on which a program can execute/run.
e.g. c, c++, Java etc.
overview of java
What is Java?
Java is a high level programming language and also known as platform because of its JRE (java runtime environment).
Brief History of Java.
Java language project initially started in June 1991 by James Gosling, Mike Sheridan, and Patrick Naughton. An oak tree
stood outside Goslings office at that time and java named as oak initially. It later renamed as Green and was later
renamed as java from java coffee.
Base concept of java language project.
Write once, run anywhere (WORA) that means java program can run anywhere and on any platform. When java code is
compiled it is converted into byte code. Now only this byte code is needed to run using JVM, no need of source code and
recompilation.
Java released versions:
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)
java features
Why java is used?
Java is used because of following features.
Java features:
1. Simple, easy and familiar:

Java is easy to learn and familiar because java syntax is just like c++.
It is simple because:
a) it does not use header files.
b) eliminated the use of pointer and operator overloading.
2. Platform Independent:
Write once, run anywhere (WORA).

3.Object-Oriented:
Java is Object oriented throughout language- that mean no coding outside of
class definitions, including main().
4. Robust:
Robust means inbuilt capabilities to handle errors/exceptions.
Java is robust because of following:
1. Built-in Exception handling.
2. Strong type checking i.e. all data must be declared an explicit type.
3. Local variables must be initialized.
4. Automatic garbage collection.
5. First checks the reliability of the code before Execution etc.
5. Secure:
Java is secure because it provides:
1. access restrictions with the help of access modifiers (public, private etc).
2. byte codes verification checks classes after loading.
Class loader confines objects to unique namespaces.
Security manager determines what resources a class can access such as reading and writing to the local disk.
6. Distributed:
Java provides the network facility. i.e. programs can be access remotely from any machine on the network rather than
writing program on the local machine. HTTP and FTP protocols are developed in java.
7. Compiled and interpreted:
Java code is translated into byte code after compilation and the byte code is interpreted by JVM (Java Virtual Machine).
This two steps process allows for extensive code checking and also increase security.
8. Portable:
Means able to be easily carried or moved. Write once, run anywhere (WORA) feature makes it portable.
9. Architecture-Neutral:
Java code is translated into byte code after compilation which is independent of any computer architecture, it needs only
JVM (Java Virtual Machine) to execute.
10. High performance:

JVM can execute byte codes (highly optimized) very fast with the help of Just in time (JIT) compilation technique.
11. Re-usability of code:
Java provides the code reusability With the Help of Inheritance.
12. Multithreading:
Java provides multitasking facility with the help of lightweight processes called threads.
13. Dynamic:
Java have the capability of linking dynamic new classes, methods and objects.
jvm (Java Virtual Machine)
What is JVM?
JVM is a virtual machine or a program that provides run-time environment in which java byte code can be executed.
JVMs are available for many hardware and software platforms. The use of the same byte code for all JVMs on all
platforms make java platform independent.
JVM diagram:

JVM details:
1. Class loader subsystem:
It is a part of JVM that care of finding and loading of class files.
2. Class/method area:
It is a part of JVM that contains the information of types/classes loaded by class loader. It also contain the static variable,
method body etc.
3. Heap:
It is a part of JVM that contains object. When a new object is created, memory is allocated to the object from the heap
and object is no longer referenced memory is reclaimed by garbage collector.

4. Java Stack:
It is a part of JVM that contains local variable, operands and frames. To perform an operation, Byte code instructions
takes operands from the stack, operate and then return the result in to the java stack.
5. Program Counter:
For each thread JVM instance provide a separate program counter (PC) or pc register which contains the address of
currently executed instruction.
6. Native method stack:
As java program can call native methods (A method written in other language like c). Native method stack contains
these native methods.
7. Execution Engine:
It is a part JVM that uses Virtual processor (for execution), interpreter (for reading instructions) and JIT (Just in time)
compiler (for performance improvement) to execute the instructions.

How JVM is created (Why JVM is virtual):


When JRE installed on your machine, you got all required code to create JVM. JVM is created when you run a java
program, e.g. If you create a java program named FirstJavaProgram.java. To compile use java FirstJavaProgram.java
and to execute use java FirstJavaProgram. When you run second command java FirstJavaProgram, JVM is created.
Thats why it is virtual.
Lifetime of JVM:
When an application starts, a runtime instance is created. When application ends, runtime environment destroyed. If n no.
of applications starts on one machine then n no. of runtime instances are created and every application run on its own
JVM instance.
Main task of JVM:
1. Search and locate the required files.
2. Convert byte code into executable code.
3. Allocate the memory into ram
4. Execute the code.
5. Delete the executable code.
Difference between JVM, JRE and JDK
JVM (Java Virtual Machine):
JVM is a virtual machine or a program that provides run-time environment in which java byte code can be executed.
JVMs are available for many hardware and software platforms. The use of the same byte code for all JVMs on all
platforms make java platform independent.
Main task of JVM:
1. Search and locate the required files.
2. Convert byte code into executable code.
3. Allocate the memory into ram
4. Execute the code.
5. Delete the executable code.
JRE (Java RunTime Environment):
JVM + java runtime libraries + java package classes (e.g. util, lang etc). JRE provides class libraries and other supporting
files with JVM. It not provide any development tool like compiler, debugger etc.

JDK (Java Development Kit):


JRE+ development tool (compiler, debugger etc.). JDK contains tools to develop the application and JRE to execute the
application.

Java Coding Guidelines


1. Basic Naming convention standards:
To describe variable/constant/method/class/interface etc use full descriptor. E.g.: rollNumber, firstName, lastName,
getTotalMarks().
2. Naming variable:
Use first word in small letters and all remaining words will be capitalized. E.g. rollNumber, firstName.
3. Naming Constants:
Use all letters in upper case. E.g. MAX_MARKS.
4. Naming methods:
a). Naming member methods :
Use first word in small letters and all remaining words will be capitalized. E.g. getTotalMarks().
b). Naming accessor methods:
for getters use get as prefix to property (for non Boolean properties). e.g. getRollNumber().
for setters use set as prefix to property. e.g. setRollNumber().
use is as prefix to property(for Boolean properties). e.g. isNewStudent().
5. Naming class/interface:
Use capitalized words for class/interface name. E.g.- HelloWorld.
6. Comment:
For clarity of the code add comments.
Some important definitions for java programs
1. Operand :
Arguments on which operation is performed are known as operand.

2. Operator:
Operator is a special symbol used for performing a specific task. e.g. A+B. Here + symbol represents the operator.

3. Expression:
A sequence of operands connected by operators is known as expression. e.g. A+B*5.
variable and datatypes in java

Variable:
Variable is the name of reserved memory location. It means when we declare a variable some part of memory is reserved.
e.g. int var1 = 35;
var1 is a variable here.
Variable Types:

Local variable:
A variable that is declared within the method, constructor, or block is known as local variable.
No Access modifier is used for local variables. Scope of local variable is limited to that method, constructor, or block
only in which it declared.
Instance variable:
A variable that is declared within the class but outside of method, constructor, or block is known as instance variable
(Non static). They are associated with object. Access modifiers can be used with instance variables. Inside class you can
access instance variable direct by variable name without any object reference.
Static variable:
A variable that is declared within the class with static keyword but outside of method, constructor, or block is known as
Static/class variable. They are associated with class. Static variable are accessed by ClassName.VariableName.
Data types:
As we discussed when a variable is declared some part of memory is reserved. But how much memory will be reserved.
It depends upon the data type of the variable. i.e. how much memory will be reserved and which type of data can be
stored in reserved memory is depends upon data type of the variable.
Data types in java:

1. Primitive data types:


Primitive data types are predefined in the language.

2. Referenced or object data types:


Any class object or array type. Default value of object data types is null.
Note:
1. Compiler never initialize local variable with default values. So you have to initialize local variable before using
otherwise it will result in compile-time error.
2. Char in java takes 2 bytes because java uses Unicode system (UTF-16) which needed a minimum of 2 bytes
memory to store a character.

Hello world java program


As we have discussed all required detail to develop and execute a java program. Let us start java programming with first
simple java program to print Hello World.

Create Hello world java program:


HelloWorld.java

/**
* This program is used to print "Hello World".
* @author javawithease
*/
public class HelloWorld {
public static void main(String args[]){
//This line will print "Hello World".
System.out.println("Hello World.");
}
}
Output:
Hello World.
Download this example.
To understand above java program better let us have a brief look on it:
1. class: is a keyword used to declare a class with specific name.
2. public: is an access modifier.
3. static: is a keyword which can be used with class, method, variable/constant , block. If it is used with a method that
method is known as static method. For static method invocation no need for object creation , method will be associate
with class.
4. void : return type of the method , void means it does not return any value.
5. main : method is invoked by JVM, as it is static no need to create an object. It represent the programs startup.
6. String args[] : represents the array of String type which is used in command line arguments.
7. System.out.println():
1. System is a final class and its all members are static.
2. out is a public final static member of System class. out is of PrintStream type.
3. println() is the method of PrintStream class.
Important Java Programs
Program to print alphabets both in small and capital.
/**
* This program is used to print alphabets both in small and capital.
* @author javawithease
*/
public class Alphabets {
public static void main(String args[]){
char ch;
System.out.println("Small Alphabets: ");
for( ch = 'a' ; ch <= 'z' ; ch++ ){
System.out.println(ch);

}
System.out.println("Capital Alphabets: ");
for( ch = 'A' ; ch <= 'Z' ; ch++ ){
System.out.println(ch);
}
}
}
Output:
Small Alphabets:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
Capital Alphabets:
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S

T
U
V
W
X
Y
Z
Download this example.

Program to perform arithmetic operations.


/**
* This program is used to perform arithmetic operations.
* @author javawithease
*/
public class ArithmeticOperations {
/**
* This method is used to add two numbers.
* @param num1
* @param num2
*/
static void addition(int num1, int num2){
System.out.print("Addition of given numbers = ");
System.out.println(num1 + num2);
}
/**
* This method is used to subtract two numbers.
* @param num1
* @param num2
*/
static void subtraction(int num1, int num2){
System.out.print("Subtraction of given numbers = ");
System.out.println(num1 - num2);
}
/**
* This method is used to multiply two numbers.
* @param num1
* @param num2
*/
static void multiplication(int num1, int num2){
System.out.print("Multiplication of given no.s = ");
System.out.println(num1 * num2);
}
/**
* This method is used to divide two numbers.
* @param num1
* @param num2
*/
static void division(int num1, int num2){
System.out.print("Division of given given no.s = ");
System.out.println(num1 / num2);
}

/**
* This method is used to modulo divide two numbers.
* @param num1
* @param num2
*/
static void moduloDivision(int num1, int num2){
System.out.print("ModuloDivision of given no.s = ");
System.out.println(num1 % num2);
}
public static void main(String args[]){
//method call from main method
addition(20, 10);
subtraction(40, 30);
multiplication(20, 30);
division(20, 4);
moduloDivision(20, 3);
}
}
Output:
Addition of given numbers = 30
Subtraction of given numbers = 10
Multiplication of given numbers = 600
Division of given given numbers = 5
ModuloDivision of given numbers = 2
Download this example.
Program to find that given number is Armstrong or not.
/**
* This program is used to find that given number is Armstrong or not.
* @author javawithease
*/
public class ArmstrongNumber {
/**
*This method is used to find that given number is Armstrong or not
*@param num
*/
static void armstrong(int num){
int newNum = 0, reminder, temp;
temp = num;
//find sum of all digit's cube of the number.
while(temp != 0){
reminder = temp % 10;
newNum = newNum + reminder*reminder*reminder;
temp = temp/10;
}
//Check if sum of all digit's cube of the number is
//equal to the given number or not.
if(newNum == num){
System.out.println(num +" is armstrong.");
}else{
System.out.println(num +" is not armstrong.");
}

}
public static void main(String args[]){
//method call
armstrong(407);
}
}
Output:
407 is armstrong.
Download this example.
Program to check that given number is even or odd.
/**
* This program is used to check that given number is even or odd.
* @author javawithease
*/
public class EvenOrOdd {
/**
* This method is used to check that given no is even or odd.
* @param num
*/
static void evenOdd(int num){
if(num % 2 == 0){
System.out.println("Given number is even.");
}else{
System.out.println("Given number is odd.");
}
}
public static void main(String args[]){
//method call, no need of object.
evenOdd(123);
}
}
Output:
Given number is odd.
Download this example.
Program to calculate Factorial of given number.
/**
* This program is used to calculate Factorial of given number.
* @author javawithease
*/
public class Factorial {
/**
* This method is used to calculate Factorial of given no.
* @param num
*/

static void factorialNumber(int num){


int fact = 1;
//Factorial of 0 and 1 is 1.
if(num == 0 || num == 1){
System.out.println("factorial of " + num + " is 1.");
}
//for calculating factorial, number should be non negative.
if(num > 0){
//calculate factorial.
for(int i = 2; i <= num; i++){
fact = fact*i;
}
System.out.println("factorial of " + num + " is " +fact);
}else{
System.out.println("no. should be non negative.");
}
}
public static void main(String args[]){
//method call
factorialNumber(5);
}
}
Output:
factorial of 5 is 120
Download this example.
Program to find factorial of given number by recursion.
/**
* This program is used to find factorial of given number by recursion.
* @author javawithease
*/
public class FactorialByRecursion {
/**
* This method is used to find factorial of given no. by recursion.
* @param num
* @return int
*/
static int fact(int num){
//Factorial of 0 is 1.
if (num == 0)
return 1;
else
return num * fact(num-1);
}
public static void main(String args[]){
int num = 5, factorial;
//method call
if(num > 0){
factorial = fact(num);
System.out.println("Factorial of "+num+" is "+ factorial);

}else{
System.out.println("Number should be non negative.");
}
}
}
Output:
Factorial of 5 is 120
Download this example.
Program to print fibonacci series.
/**
* This program is used to print fibonacci series.
* @author javawithease
*/
public class FibonacciSeries {
/**
* This method is used to print fibonacci series.
* @param num
*/
static void fibonacci(int num){
int f1, f2=0, f3=1;
for(int i=1;i <=num;i++){
System.out.println(f3);
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
}
public static void main(String args[]){
int num = 6;
//method call
if(num > 0){
fibonacci(num);
}else{
System.out.println("No. should be greater than zero.");
}
}
}
Output:
1
1
2
3
5
8
Download this example.

Program to find that given number is Palindrome or not.


/**
* This program is used to find that given number is Palindrome or not.
* @author javawithease
*/
public class PalindromeNumber {
static void palindrome(int num){
int newNum = 0, reminder, temp;
temp = num;
//find sum of all digit's of the number.
while(temp != 0){
reminder = temp % 10;
newNum = newNum*10 + reminder;
temp = temp/10;
}
//Check if sum of all digit's of the number
//is equal to the given number or not.
if(newNum == num){
System.out.println(num +" is palindrome.");
}else{
System.out.println(num +" is not palindrome.");
}
}
public static void main(String args[]){
//method call
palindrome(12321);
}
}
Output:
12321 is palindrome.
Download this example.
Program to find that given number is prime or not.
/**
* This program is used to find that given number is prime or not.
* @author javawithease
*/
public class PrimeNumber {
/**
* This method is used to find that given number is prime or not.
* @param num
*/
static void primeNumber(int num){
int count = 0;
//0 and 1 are not prime numbers.
if(num == 0 || num == 1){
System.out.println(num + " is not prime.");
}else{
for(int i = 1; i <= num/2; i++){
if(num % i == 0){
count++;

}
}
if(count > 1){
System.out.println(num + " is not prime.");
}else{
System.out.println(num + " is prime.");
}
}
}
public static void main(String args[]){
//method call
primeNumber(37);
}
}
Output:
37 is prime.
Download this example.
Program to swap two numbers without using third or temp variable.
/**
* This program is used to swap two numbers without using third variable.
* @author javawithease
*/
public class SwapNumbers {
/**
* This method is used to swap no.s without using third variable.
* @param num1
* @param num2
*/
static void swapNumbers(int num1, int num2){
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("After swapping: "+ num1 + " and " + num2);
}
public static void main(String args[]){
int num1 = 20;
int num2 = 30;
System.out.println("Before swapping:"+ num1 + " and " + num2);
//method call
swapNumbers(num1, num2);
}
}
Output:
Before swapping no.s are : 20 and 30
After swapping no.s are : 30 and 20

Download this example.

How to set permanent path in java?


1. Right click on my computer. Click on properties.

2. Click on advanced system settings.

3. Click on Environment Variables.

4. Click on new.

5. Copy the java path up to bin folder.

6. Paste this path in variable value and write path in variable name. Click ok.

7. Click ok.

8. Click ok.

Now permanent java path is set on your machine.


Object-oriented programming style
OOPs is a style of computer programming which represents concepts as objects that have state and behavior. e.g.
objective-c, c#, Java.
Difference between Object Oriented Programming and Procedural Programming.
Procedural Programming
Object Oriented Programming
1. In Procedural Programming a program is created step
1. In Object Oriented Programming a program is
by step instructional format and instructions are executed
created in a way as real world works.
in order.
2. Follow bottom to top approach.
2. Follow top down approach.
3. Secure because it have proper way of data
3. Less secure because it does not have any proper way
hiding.
of data hiding.
4. Provide code reusability feature.
4. Does not provide code re-usability feature.
5. Provide ability to simulate real-world event
5. Doesnt provide ability to simulate real-world event
much more effectively.
much more effectively.
6. Fast Development.
6. Slow development.
Difference between Object Oriented and Object based language.
Object oriented language
Object based language
1. Doesnt support all the features of OOPs (like
1. Supports all the features of OOPs.
Inheritance, polymorphism).
2. Doesnt have in-built object.
2. Has in-built object (like window object in
3. E.g. C#, Java etc.
JavaScript).
3. E.g. JavaScript, VB etc.

Object and Class in Java


Before discussing OOPs concept let us have a brief look at object and class with real world examples.
Object in Real world:
A real world entity. Every real world object/entity has two characteristics state and behavior. Let us take the example of
a car. Its state is defined by color, current speed etc and behavior is defined by changing speed, applying breaks etc.
Object in programming:
Like every real world object, software objects also have state and behavior. State of the object is represented by data
members or fields and behavior is represented by methods.

Class in Real world:


Let us take the example of cars. There are thousands of cars in existence but all built from the same set of blueprints and
therefore contains the same components. In other words your car is an instance (object) and cars is the blueprint (class of
objects).
Class in programming:
Class is act as a blue print or template for creating objects. It provides state and behavior for its objects. Java is a pure
object oriented language means everything we discuss in java is an object.
Syntax:
access_modifier class class_name{

//body of the class

Java class has mainly two type of access level:


Default: class objects are accessible only inside the package.
Public: class objects are accessible in code in any package.
Note: If no access modifier used it is taken as default.
Example:
/**
* This class is used add and show car details.
* @author javawithease

*/
public class Car {
String carColor;
int carSpeed;
/**
* This method is used to add car details.
* @param color
* @param speed
* @author javawithease
*/
void addCarDetails(String color, int speed){
carColor = color;
carSpeed = speed;
}
/**
* This method is used to show details.
* @author javawithease
*/
void showCarDetails(){
System.out.println("Color: " + carColor);
System.out.println("Speed: " + carSpeed);
}
public static void main(String args[]){
//creating objects
Car car1 = new Car();
Car car2 = new Car();
//method call, need object here
//because method is non-static.
car1.addCarDetails("white", 120);
car2.addCarDetails("Red", 150);
car1.showCarDetails();
car2.showCarDetails();
}
}
Output:
Color: white
Speed: 120
Color: Red
Speed: 150
Download this example.

1.
2.
3.
4.

OOPs concepts in java


OOPs principles are as follows:
1. Abstraction.
2. Encapsulation.
3. Polymorphism.
4. Inheritance.
1. Abstraction:
Abstraction is a way of hiding complexity. Let us take the example of a car. We know that if accelerator pressed, speed
will increase but dont know the internal process how speed will be increased.
2. Encapsulation:

Encapsulation is a process of wrapping code and data into a single unit. Let us take an example of a HR in a company.
We communicate through HR not directly with the departments. HR is acting as a public interface here.
3. Polymorphism:
Polymorphism means more than one forms. In java polymorphism is a way in which something behaves differently based
on its call. Water can be of in any form solid, liquid or gas.
4. Inheritance:
Inheritance is the way of re-usability of code. Let us take the example of parent and child. A child inherits the properties
of its parent.
Abstraction in java
Abstraction in real world:
Abstract is a way of hiding complexity. Let us take the example of a car. We know that if accelerator pressed, speed will
increase but dont know the internal process how speed will be increased.
Abstraction in programming:
Abstract way to show essential details (what) to the user and hide non-essential details (how). Let us take a simple
example:
num = num1*num2;
In the above example we multiply two numbers and store result into new variable. But what is happening behind the
sense? There are so many things like registers, program counter (PC) etc are involved. Numbers of operations like
PUSH, POP etc are happening. But these operations are hiding by high level languages we are using for programming.
Abstraction in java is achieved with the help of abstract class and interface. We will discuss later about abstract class and
interface.

Advantages/Benefits of Abstraction:
1. Only show essential details to end user.
2. Hide complexity.
Difference between abstraction and encapsulation:
Encapsulation
1. Encapsulation is a concept for wrapping of data and
code into a single unit.
2. Encapsulation is a way of data hiding.
3. Encapsulation is achieved by access modifiers and
classes.

Abstraction
1. Abstraction is a way to show only essential
details to user.
2. Abstraction is way of hiding complexity.
3. Abstraction is achieved by abstract class and
interface.

Encapsulation in java
Dictionary meaning of Encapsulation:
The condition of being enclosed.
Capsule:
Capsule refers to a small container which contains a dose of medicine.
Definition of Encapsulation:
Encapsulation is a process of wrapping code and data into a single unit.
Encapsulation in real world:

Let us take an example of a HR in a company. We communicate through HR not directly with the departments. HR is
acting as a public interface here.
Encapsulation in programming:
Encapsulation is the way of declaring the data members as private and providing access to the data members through
public methods (getter and setter methods). As private field cant be access outside the class that means data is hiding
within the class. Thats why encapsulation is also known as data hiding.
Important points:
1. Main Concept behind encapsulation is control over the data. It is achieved using class and access modifier private,
protected, public. Class is act as a container which contains code and data.
2. Factory pattern and Singleton pattern in Java are based on the concept encapsulation.
Example:
Car.java
/**
* This class is used to set and get car properties.
* @author javawithease
*/
public class Car {
//data members
private int speed;
private String color;
//getter setters of above data members.
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
CarTest.java
/**
* This class is used to interact with Car class.
* @author javawithease
*/
public class CarTest {
public static void main(String args[]){
//create Car class object
Car car1 = new Car();

//set car details.


car1.setColor("white");
car1.setSpeed(120);
//get and print car details.
System.out.println("Car color: " + car1.getColor());
System.out.println("Car speed: " + car1.getSpeed());
}
}
Output:
Car color: white
Car speed: 120
Download this example.
Advantages/Benefits of Encapsulation:
1.
2.
3.

1. A read-only (immutable) or write-only class can be made.


2. Control over the data.
3. It helps in achieving high cohesion and low coupling in the code.
Polymorphism in java
Polymorphism in real world:
Polymorphism means more than one forms. Water can be of in any form solid, liquid or gas.
Polymorphism in programming:
In java polymorphism is a way in which something behaves differently based on its call. Let us take the example of +
operator and see the below example.
PolymorphismExample.java
/**
* This program is used to show simple example of polymorphism.
* @author javawithease
*/
public class PolymorphismExample {
public static void main(String args[]){
//+ operator add two numeric values
System.out.println(20 + 30);
//+ operator concatenate two strings.
System.out.println("hello " + "java.");
}
}
Output:
50
hello java.

Download this example.


In the above example + operator behaves differently based on type of argument. When arguments are of integer type it
acts as additional operator and when arguments are of String type it acts as concatenation operator.
Polymorphic object:
In java an object which can pass two or more IS-A test. All objects in java are polymorphic in nature because they passed
IS-A test at least for its own type and Object class type.
Types of polymorphism:
1.
2.

Static/compile time polymorphism (by method overloading).


Dynamic/run time polymorphism (by method overriding).
Method overloading in java
Method overloading is the way of implementing static/compile time polymorphism in java. Method overloading means
more than one methods in a class with same name but different parameters. Parameters can be differing in types, numbers
or order. Compiler resolve method call by matching method signature at compile time, thats why it is known as static or
compile time polymorphism. It is also known as static binding.
Ways to implement method overloading in java:

1.
2.
3.

1. Parameters differ in types.


2. Parameters differ in number.
3. Parameters differ in order.
1. Parameters differ in types.
Example:
Below example have two methods which have the same name bur method parameters are differ in their order.
AddExample.java
/**
* This class is used for method overloading
* by parameters change in their types.
* @author javawithease
*/
public class AddExample {
/**
* This method is used to add two integer values.
* @param var1
* @param var2
* @author javawithease
*/
void add(int var1, int var2){
System.out.println(var1 + var2);
}
/**
* This method is used to add one double and one integer.
* @param var1
* @param var2

* @author javawithease
*/
void add(double var1, int var2){
System.out.println(var1 + var2);
}
/**
* This method is used to concatenate two string values.
* @param var1
* @param var2
* @author javawithease
*/
void add(String var1, String var2){
System.out.println(var1 + var2);
}
public static void main(String args[]){
//creating object here
AddExample addExample = new AddExample();
//method call
addExample.add(10, 20);
addExample.add(12.50, 30);
addExample.add("hello ", "java.");
}
}
Output:
30
42.5
hello java.
Download this example.
2. Parameters differ in number.
Example:
Below example have two methods which have the same name but method parameters are differ in number.
AddExample.java
/**
* This class is used for method overloading
* by parameters change in number.
* @author javawithease
*/
public class AddExample {
/**
* This method is used to add two integer values.
* @param num1
* @param num2
* @author javawithease
*/
void add(int num1, int num2){
System.out.println(num1 + num2);
}

/**
* This method is used to add three integer values.
* @param num1
* @param num2
* @param num3
* @author javawithease
*/
void add(int num1, int num2, int num3){
System.out.println(num1 + num2 + num3);
}
public static void main(String args[]){
//creating object here
AddExample addExample = new AddExample();
//method call
addExample.add(10, 20);
addExample.add(20, 30, 40);
}
}
Output:
30
90
Download this example.
3. Parameters differ in order.
Example:
Below example have two methods which have the same name bur method parameters are differ in their order.
AddExample.java
/**
* This class is used for method overloading
* by parameters change in order.
* @author javawithease
*/
public class AddExample {
/**
* This method is used to add two numerics.
* @param num1
* @param num2
* @author javawithease
*/
void add(int num1, double num2){
System.out.println(num1 + num2);
}
/**
* This method is used to add two numerics.
* @param num1
* @param num2
* @author javawithease
*/
void add(double num1, int num2){

System.out.println(num1 + num2);
}
public static void main(String args[]){
//creating object here
AddExample addExample = new AddExample();
//method call
addExample.add(10, 20.40);
addExample.add(20.50, 30);
}
}
Output:
30.4
50.5
Download this example.
Why method overloading is not possible by changing return type of the method?
Method overloading is not possible by changing return type of the method. Because, as discussed above compiler resolve
method call by matching method signature(method name and parameters). If method signatures are same for two or more
methods then how compiler will know which method have to be called.
AmbiguityInOverloading.java
/**
* This class is used to show ambiguity problem
* in case of change in return type of the method.
* @author javawithease
*/
public class AmbiguityInOverloading {
/**
* This method is used to add two numerics.
* @param num1
* @param num2
* @return int
* @author javawithease
*/
int add(int num1, int num2){
return num1+num2;
}
/**
* This method is used to add two numerics.
* @param num1
* @param num2
* @return float
* @author javawithease
*/
float add(int num1, int num2){
return num1 + num2;
}
public static void main(String args[]){
//creating object here
AmbiguityInOverloading obj = new AmbiguityInOverloading();

//compiler can't differentiate method call


System.out.println(obj.add(10, 20));
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The method add(int, int) is undefined for the type AmbiguityInOverloading
at com.javawithease.business.AmbiguityInOverloading.main
(AmbiguityInOverloading.java:34)
Download this example.
Note: main method can also be overloaded.
MainMethodOverloding.java
/**
* This class is used for main method overloading.
* @author javawithease
*/
public class MainMethodOverloding {
//overloaded main method with one parm
public static void main(int num1){
System.out.println(num1);
}
//overloaded main method with two parm
public static void main(int num1, int num2){
System.out.println(num1 + num2);
}
public static void main(String args[]){
//method call
main(20);
main(10, 20);
}
}
Output:
20
30
Download this example.
Method overriding in java
If a subclass provides a method with the same signature (name and parameter) as in its super class, then subclass
overrides the method of its super class. This process of overriding a super class method by subclass is known as method
overriding.
Conditions for method overriding:

1.
2.

1. Method in subclass must have same signature as in its super class.


2. Two classes must follow IS-A relationship.
Example:
/**
* This program is used for simple method overriding example.
* @author javawithease
*/
class Student {
/**
* This method is used to show details of a student.
* @author javawithease
*/
public void show(){
System.out.println("Student details.");
}
}
public class CollegeStudent extends Student {
/**
* This method is used to show details of a college student.
* @author javawithease
*/
public void show(){
System.out.println("College Student details.");
}
//main method
public static void main(String args[]){
CollegeStudent obj = new CollegeStudent();
//subclass overrides super class method
//hence method of CollegeStudent class will be called.
obj.show();
}
}
Output:
College Student details.
Download this example.
Can static method be overridden?
No, Static methods cant be overridden because they are associated with class not with the object.
Role of access modifiers in method overriding:
Access modifier of overridden method in subclass cant be more restrictive than in super class. Otherwise it will throw an
exception.
Example:
/**
* This program is used for simple method overriding example.

* @author javawithease
*/
class Student {
/**
* This method is used to show details of a student.
* @author javawithease
*/
public void show(){
System.out.println("Student details.");
}
}
public class CollegeStudant extends Student {
/**
* This method is used to show details of a college student.
* @author javawithease
*/
protected void show(){//compile-time error
System.out.println("College Student details.");
}
//main method
public static void main(String args[]){
CollegeStudant obj = new CollegeStudant();
//subclass overrides super class method
//hence method of CollegeStudant class will be called.
obj.show();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Cannot reduce the visibility of the inherited method from Student
at com.javawithease.business.CollegeStudent.show(CollegeStudent.java:22)
at com.javawithease.business.CollegeStudent.main(CollegeStudent.java:30)
Download this example.
Dynamic method dispatch in java
Dynamic method dispatch is a mechanism to resolve overridden method call at run time instead of compile time. It is
based on the concept of up-casting (A super class reference variable can refer subclass object.).
Example 1:
/**
* This program is used for simple method overriding example.
* with dynamic method dispatch.
* @author javawithease
*/
class Student {
/**
* This method is used to show details of a student.
* @author javawithease
*/

public void show(){


System.out.println("Student details.");
}
}
public class CollegeStudent extends Student {
/**
* This method is used to show details of a college student.
* @author javawithease
*/
public void show(){
System.out.println("College Student details.");
}
//main method
public static void main(String args[]){
//Super class can contain subclass object.
Student obj = new CollegeStudent();
//method call resolved at runtime
obj.show();
}
}
Output:
College Student details.
School Student details.
Download this example.
Example 2:
/**
* This program is used for simple method overriding example.
* @author javawithease
*/
class Student {
/**
* This method is used to show details of a student.
* @author javawithease
*/
public void show(){
System.out.println("Student details.");
}
}
public class CollegeStudent extends Student {
/**
* This method is used to show details of a college student.
* @author javawithease
*/
public void show(){
System.out.println("College Student details.");
}
//main method
public static void main(String args[]){

//Super class can contain subclass object.


Student obj = new CollegeStudent();
//method call resolved at runtime
obj.show();
}
}
Output:
College Student details.
Download this example.
Note: Only super class methods can be overridden in subclass, data members of super class
cannot be overridden.
/**
* This program is used for simple method overriding example.
* with dynamic method dispatch.
* @author javawithease
*/
class Student {
int maxRollNo = 200;
}
class SchoolStudent extends Student{
int maxRollNo = 120;
}
class CollegeStudent extends SchoolStudent{
int maxRollNo = 100;
}
public class StudentTest {
public static void main(String args[]){
//Super class can contain subclass object.
Student obj1 = new CollegeStudent();
Student obj2 = new SchoolStudent();
//In both calls maxRollNo of super class will be printed.
System.out.println(obj1.maxRollNo);
System.out.println(obj2.maxRollNo);
}
}
Output:
200
200
Download this example.

Association in java

Association is a way of defining a relationship between classes of objects. Two classes are said to be associate with each
other if they are related with each other in some way.
Types of Association:

Important definitions for association:


Subclass/child class/ derived class:
A class which is derived from another class.
Super class/ parent class/ Base class:
A class from which subclass is derived.
Example:
Let us take the example of Student and MCAStudent. A MCAStudent is derived from Student class and can inherit the
properties from Student class. So MCAStudent is a subclass and Student is a super class here.
Note: Every class in java except object class have a super class (object class is a super class of all classes).
Inheritance in java
Inheritance is a way to implement IS-A relationship i.e. parent child relationship. Subclass inherits the subclass properties
like data member, methods. Inheritance is the way of re-usability of code. Let us take the example of parent and child. A
child inherits the properties of its parent.
Why inheritance is used?
1.
2.

1. Code re-usability.
2. Run-time polymorphism.
Syntax:
class subclass extends superclass{

//subclass code
}

Types of inheritance:

1. Single inheritance:
When a derived class inherits the properties and behavior from a single parent class. It is known as single inheritance.
Example:
/**
* This program is used for single inheritance example.
* @author javawithease
*/
class Student {
String name = "jai";
}
public class CollegeStudent extends Student {
String className = "MCA";
/**
* This method is used to show details of a student.
* @author javawithease
*/
public void showDetail(){
System.out.println("Student name = " + name);
System.out.println("Student class name = " + className);
}
public static void main(String args[]){
//creating subclass object
CollegeStudent obj = new CollegeStudent();
//method call
obj.showDetail();
}

}
Output:
Student name = jai
Student class name = MCA
Download this example.
2. Multilevel inheritance:
When a derived class inherits the properties and behavior from a derived class. It is known as multilevel inheritance.

Example:
/**
* This program is used for multilevel inheritance example.
* @author javawithease
*/
class Student {
String name = "jai";
}
class CollegeStudent extends Student {
String className = "MCA";
}
class McaStudent extends CollegeStudent{
String semester = "3rd sem.";
/**
* This method is used to show details of a student.
* @author javawithease
*/
public void showDetail(){
System.out.println("Student name = " + name);
System.out.println("Student class name = " + className);
System.out.println("Student semester = " + semester);
}
}
public class StudentTest {
public static void main(String args[]){
//creating subclass object
McaStudent obj = new McaStudent();
//method call
obj.showDetail();
}
}
Output:
Student name = jai

Student class name = MCA


Student semester = 3rd sem.
Download this example.
3. Hierarchical inheritance:
When two or more derived class inherits the properties and behavior from same parent class. It is known as hierarchical
inheritance.
Example:
/**
* This program is used for Hierarchical inheritance example.
* @author javawithease
*/
class Numbers {
int a = 10;
int b = 20;
}
class AddNumbers extends Numbers {
/**
* This method is used to add.
* @author javawithease
*/
public void showAdd(){
System.out.println(a + b);
}
}
class MultiplyNumbers extends Numbers {
/**
* This method is used to multiply.
* @author javawithease
*/
public void showMultiplication(){
System.out.println(a * b);
}
}
public class Test {
public static void main(String args[]){
//creating base classes objects
AddNumbers obj1 = new AddNumbers();
MultiplyNumbers obj2 = new MultiplyNumbers();
//method calls
obj1.showAdd();
obj2.showMultiplication();
}
}
Output:
30
200

Download this example.


Why multiple inheritance is not supported in java?
Multiple inheritance is not supported by Java because of ambiguity problem. Let us consider the below example. We
have two classes Test1 and Test2 which have same method show(). If multiple inheritance is possible than Test class can
inherit properties and behaviour of both Test1 and Test2 classes. Now Test class have two show() methods inherited from
Test1 and Test2. Problem occurs now in method call, when show() method is called with Test class object which method
will be called, of Test1 class or Test2 class. That is why multiple inheritance is not supported in java.
Example:
/**
* This is used to show that multiple inheritance
* is not supported in java in case of classes.
* @author javawithease
*/
class Test1{
public void show(){
System.out.println("show details.");
}
}
class Test2{
public void show(){
System.out.println("show details.");
}
}
//let multiple inheritance is possible.
public class Test extends Test1, Test2 {
public static void main(String args[]){
Test obj = new Test();
//Ambiguity problem in method call
//which class show() method will be called.
obj.show();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
at com.javawithease.business.Test.main(Test.java:19)
Download this example.
Aggregation in java
Aggregation is a type of HAS-A relationship. Aggregation represents a type of relationship between two objects in which
one contain the others reference. Two objects can exist independently. If one is deleted other can still exist.
Aggregation in real world:

Let us take the example: A room has a chair. Here room object contain the chair object. Both room and chair exist
independently.
Example:
/**
* This is used to show simple aggregation example.
* @author javawithease
*/
class Chair{
public void show(){
System.out.println("show chair details.");
}
}
public class RoomTest {
public static void main(String args[]){
//Chair class object in RoomTest class
Chair obj = new Chair();
obj.show();
}
}
Output:
show chair details.
Download this example.
Note: Aggregation is mainly used for code re-usability.
Command line arguments in java
Command line arguments are the arguments passed at run time to java program. Arguments are used as input for the
program. Any number of command line arguments can be passed to the program.
Command line arguments are be received by main methods string type array, so they are string by default.
Example 1:
/**
* This program is used for taking input by command line args.
* @author javawithease
*/
public class CommandLineArgument {
public static void main(String args[]){
int num1, num2;
//check whether any value is entered or not.
if (args.length > 0) {
try {
//parse string values to integer
num1 = Integer.parseInt(args[0]);
num2 = Integer.parseInt(args[1]);
System.out.println("Sum of entered numbers = ");
System.out.println(num1 + num2);

} catch (NumberFormatException e) {
//Catch exception if any in parsing.
System.err.println("Argument must be an integer.");
}
}
}
}
Output:
Sum of entered numbers = 50
Download this example.
Example 2:
/**
* This program is used for taking any number of
* input by command line args.
* @author javawithease
*/
public class CommandLineArgument {
public static void main(String args[]){
//print all entered values.
for(int i = 0; i < args.length; i++){
System.out.println(args[i]);
}
}
}
Output:
20
30
Download this example.

How to execute command line argument program in eclipse


1. Click on run in eclipse menu.

2. Click on Run Configurations

3. You will see program window. Select your program for which you are passing arguments. Then Click on
arguments tab. Enter your arguments in program arguments section.

4. Click on run button. Your program will execute.


How to read input from command line in Java using Scanner

Scanner class is used to read input from command line. Scanner class is in java.util package. Scanner class has methods
like nextInt(), nextFloat(), nextDouble() etc which read numeric data without any need of parsing using
Integer.parseInt() etc. These methods will throw an exception if you pass string or char type value.
Example:
/**
* This program is used to read input using Scanner Class.
* @author javawithease
*/
public class ReadInputUsingScanner {
public static void main(String args[]){
//create a scanner class object.
Scanner scanner = new Scanner(new
InputStreamReader(System.in));
System.out.println("Enter your full name: ");
//read a line using scanner object.
String userName = scanner.nextLine();
System.out.println("Enter your full age: ");
//read an integer using scanner object.
int age = scanner.nextInt();
//print input values
System.out.println("User name : " + userName);
System.out.println("User age : " + age);
}
}
Output:
Enter your full name:
jai
Enter your full age:
27
User name : jai
User age : 27
Download this example.

Abstract class in java


Abstract class in real world:
Let us take an example of graphic objects. Different graphic objects are there such as circle, rectangle, triangle etc. They
all have state defined by their positions, colour etc. and behaviour defined by draw, resize, calculate size etc. As all these
object types has common things but with different implementations. We can take advantage of common things with

different implementations and put these common things in an abstract class (say GraphicObjects) then extends this class
in subclasses to provide specific implementations.
Abstract class in java:
Abstract class is a way of implementing 0 to 100% abstraction. A class declared with abstract keyword is known as an
abstract class. An abstract class may or may not contain abstract method. Abstract classes cannot be instantiated.
Syntax:
abstract class className {
// declare fields
// declare abstract/non-abstract methods
}

Abstract method:
A method with no implementation i.e. without braces and followed by a semicolon.
Syntax:
abstract return_type methodName();
Example:
/**
* This program is used to show simple use of abstract class.
* @author javawithease
*/
abstract class GraphicObjects{
//abstract method declaration
abstract void showShape();
}
class Circle extends GraphicObjects{
/**
* This is the overridden method, provide implementation
* of abstract method according to your need.
* @author javawithease
*/
void showShape() {
System.out.println("Object type is Circle.");
}
}
class Rectangle extends GraphicObjects{
/**
* This is the overridden method, provide implementation
* of abstract method according to your need.
* @author javawithease
*/

void showShape() {
System.out.println("Object type is Rectangle.");
}
}
class Triangle extends GraphicObjects{
/**
* This is the overridden method, provide implementation
* of abstract method according to your need.
* @author javawithease
*/
void showShape() {
System.out.println("Object type is Triangle.");
}
}
public class AbstractClassExample1 {
public static void main(String args[]){
//GraphicObjects is the super class
//hence it's reference can contain subclass object.
GraphicObjects obj = new Circle();
obj.showShape();
obj = new Rectangle();
obj.showShape();
obj = new Triangle();
obj.showShape();
}
}
Output:
Object type is Circle.
Object type is Rectangle.
Object type is Triangle.
Download this example.
If a class have one abstract method it must be an abstract class but vice versa is not true i.e. it
is not necessary that an abstract class have an abstract method.
Example:
abstract class GraphicObjects{//no error
//non-abstract method declaration
void showShape(){
System.out.println("Print object shape.");
}
}
//error here class must be abstract if it
//have one or more abstract methods.
class GraphicObjects{
//abstract method declaration
abstract void showShape(){
}

If a class extends abstract class than either it has to provide implementation of all abstract
methods or declare this class as abstract class.
Example:
/**
* This program is used to show that a class either
* have to provide implementation
* of all abstract methods of extended abstract
* class or declare abstract itself.
* @author javawithease
*/
abstract class GraphicObjects{
//abstract method declaration
abstract void showShape();
}
class Circle extends GraphicObjects{
/**
* This is the overridden method, provide implementation
* of abstract method according to your need.
* @author javawithease
*/
void showShape() {
System.out.println("Object type is Circle.");
}
}
class Rectangle extends GraphicObjects{
//error here, Rectangle class have to provide implementation
//of all abstract methods of extended abstract class.
}
abstract class Triangle extends GraphicObjects{
//no error here, because Triangle class is declared
//as an abstract class
}
public class AbstractClassExample2 {
public static void main(String args[]){
//GraphicObjects is the super class
//hence it's reference can contain subclass object.
GraphicObjects obj = new Circle();
obj.showShape();
}
}
Output:
Error.
Download this example.
An abstract class can have both static and non-static data members and methods like any other
java class.
Example:

/**
* This program is used to show that abstract class can have both static
* and non-static data members and methods like any other java class.
* @author javawithease
*/
abstract class GraphicObjects{
//non static data member
int var1 = 50;
//static data member
static String str1 = "www.javawithease.com";
//abstract method declaration
abstract void showShape();
//non abstract, non static method
void area(int area){
System.out.println("Area = " + area);
}
//non abstract, static method
static void displayGraphicObjects(){
System.out.println("Graphic objects.");
}
}
class Circle extends GraphicObjects{
/**
* This is the overridden method, provide implementation
* of abstract method according to your need.
* @author javawithease
*/
void showShape() {
System.out.println("Object type is Circle.");
System.out.println("Non static variable = " + var1);
}
}
public class AbstractClassExample3 {
public static void main(String args[]){
//GraphicObjects is the super class
//hence it's reference can contain subclass object.
GraphicObjects obj = new Circle();
obj.showShape();
obj.area(250);
//call static method and variable with class name.
GraphicObjects.displayGraphicObjects();
System.out.println("static variable = "
+ GraphicObjects.str1);
}
}
Output:
Area = 250
Graphic objects.
static variable = www.javawithease.com

Download this example.


Why abstract class is used:
Abstract class in java is used to implement 0 to 100% abstraction.
Note: Abstract class provide 0 to 100% abstraction because it may contain no abstract method or it may contain some of
its methods as abstract methods or it may contain all its methods as abstract methods.
Can abstract class have constructors in Java?
Yes, abstract class have constructors in java. But it is not used to instantiate abstract class. It is used in constructor
chaining or to initialize abstract class common variables.
Can abstract class be final in Java?
No, abstract class cant be final in Java because abstract classes are used only by extending and if they made final they
cant extended.
Interface in java
Interface in real world:
You can see number of interface examples. Let us take example of a TV. You press change channel button of TV remote
and channel is changed. Here remote is act as an interface between you and TV.
Dictionary meaning of interface:
A point where two systems, subjects, organizations, etc., meet and interact.
Interface in java:
Interface is a way of implementing 100% abstraction. An interface is declared with interface keyword. It can contain only
abstract methods and static final data members Or Interface is a group of related abstract methods.
Syntax:
Interface Interface_Name {
//abstract methods
//static final data members
}

An interface cant be instantiated, it can be implemented by classes. To implement an interface implements keyword is
used. Interface forms a contract with your class that force your class to have all methods defined by the interface must
appear in the class. This all enforce check is done at compile time by compiler i.e. A class that implements an interface
must implement all of the methods described in the interface.

Syntax:
class class_name implements Interface_Name {
//all methods of interface
//block of code for class
}
Note:
1. A class extends another class.
2. An interface extends another interface.
3. A class implements an interface.
Example:
/**
* This program is used to show simple interface example.
* @author javawithease
*/
interface ShowDetails{
//This method is used to print name and age.
void showDetail(String name, int age);
}
public class InterfaceExample1 implements ShowDetails{
/**
* This method is used to print name and age.
* @author javawithease
*/
@Override
public void showDetail(String name, int age) {
System.out.println("Name = " + name);
System.out.println("Age = " + age);
}
public static void main(String args[]){
//object creation
InterfaceExample1 obj = new InterfaceExample1();
//method call
obj.showDetail("jai", 26);
}
}
Output:
Name = jai
Age = 26
Download this example.

Multiple inheritance in java.

1.
2.

1. A class can implements multiple interfaces.


2. An interface can extends multiple interfaces.
Example:
/**
* This program is used to show multiple inheritance example.
* @author javawithease
*/
interface ShowAge{
//This method is used to print age.
void age(int age);
}
interface ShowName{
//This method is used to print name.
void name(String name);
}
public class InterfaceExample2 implements ShowAge, ShowName{
/**
* This method is used to print age.
* @author javawithease
*/
@Override
public void age(int age) {
System.out.println("Age = " + age);
}
/**
* This method is used to print name.
* @author javawithease
*/
@Override
public void name(String name) {
System.out.println("Name = " + name);
}
public static void main(String args[]){
//object creation
InterfaceExample2 obj = new InterfaceExample2();
//method call
obj.name("jai");
obj.age(26);
}
}
Output:
Name = jai
Age = 26
Download this example.

Why multiple inheritance is possible in case of interfaces but not possible in case of classes?

Multiple inheritance is possible in case of interfaces but not possible in case of classes because there is no ambiguity
problem in case of interfaces as implementation is provided by class that implements interfaces not by interfaces itself.
Example:
/**
* This program is used to show multiple inheritance is
* possible in case of interfaces because there
* is no problem of ambiguity.
* @author javawithease
*/
interface Show{
//This method is used to print name and age.
void show(String name, int age);
}
interface Detail{
//This method is used to print name and age.
void show(String name, int age);
}
public class InterfaceExample3 implements Show, Detail{
@Override
public void show(String name, int age){
System.out.println("Name = " + name);
System.out.println("Age = " + age);
}
public static void main(String args[]){
//object creation
InterfaceExample3 obj = new InterfaceExample3();
//method call
obj.show("jai", 26);
}
}
Output:
Name = jai
Age = 26
Download this example.
An interface extends another interface Example:
/**
* This program is used to show that an interface
* can extends multiple interfaces.
* @author javawithease
*/
interface ShowAge{
//This method is used to print age.
void age(int age);
}
interface ShowName{
//This method is used to print name.

void name(String name);


}
interface showDetails extends ShowAge, ShowName{
//This method is used to print roll no.
void rollNo(int rollNo);
}
public class InterfaceExample4 implements showDetails{
/**
* This method is used to print age.
* @author javawithease
*/
@Override
public void age(int age) {
System.out.println("Age = " + age);
}
/**
* This method is used to print name.
* @author javawithease
*/
@Override
public void name(String name) {
System.out.println("Name = " + name);
}
/**
* This method is used to print rollNo.
* @author javawithease
*/
@Override
public void rollNo(int rollNo) {
System.out.println("RollNo = " + rollNo);
}
public static void main(String args[]){
//object creation
InterfaceExample4 obj = new InterfaceExample4();
//method call
obj.name("jai");
obj.age(26);
obj.rollNo(4);
}
}

Output:
Name = jai
Age = 26
RollNo = 4
Download this example.
Methods of an interface are public abstract by default.

Data members of an interface are public static final by default.


Interface is abstract by default thats why no abstract keyword is used in interface declaration.

Marker/Tagging Interfaces:
An interface with no methods is known as marker or tagged interface.
Why marker interface used:
It provides some useful information to JVM/compiler so that JVM/compiler performs some special operations on it. It is
used for better readability of code. Example: Serializable, Clonnable etc.
Syntax:
public interface Interface_Name {
}

How to create custom marker Interface.


Why an interface cant have constructor?
Because interface not have any instance fields so nothing to construct. Now the question arise how interface can be
inherited without constructor because subclass constructor call super class constructor. Now we have two cases. First
case is when an interface extends other interface, in this case there is no issue because no interface have constructor and
hence no super class constructor call. Second case when a class implements an interface, in this case there is no
inheritance because class implements interface not extends interface.
how to create custom marker interface in java
Marker/Tagging Interfaces:
An interface with no methods is known as marker or tagged interface.
Why marker interface used:
It provides some useful information to JVM/compiler so that JVM/compiler performs some special operations on it. It is
used for better readability of code. Example: Serializable, Clonnable etc.
Syntax:
public interface Interface_Name {
}

Let us understand it with a example. We have no. of colleges from which some colleges are of A grade. We have created
a AGradeCollegeMarker interface which contains no method and only inform the JVM that it is a A grade college. Every
A grade college have to implement AGradeCollegeMarker. In TestCollege class, tester method will print A grade
college. if object belongs to A grade college.
Example:
AGradeCollegeMarker.java
package com.javawithease.business;
/**
* This is marker interface for A grade college.
* @author javawithease
*/
public interface AGradeCollegeMarker {
}
College1.java
package com.javawithease.business;
/**
* This class represents a A grade college.
* @author javawithease
*/
public class College1 implements AGradeCollegeMarker{
//Do something
}
College2.java
package com.javawithease.business;
/**
* This class represents a, non A grade college.
* @author javawithease
*/
public class College2 {
//Do something
}
TestCollege.java
package com.javawithease.business;
/**
* This class is used to test the custom marker interface functionality.
* @author javawithease
*/
public class TestCollege {
static void tester(Object obj){
if (obj instanceof AGradeCollegeMarker) {
System.out.println("A grade college.");
}

}
public static void main(String args[]){
College1 obj1 = new College1();
College2 obj2 = new College2();
//test college objects
tester(obj1);
tester(obj2);
}
}
Output:
A grade college.
Download this example.

Constructor in java
Constructor:
Constructor is a special member of a class which is used to initialize the state of an object. It provides the values to the
data members at the time of object creation that is why it is known as constructor.
Characteristics of constructor:
1.
2.
3.

1. A constructor must have the same name as of its class.


2. It is invoked at the time of object creation and used to initialize the state of an object.
3. It does not have an explicit return type.
Types of constructor:

1.
2.

1. Default or no-argument constructor.


2. Parameterized constructor.

Default or no-argument constructor:

A constructor with no parameter is known as default or no-argument constructor. If no constructor is defined in the class
then compiler automatically creates a default constructor at the time of compilation.
Syntax:
Class_name(){
//optional block of code
}

Why default constructor is used?


Default constructor is used to provide default values to the object properties i.e. to provide default state of an object.
Example:
/**
* This program is used to show the use of default constructor.
* @author javawithease
*/
public class ConstructorExample1 {
int num;
String str;
ConstructorExample1(){
System.out.println("Constructor called.");
}
public static void main(String args[]){
//constructor call
ConstructorExample1 obj1 =
new ConstructorExample1();
//print default values of object properties.
System.out.println("num = " + obj1.num);
System.out.println("str = " + obj1.str);
}
}
Output:
Constructor called.
num = 0
str = null
Download this example.
Note: If no constructor is defined in the class then compiler automatically creates a default
constructor at the time of compilation.
Example:
/**

* This program is used to show that compiler will automatically


* creates the default constructor if not defined.
* @author javawithease
*/
public class ConstructorExample2 {
int num;
String str;
public static void main(String args[]){
//constructor call, compiler will automatically
//creates the default constructor
ConstructorExample2 obj1 =
new ConstructorExample2();
//print default values of object properties.
System.out.println("num = " + obj1.num);
System.out.println("str = " + o Dismiss bj1.str);
}
}
Output:
num = 0
str = null
Download this example.
Parameterized constructor:
A constructor with one or more arguments is known as parameterized constructor.
Why parameterized constructor is used?
Parameterized constructor is used to provide values to the object properties. By use of parameterized constructor different
objects can be initialize with different states.
Example:
/**
* This program is used to show the use of parameterized constructor.
* @author javawithease
*/
public class ConstructorExample3 {
int num;
String str;
ConstructorExample3(int n, String s){
System.out.println("Constructor called.");
num = n;
str = s;
}
public static void main(String args[]){
//constructor call
ConstructorExample3 obj1 =
new ConstructorExample3(10, "javawithease");

//print values of object properties


System.out.println("num = " + obj1.num);
System.out.println("str = " + obj1.str);
}
}
Output:
Constructor called.
num = 10
str = javawithease
Download this example.
Note: If a class contains parameterized constructor and default constructor is needed than
default constructor has to be defined explicitly. In this case compiler will not provide default
constructor.
Example:
/**
* This program is used to show that if a class contains
* parameterized constructor and default constructor is needed
* than default constructor has to be defined explicitly. In this
* case compiler will not provide default constructor.
* @author javawithease
*/
public class ConstructorExample4 {
int num;
String str;
ConstructorExample4(int n, String s){
System.out.println("Constructor called.");
num = n;
str = s;
}
public static void main(String args[]){
//constructor call
ConstructorExample4 obj1 =
new ConstructorExample4(10, "javawithease");
//error, because in this case default constructor
//will not be provided by compiler.
ConstructorExample4 obj2 = new ConstructorExample4();
//print values of object properties.
System.out.println("num = " + obj1.num);
System.out.println("str = " + obj1.str);
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The constructor ConstructorExample4() is undefined
at com.javawithease.business.ConstructorExample4.main

(ConstructorExample4.java:23)
Download this example.
Constructor overloading in java.
The process of defining more than one constructor with different parameters in a class is known as constructor
overloading. Parameters can differ in number, type or order.

Example:
/**
* This program is used to show the use of constructor overloading.
* @author javawithease
*/
public class ConstructorExample5 {
int num;
boolean isStudent;
String str;
//One argument constructor
ConstructorExample5(boolean boolean1){
System.out.println("One argument constructor called.");
isStudent = boolean1;
}
//Two argument constructor
ConstructorExample5(int n, String s){
System.out.println("Two argument constructor called.");
num = n;
str = s;
}
//Three argument constructor
ConstructorExample5(boolean boolean1, int n, String s){
System.out.println("Three argument constructor called.");
isStudent = boolean1;
num = n;
str = s;
}
public static void main(String args[]){
//one argument constructor call
ConstructorExample5 obj1 = new ConstructorExample5(true);
//print values of object properties.
System.out.println("isStudent = " + obj1.isStudent);
System.out.println("num = " + obj1.num);
System.out.println("str = " + obj1.str);
//two argument constructor call
ConstructorExample5 obj2 =
new ConstructorExample5(10, "javawithease");
//print values of object properties.
System.out.println("isStudent = " + obj2.isStudent);

System.out.println("num = " + obj2.num);


System.out.println("str = " + obj2.str);
//three argument constructor call
ConstructorExample5 obj3 = new
ConstructorExample5(false, 20, "javawithease.com");
//print values of object properties.
System.out.println("isStudent = " + obj3.isStudent);
System.out.println("num = " + obj3.num);
System.out.println("str = " + obj3.str);
}
}
Output:
isStudent = false
num = 20
str = javawithease.com
Download this example.
Difference between constructor and method.
Constructor

Method
1. It may or may not have same name as

1. It has same name as of class.


2. Invoked implicitly.
3. Must not have any explicit return type.
4. It is used to initialize the state of an object.

of class.
2. Invoked explicitly.
3. Must have a return type.
4. It is used to show behavior of an

object.
Note: An object can also perform any operation like any other method.
Does a constructor return any value?
Yes, a constructor implicitly returns the instance of the current class.
How to copy the values one object into another object using constructor?
Example:
/**
* This program is used to copy the values one object
* into another object using constructor.
* @author javawithease
*/
public class ConstructorExample6 {
int num;
String str;
ConstructorExample6(int n, String s){
System.out.println("Constructor called.");
num = n;
str = s;
}

//This constructor will copy the value


//of one object into another.
ConstructorExample6(ConstructorExample6 obj){
System.out.println("Constructor called
for copying value.");
num = obj.num;
str = obj.str;
}
public static void main(String args[]){
//parameterized constructor call
ConstructorExample6 obj1 = new
ConstructorExample6(10, "javawithease");
//print values of object properties.
System.out.println("obj1 num = " + obj1.num);
System.out.println("obj1 str = " + obj1.str);
//Constructor call to copy the value
//one object into other.
ConstructorExample6 obj2 = new ConstructorExample6(obj1);
//print values of object properties.
System.out.println("obj2 num = " + obj2.num);
System.out.println("obj2 str = " + obj2.str);
}
}
Output:
Constructor called for copying value.
obj2 num = 10
obj2 str = javawithease
Download this example.
Package in java
Package:
Package is a namespace that is used to group logically related classes and interfaces.
Advantages/Benefits of package in java:
1.
2.
3.

1. Package provides unique namespace.


2. Package provides access protection.
3. Package provides grouping of logically related classes and interfaces so easy to maintain.
How to create a package:
A package is created with package keyword.
Example:
PackageExample1.java
package test;

/**
* This program is used to show simple use of package.
* @author javawithease
*/
public class PackageExample1 {
public static void main(String args[]){
System.out.println("This is first package example.");
}
}
Output:
This is first package example.
Download this example.
How to access package from outside the package:
1. Using import keyword.
a. Import packagename.*;
All classes and interface will be accessible but not of subpackages.
b. Import packagename.classname;
Only specific class is accessible.
2. Using full qualified name.
Specific class will be accessible and no need to import but everywhere it is used fully qualified name is needed.
Example of import packagename.*
Display.java
package com.javawithease.display;
/**
* This class is used to display entered text.
* @author javawithease
*/
public class Display {
public void displayText(String text){
System.out.println(text);
}
}
Test.java
package test;
import display.*;
/**
* This class is used to show package use with import packagename.*.
* @author javawithease
*/
public class Test {

public static void main(String args[]){


Display display = new Display();
display.displayText("Hello java.");
}
}
Output:
Hello java.
Download this example.
Example of import packagename.classname
Display.java
package com.javawithease.display;
/**
* This class is used to display entered text.
* @author javawithease
*/
public class Display {
public void displayText(String text){
System.out.println(text);
}
}
Test.java
package test;
import display.Display;
/**
* This class is used to show package using import packagename.className.
* @author javawithease
*/
public class Test {
public static void main(String args[]){
Display display = new Display();
display.displayText("Hello java.");
}
}
Output:
Hello java.
Download this example.
Example of using full qualified name
Display.java
package display;
/**
* This class is used to display entered text.

* @author javawithease
*/
public class Display {
public void displayText(String text){
System.out.println(text);
}
}
Test.java
package test;
/**
* This class is used to show package using full qualified name.
* @author javawithease
*/
public class Test {
public static void main(String args[]){
display.Display display =
new display.Display();
display.displayText("Hello java.");
}
}
Output:
Hello java.
Download this example.
Subpackage:
A package inside a package is known as subpackage.
Example:
Display.java
package com.javawithease.display;
/**
* This class is used to display entered text.
* @author javawithease
*/
public class Display {
public void displayText(String text){
System.out.println(text);
}
}
Test.java
package com.javawithease.test;
import com.javawithease.display.*;
/**
* This class is used to show sub package using import.
* @author javawithease
*/

public class Test {


public static void main(String args[]){
Display display =
new Display();
display.displayText("Hello java.");
}
}
Output:
Hello java.
Download this example.
Note: If a package is import, all classes and interface will be accessible of that package but not of subpackages. So
subpackage also be import to access classes and interfaces of subpackage.

Example:
Display.java
package com.javawithease.display;
/**
* This class is used to display entered text.
* @author javawithease
*/
public class Display {
public void displayText(String text){
System.out.println(text);
}
}
Test.java
package com.javawithease.test;
import com.javawithease.*;
/**
* This class is used to show sub package classes
* will not import if package is imported.
* @author javawithease
*/
public class Test {
public static void main(String args[]){
//Error
Display display = new Display();
display.displayText("Hello java.");
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problems:
Display cannot be resolved to a type

Display cannot be resolved to a type


at com.javawithease.test.Test.main(Test.java:13)
Download this example.

Access modifier in java


Access modifiers:
Access modifiers are keywords used for defining accessibility of classes, methods and data members.
Types of access modifier.
1.
2.
3.
4.

1. Private.
2. Default
3. Protected
4. Public
Private:
Data members, methods and constructors that are declared with private access modifier can be accessed into that class
only.
Example:
PrivateAccessModifier.java
/**
* This program is used to show that private members
* of a class can be accessed in that class only
* @author javawithease
*/
class Student {
//private members of the class
private int rollNo = 5;
private void showRollNo(){
//rollNo which a private data member is
//accessible in that class.
System.out.println("RollNo = " + rollNo);
}
}
public class PrivateAccessModifier {
public static void main(String args[]){
//creating Student class object
Student obj = new Student();
//compile time error because private members
//of a class can be accessed in that class only.
System.out.println(obj.rollNo);

obj.showRollNo();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problems:
The field Student.rollNo is not visible
The method showRollNo() from the type Student is not visible
at com.javawithease.business.PrivateAccessModifier.main
(PrivateAccessModifier.java:24)
Download this example.
Note: A class can have a private constructor but we cannot create an instance of that class from
outside the class.
PrivateConstructor.java
/**
* This program is used to show that we cannot create an instance
* of that class from outside the class if constructor is private.
* @author javawithease
*/
class Student {
//private constructor of the class
private Student(){
}
public void show(){
System.out.println("Hello javawithease.com");
}
}
public class PrivateConstructor {
public static void main(String args[]){
//compile time error in creating Student class object
//because of private constructor.
Student obj = new Student();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The constructor Student() is not visible
at com.javawithease.business.PrivateConstructor.main
(PrivateConstructor.java:22)
Download this example.

Note: Classes and interfaces cant be private except nested classes.


Default:
Classes, data members, methods and constructors that are not declared with any access modifier are treated as default.
They can be accessed into all classes within the same package only.
Example 1:
DefaultAccessModifier1.java
/**
* This program is used to show that members of the class
* of a class can be accessed in the package level only.
* @author javawithease
*/
class Student {
//private members of the class
int rollNo = 5;
void showRollNo(){
System.out.println("RollNo = " + rollNo);
}
}
public class DefaultAccessModifier1 {
public static void main(String args[]){
//creating Student class object
Student obj = new Student();
//No compile time error because members of the class
//of a class can be accessed in that package but can't be
//accessed outside the package.
System.out.println(obj.rollNo);
obj.showRollNo();
}
}
Output:
5
RollNo = 5
Download this example.
Example 2:
Display.java
package com.javawithease.display;
/**
* This class is used to print a line.
* @author javawithease
*/
class Display {
void display(){

System.out.println("Hello javawithease.com");
}
}
Test.java
package com.javawithease.test;
import com.javawithease.display.*;
/**
* This program is used to show that default members of the class
* are not accessible from outside the package.
* @author javawithease
*/
public class Test {
public static void main(String args[]){
//compile time error because default members of the class
//are not accessible from outside the package.
Display obj = new Display();
obj.display();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problems:
The type Display is not visible
The type Display is not visible
The type Display is not visible
at com.javawithease.test.Test.main(Test.java:13)
Download this example.
Protected:
Data members, methods and constructors that are declared with protected access modifier can be accessed into all classes
within the same package and only in subclasses outside the package.
Example 1:
Display.java
package com.javawithease.display;
/**
* This class is used to print a line.
* @author javawithease
*/
public class Display {
protected void display(){
System.out.println("Hello javawithease.com");
}
}
Test.java
package com.javawithease.display;

package com.javawithease.test;
import com.javawithease.display.*;
/**
* This program is used to show that protected members of the
* class are accessible from outside the package in subclasses.
* @author javawithease
*/
public class Test extends Display{
public static void main(String args[]){
Test obj = new Test();
//No compile time error because protected members
//of the class are accessible from outside the
//package in subclasses.
obj.display();
}
}
Output:
Hello javawithease.com
Download this example.
Example 2:
Display.java
package com.javawithease.display;
/**
* This class is used to print a line.
* @author javawithease
*/
public class Display {
protected void display(){
System.out.println("Hello javawithease.com");
}
}
Test.java
package com.javawithease.test;
import com.javawithease.display.*;
/**
* This program is used to show that protected members of the class
* are not accessible from outside the package in non-subclasses.
* @author javawithease
*/
public class Test {
public static void main(String args[]){
Display obj = new Display();
//compile time error because protected members
//of the class are not accessible from outside
//the package in non-subclasses.
obj.display();

}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The method display() from the type Display is not visible
at com.javawithease.test.Test.main(Test.java:15)
Download this example.
Note: Classes and interfaces cant be protected except nested classes.
Public:
Classes, data members, methods and constructors that are declared with public access modifier can be accessed
everywhere.
Example:
Display.java
package com.javawithease.display;
/**
* This class is used to print a line.
* @author javawithease
*/
public class Display {
public void display(){
System.out.println("Hello javawithease.com");
}
}
Test.java
package com.javawithease.test;
import com.javawithease.display.*;
/**
* This program is used to show that public members of the class
* are accessible everywhere.
* @author javawithease
*/
public class Test {
public static void main(String args[]){
Display obj = new Display();
//public members of the class accessible everywhere.
obj.display();
}
}
Output:
Hello javawithease.com

Download this example.


Static import in java
Static import:
Static import is a feature which provides the facility to access static members of a class directly without using class
name.
Example:
Display.java
package display;
/**
* This class is used to display entered text.
* @author javawithease
*/
public class Display {
public static void displayText(String text){
System.out.println(text);
}
}
Test
package test;
import static display.Display.*;
/**
* This class is used to show static import example.
* @author javawithease
*/
public class Test {
public static void main(String args[]){
displayText("Hello java.");
}
}
Output:
Hello java.
Download this example.
Advantages of static import:
It reduces the code by removing the need of class name to access static data members.
Disadvantages of static import:
1. It reduces the code readability because of class name absence.
2. If two classes have static data member with same name and both classes are statically imported. Then java will throw
compile time error.

Difference between import and static import.


import
1. Access classes and interfaces without
package name.
2. Accessibility is for classes and interfaces.
3. import not result in a unreadable code.
4. No code conflict.

static import
1. Access static members without class
and interface name.
2. Accessibility is for static data
members.
3. Static import can result in an
unreadable code.
4. Code conflict can occur.

Package class in java


Package class:
Package class provides the information about a package like package name, implementation title etc.
Example:
/**
* This class is used to show use of Package class.
* @author javawithease
*/
public class Test {
public static void main(String args[]){
Package package1=Package.getPackage("java.lang");
System.out.println("package name = "
+package1.getName());
System.out.println("Specification Title = "
+package1.getSpecificationTitle());
System.out.println("Specification Vendor = "
+package1.getSpecificationVendor());
System.out.println("Specification Version = "
+package1.getSpecificationVersion());
System.out.println("Implementaion Title = "
+package1.getImplementationTitle());
}
}
Output:
package name = java.lang
Specification Title = Java Platform API Specification
Specification Vendor = Oracle Corporation
Specification Version = 1.7
Implementaion Title = Java Runtime Environment
Download this example.
this keyword in java
this keyword:
this is a keyword in java which refers to the current instance of the class. Every constructor and all non-static methods in
java have this as an implicitly parameter.

Note: When n numbers of parameters are passed in a method then from JRE point of view n+1 number of parameters are
passed in the method. One additional parameter is this. If this keyword is used in constructor or method then this must be
the first statement.
Use of this keyword in java:
1.
2.
3.
4.
5.
6.

1. this can be used to differentiate between instance variable and local variable.
2. this can be used in constructor chaining. this() and super() must be the first statement.
3. this can be used to invoke current class method implicitly.
4. this can be used to return current instance of the class.
5. this can be used as a parameter in constructor call.
6. this can be used as a parameter in method call.
1. this can be used to differentiate between instance variable and local variable.
If local variable and instance variables are same than compiler will not be able to distinguish them.
Example:
ThisExample1.java
/**
* This program is used to show that if local variable and
* instance variables are same than compiler will not be able
* to distinguish them.
* @author javawithease
*/
class Student{
//instance variable.
int rollNo;
String name;
Student(String name, int rollNo){
//local variable.
name = name;
rollNo = rollNo;
}
public void displayDetails(){
System.out.println("RollNo = " + rollNo);
System.out.println("name = " + name);
}
}
public class ThisExample1 {
public static void main(String args[]){
//creating Student class object.
Student stu1 = new Student("jai", 6);
//method call
stu1.displayDetails();
}
}
Output:
RollNo = 0
name = null

Download this example.


If local variable and instance variables are same than compiler will not be able to distinguish them. this can be used to
differentiate between instance variable and local variable
Example:
ThisExample2.java
/**
* This program is used to show that if local variable and
* instance variables are same than compiler will not be able
* to distinguish them. This problem is resolved using this keyword.
* @author javawithease
*/
class Student{
//instance variable.
int rollNo;
String name;
Student(String name, int rollNo){
//local variable.
this.name = name;
this.rollNo = rollNo;
}
public void displayDetails(){
System.out.println("RollNo = " + rollNo);
System.out.println("name = " + name);
}
}
public class ThisExample2 {
public static void main(String args[]){
//creating Student class object.
Student stu1 = new Student("jai", 6);
//method call
stu1.displayDetails();
}
}
Output:
RollNo = 6
name = jai
Download this example.
If local variable and instance variables are different than no need of this keyword.
Example:
ThisExample3.java
/**
* This program is used to show that if local variable and

* instance variables are different than no need for this keyword.


* @author javawithease
*/
class Student{
//instance variable.
int rollNo;
String name;
Student(String n, int r){
//local variable.
name = n;
rollNo = r;
}
public void displayDetails(){
System.out.println("RollNo = " + rollNo);
System.out.println("name = " + name);
}
}
public class ThisExample3 {
public static void main(String args[]){
//creating Student class object.
Student stu1 = new Student("jai", 6);
//method call
stu1.displayDetails();
}
}
Output:
RollNo = 6
name = jai
Download this example.
2. this can be used in constructor chaining.
Constructor chaining:
Constructor chaining is a process of calling one constructor from other constructor of a class on an object.
Example:
ThisExample7.java
/**
* This program is used to show the use of this keyword
* in constructor chaining.
* @author javawithease
*/
class Display {
int a, b;
//default constructor.
Display(){

//call two parameter constructor using this.


this(10, 20);
System.out.println("Default Constructor called.");
}
//one parameter constructor.
Display(int num1){
//call two parameter constructor using this.
this(num1, 40);
System.out.println("one parameter constructor called.");
}
//two parameter constructor.
Display(int num1, int num2){
a = num1;
b = num2;
System.out.println("two parameter constructor called.");
}
//method to display values.
public void display(){
System.out.println("a = " +a);
System.out.println("b = " +b);
}
}
public class ThisExample7 {
public static void main(String args[]){
//call default constructor.
Display obj1 = new Display();
obj1.display();
//call one parameter constructor.
Display obj2 = new Display(30);
obj2.display();
//call two parameter constructor.
Display obj3 = new Display(50, 60);
obj3.display();
}
}
Output:
two parameter constructor called.
Default Constructor called.
a = 10
b = 20
two parameter constructor called.
one parameter constructor called.
a = 30
b = 40
two parameter constructor called.
a = 50
b = 60
Download this example.
3. this can be used to invoke current class method implicitly.

Method chaining:
Method chaining is a process of calling multiple methods on an object in a single statement.
Example:
ThisExample4.java
/**
* This program is used to show that this keyword
* can call current class method implicitly.
* @author javawithease
*/
class Display{
public void displayName(){
System.out.println("jai");
//call current class method using this
this.displayRollNo();
}
public void displayRollNo(){
System.out.println("6");
//compiler will automatically add this
//keyword if not used.
displayClass();
}
public void displayClass(){
System.out.println("MCA");
}
}
public class ThisExample4 {
public static void main(String args[]){
//create Display class object
Display display = new Display();
//method call
display.displayName();
}
}
Output:
jai
6
MCA
Download this example.
4. this can be used to return current instance of the class.
Example:

ThisExample6.java
/**
* This program is used to show that this keyword
* returns the instance of current class.
* @author javawithease
*/
class Display{
public Display getDisplay(){
//this return the current class object.
return this;
}
public void display(){
System.out.println("Hello javawithease.com");
}
}
public class ThisExample6 {
public static void main(String args[]){
//create Display class object
Display display = new Display();
//method call, here getDisplay() returns the
//object of current Display class.
display.getDisplay().display();
}
}
Output:
Hello javawithease.com
Download this example.
5. this can be used as a parameter in constructor call.
Example:
ThisExample8.java
/**
* This program is used to show that this keyword
* can be passed as an argument in the constructor.
* @author javawithease
*/
class Display{
Display(Show obj){
System.out.println("Show obj = " + obj);
}
}
class Show{
Show(){
//pass show class object as an argument using this.
Display obj = new Display(this);
}

}
public class ThisExample8 {
public static void main(String args[]){
//create Show class object
Show show = new Show();
}
}
Output:
Javawithease
com.javawithease.business.Display@dc8569
Download this example.
6. this can be used as a parameter in method call.
Example:
ThisExample5.java
/**
* This program is used to show that this keyword
* can be passed as an argument in the method.
* @author javawithease
*/
class Display{
public void displayName(){
System.out.println("javawithease");
//passing this keyword as an argument.
displayObject(this);
}
public void displayObject(Display obj){
//will print string representation of the object.
System.out.println(obj);
}
}
public class ThisExample5 {
public static void main(String args[]){
//create Display class object
Display display = new Display();
//method call
display.displayName();
}
}
Output:
Show obj = com.javawithease.business.Show@1bab50a
Download this example.

Note: this is a final variable, so you cant assign any value to this. this cant be used in static method.
Instance Initializer block in java
Instance initializer block:
Instance initializer block is a mechanism provided by java compiler to define a group of statements common to all
constructors at a single place. At the compilation time, compiler moves these statements at the beginning of all
constructors after super. It is can also be used to initialize the instance variable.
Example:
AnonymousBlockExample1.java
/**
* This program is used to show the use of AnonymousBlock.
* @author javawithease
*/
class Display {
int a, b;
//Anonymous or instance initializer Block
{
System.out.println("AnonumousBlock called.");
a = 10;
}
//default constructor
Display(){
System.out.println("default constructor called.");
}
//one argument constructor
Display(int num){
System.out.println("one parameter constructor called.");
b = num;
}
//method to display values
public void display(){
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
public class AnonymousBlockExample1 {
public static void main(String args[]){
Display obj1 = new Display();
obj1.display();
Display obj2 = new Display(20);
obj2.display();
}
}
Output:

AnonumousBlock called.
default constructor called.
a = 10
b=0
AnonumousBlock called.
one parameter constructor called.
a = 10
b = 20
Download this example.
If two Anonymous Blocks are used then they will execute in the same order in which they are
appear.
Example:
AnonymousBlockExample2.java
/**
* This program is used to show that if two AnonymousBlocks
* are used then they will execute in the same order in
* which they are appear.
* @author javawithease
*/
class Display {
int a, b, c;
//First Anonymous or instance initializer Block
{
System.out.println("First AnonumousBlock called.");
a = 10;
}
//Second Anonymous or instance initializer Block
{
System.out.println("Second AnonumousBlock called.");
b = 20;
}
//default constructor
Display(){
System.out.println("default constructor called.");
}
//one argument constructor
Display(int num){
System.out.println("one parameter constructor called.");
c = num;
}
//method to display values
public void display(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}

public class AnonymousBlockExample2 {


public static void main(String args[]){
Display obj1 = new Display();
obj1.display();
Display obj2 = new Display(30);
obj2.display();
}
}
Output:
First AnonumousBlock called.
Second AnonumousBlock called.
default constructor called.
a = 10
b = 20
c=0
First AnonumousBlock called.
Second AnonumousBlock called.
one parameter constructor called.
a = 10
b = 20
c = 30
Download this example.
If static and non-static Anonymous Blocks are used then static Anonymous Block is executed
only once.
Example:
AnonymousBlockExample3.java
/**
* This program is used to show that if static and non-static
* AnonymousBlocks are used then static AnonymousBlocks is
* executed only once.
* @author javawithease
*/
class Display {
int a, b;
//static Anonymous or instance initializer Block
static {
System.out.println("Static AnonumousBlock called.");
}
//non-static Anonymous or instance initializer Block
{
System.out.println("Non-Static AnonumousBlock called.");
a = 20;
}
//default constructor
Display(){
System.out.println("default constructor called.");

}
//one argument constructor
Display(int num){
System.out.println("one parameter constructor called.");
b = num;
}
//method to display values
public void display(){
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
public class AnonymousBlockExample3 {
public static void main(String args[]){
Display obj1 = new Display();
obj1.display();
Display obj2 = new Display(30);
obj2.display();
}
}
Output:
Static AnonumousBlock called.
Non-Static AnonumousBlock called.
default constructor called.
a = 20
b=0
Non-Static AnonumousBlock called.
one parameter constructor called.
a = 20
b = 30
Download this example.
In which order static initializer block, instance initialize block, super and constructor are called?
static initialize block super- instance initialize block constructor.
Example:
AnonymousBlockExample4.java
/**
* This program is used to show that in which order static
* AnonumousBlocks, non-static AnonumousBlocks, super and
* default constructors are called.
* @author javawithease
*/
class Show{
Show(){
System.out.println("Super class constructor.");
}

}
class Display extends Show{
//static Anonymous or instance initializer Block
static {
System.out.println("Static AnonumousBlock called.");
}
//non-static Anonymous or instance initializer Block
{
System.out.println("Non-Static AnonumousBlock called.");
}
//default constructor
Display(){
super();
System.out.println("default constructor called.");
}
}
public class AnonymousBlockExample4 {
public static void main(String args[]){
Display obj = new Display();
}
}
Output:
Static AnonumousBlock called.
Super class constructor.
Non-Static AnonumousBlock called.
default constructor called.
Download this example.
super keyword in java
super is a keyword in java which refers to the immediate super class object.
Use of super keyword in java:
1.
2.
3.

1. super can be used to call immediate super class constructor (constructor chaining).
2. super can be used to call immediate super class method on a subclass object from a subclass method.
3. super can be used to access immediate super class instance variable.
1. super can be used to call immediate super class constructor (constructor chaining).
Example:
SuperExample1.java
/**
* This program is used to show the use of super
* keyword to invoke super class constructor using
* super explicitly.
* @author javawithease

*/
class Display {
Display(){
System.out.println("Super class constructor called.");
}
}
public class SuperExample1 extends Display {
SuperExample1(){
//super keyword will call super class constructor.
super();
System.out.println("Current class constructor called.");
}
public static void main(String args[]){
SuperExample1 obj = new SuperExample1();
}
}
Output:
Super class constructor called.
Current class constructor called.
Download this example.
If super is not used explicitly compiler will automatically add super as the first statement.
Example:
SuperExample2.java
/**
* This program is used to show the use of super
* keyword to invoke super class constructor using
* super implicitly.
* @author javawithease
*/
class Display {
Display(){
System.out.println("Super class constructor called.");
}
}
public class SuperExample2 extends Display {
SuperExample2(){
//compiler automatically add super here.
System.out.println("Current class constructor called.");
}
public static void main(String args[]){
SuperExample2 obj = new SuperExample2();
}
}
Output:

Super class constructor called.


Current class constructor called.
Download this example.
2. super can be used to call immediate super class method on a subclass object from a subclass
method.
If super class and subclass have same methods and that method is called from subclass method than subclass method is
called.
Example:
SuperExample4.java
/**
* This program is used to show that if super class and subclass
* have same methods and that method is called from subclass
* method than subclass method is called.
* @author javawithease
*/
class Display {
public void display(){
System.out.println("display method of super class.");
}
}
class Show extends Display {
public void display(){
System.out.println("display method of sub class.");
}
public void show(){
System.out.println("show method of sub class.");
//subclass display method is called.
display();
}
}
public class SuperExample4 {
public static void main(String args[]){
//create Show class object.
Show obj = new Show();
//method call
obj.show();
}
}
Output:
show method of sub class.
display method of sub class.
Download this example.

Above problem can be solved with super keyword.


Example:
SuperExample3.java
/**
* This program is used to show the use super keyword
* to invoke the super class method from subclass method.
* @author javawithease
*/
class Display {
public void display(){
System.out.println("display method of super class.");
}
}
class Show extends Display {
public void display(){
System.out.println("display method of sub class.");
}
public void show(){
System.out.println("show method of sub class.");
//super class display method is called.
super.display();
}
}
public class SuperExample3 {
public static void main(String args[]){
//create Show class object.
Show obj = new Show();
//method call
obj.show();
}
}
Output:
show method of sub class.
display method of super class.
Download this example.
If super class and subclass not have same methods and method of super class is called from
subclass method than super class method is called. There is no need of super keyword.
Example:
SuperExample5.java
/**
* This program is used to show that if super class and subclass
* not have same methods and method of super class is called from
* subclass method than super class method is called.There is

* no need of super keyword.


* @author javawithease
*/
class Display {
public void display(){
System.out.println("display method of super class.");
}
}
class Show extends Display {
public void show(){
System.out.println("show method of sub class.");
//no need of super keyword here.
display();
}
}
public class SuperExample5 {
public static void main(String args[]){
//create Show class object.
Show obj = new Show();
//method call
obj.show();
}
}
Output:
show method of sub class.
display method of super class.
Download this example.
3. super can be used to access immediate super class instance variable.
If super class and subclass have same instance variables and that variable is called from subclass than subclass instance
variable will be referred.
Example:
SuperExample6.java
/**
* This program is used to show that if super class and subclass
* have same variable name and that variable is used in subclass
* method than subclass variable will be called.
* @author javawithease
*/
class Display {
int num = 100;
}
class Show extends Display {
int num = 200;
public void show(){

//sub class instance variable will be referred.


System.out.println("num = " + num);
}
}
public class SuperExample6 {
public static void main(String args[]){
//create Show class object.
Show obj = new Show();
//method call
obj.show();
}
}
Output:
num = 200
Download this example.
Above problem can be solved with super keyword.
Example:
SuperExample7.java
/**
* This program is used to show the use super keyword to invoke
* the super class instance variable from subclass method.
* @author javawithease
*/
class Display {
int num = 100;
}
class Show extends Display {
int num = 200;
public void show(){
//super class instance variable will be referred.
System.out.println("num = " + super.num);
}
}
public class SuperExample7 {
public static void main(String args[]){
//create Show class object.
Show obj = new Show();
//method call
obj.show();
}
}
Output:
num = 100

Download this example.


If sub class and super class instance variables are not same than there is no need of super
keyword.
Example:
SuperExample8.java
/**
* This program is used to show that if sub class and
* super class instance variables are not same than there
* is no need of super keyword.
* @author javawithease
*/
class Display {
int num = 100;
}
class Show extends Display {
public void show(){
//super class instance variable will be referred.
System.out.println("num = " + num);
}
}
public class SuperExample8 {
public static void main(String args[]){
//create Show class object.
Show obj = new Show();
//method call
obj.show();
}
}
Output:
num = 100
Download this example.
Difference between this and super keyword in java.
1.
2.

1. this is used for accessing variables and methods of current class. super is used for accessing variables
and methods of immediate super class.
2. this is used in constructor chaining in current class. super is used in constructor chaining in immediate
super class.
static keyword in java
Static is a keyword in java used to represent the class members. It can be used with variable, method, initializer block and
nested class.
Types of class members:

1.
2.
3.
4.

1. Static data members.


2. Static initializer block.
3. Static method.
4. Static nested class.
1. Static data members:
Data members declared with static keyword are known as static data members. These are mainly used to represent those
properties which are common to every object. At the time of class loading a single copy is created for static data
members, which is shared by all objects.
Memory division in a java program execution.
In a java program execution memory is divided into three parts:

1.
2.
3.
1.
2.
3.

1. Stack.
2. Heap.
3. Class/Method area.
1. Stack: Stack is used to local variables of the methods.
2. Heap: Heap is used to store objects.
3. Class Area: Class area is used to store static data members.
Static data members are used to represent those properties which are common to every object.
Example:
StaticExample1.java
/**
* This program is used to show that static data members are
* used to represent those properties which are common to every object.
* @author javawithease
*/
class MCAStudent{
//name and rollNo are not common for all students
//so keep them as non-static data members.
String name;
int rollNo;
//As course offered is same for all students
//so keep it as static.
String courseName = "MCA";
//constructor
MCAStudent(String n, int r){
name = n;
rollNo = r;
}
//display all values
public void display(){
System.out.println("Name = " + name);
System.out.println("RollNo. = " + rollNo);
System.out.println("Course Name = " + courseName);
System.out.println("");
}
}

public class StaticExample1 {


public static void main(String args[]){
//create object of MCAStudent class.
MCAStudent stu1 = new MCAStudent("jai", 6);
MCAStudent stu2 = new MCAStudent("sunil", 15);
//method call
stu1.display();
stu2.display();
}
}
Output:
Name = jai
RollNo. = 6
Course Name = MCA
Name = sunil
RollNo. = 15
Course Name = MCA
Download this example.
Non-static data members have different memory locations for different objects.
Example:
StaticExample2.java
/**
* This program is used to show that non-static data members
* have different memory locations for different objects.
* @author javawithease
*/
class Test{
int num = 0;
//constructor
Test(){
num = num + 10;
System.out.println("Number = " + num);
}
}
public class StaticExample2 {
public static void main(String args[]){
Test obj1 = new Test();
Test obj2 = new Test();
Test obj3 = new Test();
Test obj4 = new Test();
}
}
Output:
Number = 10
Number = 10

Number = 10
Number = 10
Download this example.
Static data members use the same memory locations for all objects.
Example:
StaticExample3.java
/**
* This program is used to show that static data members
* use the same memory locations for all objects.
* @author javawithease
*/
class Test{
static int num = 0;
//constructor
Test(){
num = num + 10;
System.out.println("Number = " + num);
}
}
public class StaticExample3 {
public static void main(String args[]){
Test obj1 = new Test();
Test obj2 = new Test();
Test obj3 = new Test();
Test obj4 = new Test();
}
}
Output:
Number = 10
Number = 20
Number = 30
Number = 40
Download this example.
Note: Constructor is not used to initialize the static data members because constructor initializes many times but static
data members only once. So instead of constructor static initialize block is used to initialize static data members.
Static initializer block: Click here for static initializer block.
Static methods:
Static methods represent the behavior of whole class. An instance of a class is not required to execute static methods.
They can be called using class name.
Syntax: ClassName.methodName

Example:
StaticExample4.java
/**
* This program is used to show that there is no need of an object
* for accessing a static method. It can be called with class name.
* @author javawithease
*/
class Display {
//static method
public static void display(){
System.out.println("Hello javawithease.com");
}
}
public class StaticExample4 {
public static void main(String args[]){
//No need for object to call static method.
Display.display();
}
}
Output:
Hello javawithease.com
Download this example.
Note: We can execute a program without main method.
Example:
/**
* This is java program without using main function.
* @author javawithease
*/
public class WithoutMain {
static{
System.out.println("Hello javawithease.com");
System.exit(0);
}
}
Output:
Hello javawithease.com
Limitations of static methods and static initialize blocks.
1.
2.
3.

1. Non-static data members cant be accessed in static methods and static initialize blocks.
2. Non-static methods cant be invoked in static methods and static initialize blocks.
3. This or super keyword cant be refers in static methods and static initialize blocks.
1. Non-static data members cant be accessed in static methods and static initialize blocks.

Example:
StaticExample5.java
/**
* This program is used to show that non-static data members cant
* be accessed in static methods and static initialize blocks.
* @author javawithease
*/
class Test {
//non-static data member
int num = 10;
static{
//error because non-static data members can't be
//accessed in static initializer block.
System.out.println("Num = " + num);
}
public static void display(){
System.out.println("Hello javawithease.com");
//error because non-static data members can't be
//accessed in static method.
System.out.println("Num = " + num);
show();
}
}
public class StaticExample5 {
public static void main(String args[]){
//creating object of Test class
Test obj = new Test();
//method call
obj.display();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problems:
Cannot make a static reference to the non-static field num
Cannot make a static reference to the non-static field num
The method show() is undefined for the type Test
at com.javawithease.business.Test.(StaticExample5.java:15)
at com.javawithease.business.StaticExample5.main
(StaticExample5.java:31)
Download this example.
2. Non-static methods cant be invoked in static methods and static initialize blocks.
Example:
StaticExample6.java

/**
* This program is used to show that non-static methods cant
* be accessed in static methods and static initialize blocks.
* @author javawithease
*/
class Test {
//non static method
public void show(){
System.out.println("Hello world.");
}
static{
//error because non-static methods can't be
//accessed in static initializer block.
show();
}
public static void display(){
System.out.println("Hello javawithease.com");
//error because non-static methods can't be
//accessed in static method.
show();
}
}
public class StaticExample6 {
public static void main(String args[]){
//creating object of Test class
Test obj = new Test();
//method call
obj.display();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problems:
Cannot make a static reference to the non-static
method show() from the type Test
Cannot make a static reference to the non-static
method show() from the type Test
at com.javawithease.business.Test.(StaticExample6.java:17)
at com.javawithease.business.StaticExample6.main
(StaticExample6.java:32)
Download this example.
3. This or super keyword cant be refers in static methods and static initialize blocks.
Example:
StaticExample7.java
/**
* This program is used to show that this or super keyword cant

* be refers in static methods and static initialize blocks.


* @author javawithease
*/
class Show {
int num = 10;
}
class Display extends Show {
int num = 20;
public static void show(){
//error because super can't be refers in static
//method or static initializer block.
System.out.println("num of super class = " + super.num);
}
public static void display(int num){
//error because this can't be refers in static
//method or static initializer block.
this.num = num;
}
}
public class StaticExample7 {
public static void main(String args[]){
Display obj = new Display();
obj.show();
obj.display(20);
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Cannot use super in a static context
at com.javawithease.business.Display.show
(StaticExample7.java:18)
at com.javawithease.business.StaticExample7.main
(StaticExample7.java:32)
Download this example.
final keyword in java
final is a keyword in java which can be used with instance variables, local variables , methods and classes.
Use of final keyword in java:
1. final variable in java:
A variable declared with final keyword is known as final variable. It may be member variable or local variable. final
variables are constants in java and they are generally declared with static keyword. As final variables are treated as
constants they cant reassign. They are initialised at the time of declaration.
Example:

FinalExample1.java
/**
* This program is used to show that the value of
* final variable can't be change.
* @author javawithease
*/
class Test{
//final variable
final int num = 100;
//method for try to change the value of final variable.
public void show(){
//error because value of final variable can't be change.
num = 200;
System.out.println("Num = " + num);
}
}
public class FinalExample1 {
public static void main(String args[]){
//creating object of Test Class
Test obj = new Test();
//method call
obj.show();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The final field Test.num cannot be assigned
at com.javawithease.business.Test.show(FinalExample1.java:15)
at com.javawithease.business.FinalExample1.main
(FinalExample1.java:24)
Download this example.
Note: Inside Anonymous classes only final variables are accessible.
2. final method in java:
A method declared with final keyword is known as final method.
Example:
FinalExample2.java
/**
* This program is used to show that final method can't be override.
* @author javawithease
*/
class Show{
public final void show(){
System.out.println("Hello world.");
}
}

class Display extends Show{


//error because final method can't be override.
public void show(){
System.out.println("Hello javawithease.com.");
}
}
public class FinalExample2 {
public static void main(String args[]){
//creating object of Display class
Display obj = new Display();
//method call
obj.show();
}
}
Output:
Exception in thread "main" java.lang.VerifyError:
class com.javawithease.business.Display overrides final method show.()V
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.javawithease.business.FinalExample2.main
(FinalExample2.java:23)
Download this example.
Note: A final method can be inherited but cant be override.
3. final class in java:
A class declared with final keyword is known as final class. A final class cant be inherited.
Example:
FinalExample3.java
/**
* This program is used to show that final class can't be inherited.
* @author javawithease
*/
final class Show{
public void show(){
System.out.println("Hello world.");
}
}

//error because final class can't be inherited.


class Display extends Show{
public void display(){
System.out.println("Hello javawithease.com.");
}
}
public class FinalExample3 {
public static void main(String args[]){
//creating object of Display class
Display obj = new Display();
//method call
obj.display();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The type Display cannot subclass the final class Show
at com.javawithease.business.Display.(FinalExample3.java:13)
at com.javawithease.business.FinalExample3.main
(FinalExample3.java:22)
Download this example.
Note: final method can be inherited.
Example:
FinalExample4.java
/**
* This program is used to show that final method can be inherited.
* @author javawithease
*/
class Show{
public final void show(){
System.out.println("Hello world.");
}
}
class Display extends Show{
public void display(){
System.out.println("Hello javawithease.com.");
}
}
public class FinalExample4 {
public static void main(String args[]){
//creating object of Display class
Display obj = new Display();
//method call
obj.show();
}
}

Output:
Hello world.
Download this example.
Note: Abstract class and constructor cant be final.
4. Blank final variable in java:
A variable declared with final keyword but not initialised at declaration time is known as blank final variable. They are
initialised at the time of object creation in constructor and cant change after that.
Example:
FinalExample5.java
/**
* This class is used to show the example of blank final variable.
* @author javawithease
*/
class Test{
//blank final variable which can only be
//initialize through constructor.
final int num;
Test(int n){
num = n;
System.out.println("Num = " + num);
}
}
public class FinalExample5 {
public static void main(String args[]){
new Test(100);
}
}
Output:
Num = 100
Download this example.
5. static blank final variable in java:
A static variable declared with final keyword but not initialised at declaration time is known as static blank final variable.
It can be initialised in a static block only.
Example:
FinalExample6.java
/**
* This class is used to show the example of static blank final variable.

* @author javawithease
*/
class Test{
//blank final variable which can only be initialize
//through static initializer block.
static final int num;
static{
num = 100;
System.out.println("Num = " + num);
}
}
public class FinalExample6 {
public static void main(String args[]){
new Test();
}
}
Output:
Num = 100
Download this example.
6. final parameter in java:
A method parameter declared with final keyword is known as final parameter. Its value cant be changed.
Example:
FinalExample7.java
/**
* This program is used to show that value of
* final parameter can't be changed.
* @author javawithease
*/
class Test{
public void showDouble(final int num){
//error because value of final parameter can't be changed.
num = num * 2;
System.out.println("Num * 2 = " + num);
}
}
public class FinalExample7 {
public static void main(String args[]){
//creating object of Test class
Test obj = new Test();
//method call
obj.showDouble(10);
}
}
Output:
Exception in thread "main" java.lang.Error:

Unresolved compilation problem:


The final local variable num cannot be assigned.
It must be blank and not using a compound assignment
at com.javawithease.business.Test.showDouble
(FinalExample7.java:11)
at com.javawithease.business.FinalExample7.main
(FinalExample7.java:20)
Download this example.
Advantages/Benefits of final keyword:
1.
2.

1. Performance: JVM kept in cache if variables, methods and classes are declared final.
2. Immutable classes: With the help of final keyword we can made immutable classes.
String handling in java
String handling is a way of handling and manipulating strings in java with the help of lot concepts like concatenation,
comparison etc.
String:
In General String is sequence of characters.
In Java String is an object which is created by using String class. String objects are immutable and they cant modified
i.e. any change in the existing object will result into a new object.
How to create string object?

1.
2.

1. By String literal.
2. By new keyword.
1. By String literal:
String literal: A sequence of characters enclosed in double quotes. String literal is a concept of java language. It is not
an object from java.lang.String. e.g. Hello java. In the string literal case one object and one reference variable is
created. Object is placed in string constant pool.
String literal/constant pool: is a special part of heap memory used to store string literals or string constants.
Every time a literal is created, JVM checks the string constant pool for it. If string literal is already in the pool then no
new object will be created in the pool, a reference of the already existing object will returns. If string literal is not exist in
the string constant pool then new instance will be created and placed in the string constant pool.
E.g. String str1 = javawithease
String str2 = javawithease

In the above example in case of str1 JVM checks for javawithease in string constant pool. First time it will be not in the
pool hence JVM create new instance and placed it into the pool. In case of str2 JVM will find the javawithease in the
pool. Hence no new instance will be created and reference of the already existing instance will be return.
Java uses the concept of java literal to increase memory efficiency. Because, no new instance will be created for a string
literal if it is already exist in string constant pool.
2. By new keyword:
String objects can be created with new keyword also. In this case two objects and one reference variable is created. One
object is created in heap area (non-pool) and other (string literal) is placed in string constant pool. The variable will refer
to the object in heap area.
e.g.- String str = new String(javawithease).

Why string objects are immutable in java?

As we discussed above java uses the concept of String literal. Suppose n reference variables refer to one object
javawithease .If one reference variable changes the value of the object, it will be affected to all other n-1 reference
variables. Thats why string objects are immutable in java.
String comparison in java
In java there are three ways to compare two strings.
Ways of String Comparison:
1. By == operator.
2. By equals() method.
3. By compareTo() method.
1. By == operator:
== operator compares the references of the string objects not the actual content of the string objects. It returns true if
reference of the compared strings are equal, otherwise returns false.
Example:
StringComparisonExample1.java
/**
* This program is used to show the use of == operator.
* @author javawithease.
*/
class TestString{
String str1 = "javawithease";
String str2 = "javawithease";
String str3 = new String("javawithease");
/**
* This method is used to compare strings using == operator.
* @author javawithease
*/
public void stringComparison(){
//return true, because str1 and str2 both refers to the
//same instance created in String constant pool.
System.out.println(str1 == str2);
//return false, because str3 refers to the
// instance created in nonpool.
System.out.println(str1 == str3);
}
}
public class StringComparisonExample1 {
public static void main(String args[]){
//creating TestString object.
TestString obj = new TestString();
//method call
obj.stringComparison();
}
}

Output:
True
false
Download this example.
2. By equals() method:
equals method compares the actual content of string objects not the references. equals() is an object class method and
string class overrides it. String class provides following format of equals() method.
a. public boolean equals(Object obj): Compares the string with the specified object. Returns true if actual content are
equal, otherwise returns false.
b. public Boolean equalsIgnoreCase(String str): Compares the actual content of the string with the content of specified
string. Returns true if two strings content are equal ignoring case, otherwise returns false.
Example:
StringComparisonExample2.java
/**
* This program is used to show the use of equals method.
* @author javawithease.
*/
class TestString{
String str1 = "javawithease";
String str2 = "javawithease";
String str3 = new String("javawithease");
String str4 = "jai";
String str5 = "JAVAWITHEASE";
/**
* This method is used to compare strings using equals operator.
* @author javawithease
*/
public void stringComparison(){
//return true, because content are same.
System.out.println(str1.equals(str2));
System.out.println(str2.equals(str3));
//return false, because content are not same.
System.out.println(str2.equals(str4));
//return false, because content are not same
//(differ in case).
System.out.println(str2.equals(str5));
//return true, because content are same ignoring case.
System.out.println(str2.equalsIgnoreCase(str5));
}
}
public class StringComparisonExapmle2 {
public static void main(String args[]){
//creating TestString object.
TestString obj = new TestString();

//method call
obj.stringComparison();
}
}
Output:
true
true
false
false
true
Download this example.
3. By compareTo():
compareTo() method compares the two strings lexicographically i.e. character by character. String class provides the
following formats of compareTo() method.
a. public int compareTo(String str)
b. public int compareToIgnoreCase(String str)
It returns 0 if the argument string is equal to this string, less than 0 if this string is lexicographically less than the string
argument and greater than 0 if this string is lexicographically greater than the string argument.
Example:
StringComparisonExample3.java
/**
* This program is used to show the use of compareTo method.
* @author javawithease.
*/
class TestString{
String str1 = "javawithease";
String str2 = "javawithease";
String str3 = "jai";
String str4 = "sandy";
/**
* This method is used to compare
* strings using compareTo operator.
* @author javawithease
*/
public void stringComparison(){
//return 0, because content are same.
System.out.println(str1.compareTo(str2));
//return greater than 0, because str1
//lexicographically greater than str2.
System.out.println(str1.compareTo(str3));
//return less than 0, because str1
//lexicographically less than str2.

System.out.println(str3.compareTo(str4));
}
}
public class StringComparisonExample3 {
public static void main(String args[]){
//creating TestString object.
TestString obj = new TestString();
//method call
obj.stringComparison();
}
}
Output:
0
13
-9
Download this example.
String concatenation in java
General meaning of concatenation means a series of interconnected things. String concatenation refers to the combination
of more than one string.
Ways of String concatenation:
1.
2.

1. By concatenation operator +.
2. By concat() method.
1. By concatenation operator +:
String concatenation can be performed with + operator. String concatenation is performed by StringBuilder or
StringBuffer class and its append method. Result will be a new string after appending second string at the end of the first
string. Both string and primitive data type can be concatenated.
Compiler will transform it to:
String s=(new StringBuilder()).append(firstString).append(secondString).toString();
Example:
StringConcatenationExample1.java
/**
* This program is used to show the concatenation
* of strings by + operator.
* @author javawithease
*/
class TestString{
String str1 = "www.";
String str2 = "javawithease.";
String str3 = "com";
/**

* This method is used to concatenate strings using + operator.


* @author javawithease
*/
public void concateStrings(){
System.out.println(str1 + str2 + str3);
}
}
public class StringConcatenationExample1 {
public static void main(String args[]){
//creating TestString object.
TestString obj = new TestString();
//method call
obj.concateStrings();
}
}
Output:
www.javawithease.com
Download this example.
Note: If any one of the two arguments of + operator is a string then result will be a string otherwise primitive type.
Example:
StringConcatenationExample2.java
/**
* This program is used to show the concatenation of
* strings and primitive data types by + operator.
* @author javawithease.
*/
class TestString{
String str1 = "jai";
int num1 = 20;
int num2 = 30;
int num3 = 40;
int num4 = 50;
/**
* This method is used to concatenate strings and
* primitive data types using + operator.
* @author javawithease
*/
public void concateOerations(){
//As expression executes from left to right and
//num1, num2 both are primitive data types will result
//into primitive, next argument is String and hence
// will result into a string, next argument num3
// is a primitive type but as one of the two
//operands is a string and hence result will be
//a string, same is for num4.
System.out.println(num1 + num2 + str1 + num3 + num4);
}
}
public class StringConcatenationExample2 {

public static void main(String args[]){


//creating TestString object.
TestString obj = new TestString();
//method call
obj.concateOerations();
}
}
Output:
50jai4050
Download this example.
2. By concat() method:
This method concatenate argument string at the end of current string and return the resulting string.
Syntax: public String concat(String s).
Example:
StringConcatenationExample3.java
/**
* This program is used to show the concatenation
* of strings by concat method.
* @author javawithease
*/
class TestString{
String str1 = "www.";
String str2 = "javawithease.";
String str3 = "com";
/**
* This method is used to concatenate strings using concat method.
* @author javawithease
*/
public void concateStrings(){
System.out.println(str1.concat(str2).concat(str3));
}
}
public class StringConcatenationExample3 {
public static void main(String args[]){
//creating TestString object.
TestString obj = new TestString();
//method call
obj.concateStrings();
}
}
Output:
www.javawithease.com

Download this example.


Substring in java
Substring is a string that is part of a longer string. String class provides the following methods to get a substring from a
string.
1. public String substring(int startIndex):
Returns a new string which start from a specified string and extends to the end of this string. It will throw
IndexOutOfBoundsException if startIndex is negative or larger than the length of this String object.
Example:
SubStringExample1.java
/**
* This program is used to show the use of substring(int startIndex)
* method to get substrings of a given string.
* @author javawithease
*/
class TestString{
String str = "Hello javawithease";
/**
* This method is used to get substrings of a given string.
* @author javawithease
*/
public void showSubString(){
System.out.println(str.substring(6));
}
}
public class SubStringExample1 {
public static void main(String args[]){
//creating TestString object.
TestString obj = new TestString();
//method call
obj.showSubString();
}
}
Output:
javawithease
Download this example.
2. public String substring(int startIndex, int endIndex):
Returns a new string which start from a specified string and extends to the endIndex 1 of this string. It will throw
IndexOutOfBoundsException if the startIndex is negative, or endIndex is larger than the length of this string object, or
startIndex is larger than endIndex.
Example:

SubStringExample2.java
/**
* This program is used to show the use of
* substring(int startIndex, int endIndex)
* method to get substrings of a given string.
* @author javawithease
*/
class TestString{
String str = "www.javawithease.com";
/**
* This method is used to get substrings of a given string.
* @author javawithease
*/
public void showSubString(){
System.out.println(str.substring(4,16));
}
}
public class SubStringExample2 {
public static void main(String args[]){
//creating TestString object.
TestString obj = new TestString();
//method call
obj.showSubString();
}
}
Output:
javawithease
Download this example.
Note: startIndex is inclusive but endIndex is exclusive.
How to write Immutable class in java
All wrapper classes and String class are immutable classes.
You can write your own immutable class, when creating immutable class just keep in mind that after creating an object of
this class object cant be modified. Any change in existing object result into new object.

1.
2.

1. Make final class so that it cannot inherit.


2. Object state is made up of its properties, declare all properties final. So that its properties value will remain
constant.

3.

3. Object properties value can be set using setter methods, so only define getter methods for all properties.
Example:
ImmutableClassExample.java

/**
* This program is used to create a immutable class.
* @author javawithease
*/
final class Student{
//declare all properties final.
final String rollNo;
public Student(String rollNo){
this.rollNo = rollNo;
}
//only create getter method.
public String getRollNo() {
return rollNo;
}
}
public class ImmutableClassExample {
public static void main(String args[]){
//creating Student object.
Student obj = new Student("MCA/07/06");
System.out.println(obj.getRollNo());
}
}
Output:
MCA/07/06
Download this example.
Advantages/Benefits of immutable class.
1.
2.

1. Objects are thread safe by default.


2. No need to synchronize immutable objects explicitly.
Disadvantages of immutable classes.
As discussed any change in immutable object result into a new object, hence result in unnecessary garbage.
toString() method in java
toString() method of Object class is used to provide string representation of an object.
When a object is passed in print() method as an argument then compiler internally call toString() method on the object. It
returns object representation as classname@hexadecimal representation of hash code of the object.
Example:
ToStringExample1.java
/**
* This program is used to show the use of toString method.

* @author javawithease
*/
class Student{
String name;
String rollNo;
//constructor
Student(String name, String rollNo){
this.name = name;
this.rollNo = rollNo;
}
}
public class ToStringExample1 {
public static void main(String args[]){
//creating Student class object
Student stu1 = new Student("Sunil", "MCA/07/15");
Student stu2 = new Student("Sandy", "MCA/07/19");
Student stu3 = new Student("Roxy", "MCA/07/32");
//println internally call toString method
System.out.println(stu1);
System.out.println(stu2);
System.out.println(stu3);
}
}
Output:
com.javawithease.business.Student@1888759
com.javawithease.business.Student@6e1408
com.javawithease.business.Student@e53108
Download this example.
Note: We can override toString() method for customize results.
Example:
ToStringExample2.java
/**
* This program is used to show the use of override toString method.
* @author javawithease
*/
class Student{
String name;
String rollNo;
//constructor
Student(String name, String rollNo){
this.name = name;
this.rollNo = rollNo;
}
//Override toString method to get customize results.
public String toString(){
return "Name:" + name + ", RollNo: " + rollNo;
}

}
public class ToStringExample2 {
public static void main(String args[]){
//creating Student class object
Student stu1 = new Student("Sunil", "MCA/07/15");
Student stu2 = new Student("Sandy", "MCA/07/19");
Student stu3 = new Student("Roxy", "MCA/07/32");
//println internally call toString method
System.out.println(stu1);
System.out.println(stu2);
System.out.println(stu3);
}
}
Output:
Name:Sunil, RollNo: MCA/07/15
Name:Sandy, RollNo: MCA/07/19
Name:Roxy, RollNo: MCA/07/32
Download this example.
string class methods in java
S.No. Method
1.
public boolean equals(Object anObject)
public boolean equalsIgnoreCase(String
2.
anotherString)
3.

public String concat(String str)

4.

public int compareTo(String str)

5.

public int compareToIgnoreCase(String str)

6.

public String substring(int beginIndex)

7.

public String substring(int beginIndex,int


endIndex)

8.

public String toUpperCase()

9.

public String toLowerCase()

10.

public String trim()

11.

public boolean startsWith(String prefix)

12.

public boolean endsWith(String suffix)

13.
14.

public char charAt(int index)


public int length()

15.

public String intern()

16

public int indexOf(String str)

17

public int lastIndexOf(String str)

Description
Compares this string to the specified object.
Compares this String to another String,
ignoring case.
Concatenates the argument string to the end
of this string.
Compares two strings lexicographically.
Compares two strings lexicographically,
ignoring case.
Returns a new string that is a substring of
this string.
Returns a new string that is a substring of
this string.
Converts all of the characters in this String to
upper case.
Converts all of the characters in this String to
lower case.
Returns a copy of the string, with leading and
trailing whitespace omitted.
Tests if this string starts with the specified
prefix.
Tests if this string ends with the specified
suffix.
Returns the char value at the specified index.
Returns the length of this string.
Returns a canonical representation for the
string object.
Returns the index of the first occurrence of
the specified substring within this string.
Returns the index of the last occurrence of the

18

public String toString()

specified substring within this string.


This object (which is already a string!) is itself
returned.

charAt(int index) String function in java


charAt(int index):
Returns the char value at the specified index.
Syntax: public char charAt(int index).
Note: An index ranges from 0 to length() 1. If index is negative or greater than length() 1, it will throw
IndexOutOfBoundsException.
Example:
StringCharAtExample.java
/**
* This program is used to show the use of charAt() method.
* @author javawithease
*/
class TestString{
String str = "www.javawithease.com";
/**
* This method is used to show the use of charAt() method.
* @author javawithease
*/
public void charAtTest(){
//Returns the character value at the specified index.
System.out.println(str.charAt(8));
}
}
public class StringCharAtExample {
public static void main(String args[]){
//creating TestString object
TestString obj = new TestString();
//method call
obj.charAtTest();
}
}
Output:
w
Download this example.
startsWith(String prefix) and endsWith(String suffix) string functions in java
startsWith(String prefix): Tests if this string starts with the specified prefix.

Syntax: public boolean startsWith(String prefix).


Note: It returns true if the character sequence represented by the argument is a prefix of the character sequence
represented by this string otherwise returns false. It also returns true if the argument string is empty or is equal to this
String object.
endsWith(String suffix): Tests if this string ends with the specified suffix.
Syntax: public boolean endsWith(String suffix).
Note: It returns true if the character sequence represented by the argument is a suffix of the character sequence
represented by this string otherwise returns false. It also returns true if the argument string is empty or is equal to this
String object.
Example:
StringExample.java
/**
* This program is used to show the use
* of startsWith() and endsWith() method.
* @author javawithease
*/
class TestString{
String str = "javawithease";
/**
* This method is used to show the use of startsWith() method.
* @author javawithease
*/
public void startsWithTest(){
//return true
System.out.println(str.startsWith("java"));
//return false
System.out.println(str.startsWith("a"));
}
/**
* This method is used to show the use of endsWith() method.
* @author javawithease
*/
public void endsWithTest(){
//return true
System.out.println(str.endsWith("se"));
//return false
System.out.println(str.endsWith("a"));
}
}
public class StringExample {
public static void main(String args[]){
//creating TestString obj
TestString obj = new TestString();
//method call
obj.startsWithTest();
obj.endsWithTest();
}

}
Output:
true
false
true
false
Download this example.
indexOf(String str) and lastIndexOf(String str) String functions in java
indexOf(String str): Returns the index of the first occurrence of the specified substring within this string.
Syntax: public int indexOf(String str).
Note: If no such occurrence of substring within this string than it returns -1.
lastIndexOf(String str): Returns the index of the last occurrence of the specified substring within this string.
Syntax: public int lastIndexOf(String str).
Note: If no such occurrence of substring within this string than it returns -1.
Example:
StringIndexTestExample.java
/**
* This program is used to show the use
* of indexOf and lastIndexOf() method.
* @author javawithease
*/
class TestString{
String str = "www.javawithease.com";
/**
* This method is used to show the use of indexOf() method.
* @author javawithease
*/
public void indexOfTest(){
System.out.println(str.indexOf("a"));
}
/**
* This method is used to show the use of lastIndexOf() method.
* @author javawithease
*/
public void lastIndexOfTest(){
System.out.println(str.lastIndexOf("e"));
}
}
public class StringIndexTestExample {
public static void main(String args[]){

//creating TestString object


TestString obj = new TestString();
//method call
obj.indexOfTest();
obj.lastIndexOfTest();
}
}
Output:
5
15
Download this example.
toLowerCase() and toUpperCase() String functions in java
toLowerCase(): Converts all of the characters in this String to lower case.
Syntax: public String toLowerCase().
toUpperCase(): Converts all of the characters in this String to upper case.
Synatx: public String toUpperCase().
Example:
CaseChangeExample.java
/**
* This program is used to show the use of
* toUpperCase and toLowerCase methods.
* @author javawithease
*/
class TestString{
String str = "Jai";
/**
* This method is used to show the use of toUpperCase() method.
* @author javawithease
*/
public void upperCase(){
//will convert all characters in upper case.
System.out.println(str.toUpperCase());
}
/**
* This method is used to show the use of toLowerCase() method.
* @author javawithease
*/
public void lowerCase(){
//will convert all characters in lower case.
System.out.println(str.toLowerCase());
}
}

public class CaseChangeExample {


public static void main(String args[]){
//creating TestString object
TestString obj = new TestString();
//method call
obj.upperCase();
obj.lowerCase();
}
}
Output:
JAI
jai
Download this example.

intern() String functions in java


intern():Returns a canonical representation for the string object.
Syntax: public String intern().
Note: It returns a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
Example:
StringInternExample.java
/**
* This program is used to show the use of intern() method.
* @author javawithease
*/
class TestString{
String str1 = "www.javawithease.com";
String str2;
/**
* This method is used to show the use of intern() method.
* @author javawithease
*/
public void internTest(){
str2 = str1.intern();
System.out.println(str2);
}
}
public class StringInternExample {
public static void main(String args[]){
//creating TestString object

TestString obj = new TestString();


//method call
obj.internTest();
}
}
Output:
www.javawithease.com
Download this example.
length() String functions in java
length():Returns the length of this string.
Syntax: public int length().
Example:
StringLengthExample.java
/**
* This program is used to show the use of length() method.
* @author javawithease
*/
class TestString{
String str = "www.javawithease.com";
/**
* This method is used to show the use of length() method.
* @author javawithease
*/
public void stringLengthTest(){
System.out.println(str.length());
}
}
public class StringLengthExample {
public static void main(String args[]){
//creating TestString object
TestString obj = new TestString();
//method call
obj.stringLengthTest();
}
}
Output:
20
Download this example.

trim() String functions in java


trim():Returns a copy of the string, with leading and trailing whitespace omitted.
Syntax: public String trim().
Example:
StringTrimExample.java
/**
* This program is used to show the use of trim() method.
* @author javawithease
*/
class TestString{
String str = " www.javawithease.com ";
/**
* This method is used to show the use of trim() method.
* @author javawithease
*/
public void trimString(){
//will remove all leading and trailing whitespace.
System.out.println(str.trim());
}
}
public class StringTrimExample {
public static void main(String args[]){
//creating TestString object
TestString obj = new TestString();
//method call
obj.trimString();
}
}
Output:
www.javawithease.com
Download this example.

StringBuffer in java
StringBuffer is a class in java whose object represents the mutable string. It is just like string class except that its object
can be modified. StringBuffer is synchronized, hence it is thread-safe.
i.e. StringBuffer class objects are thread safe , mutable sequence of characters.
For these reasons, Java would handle an expression like
String newString = aString + anInt + aChar + aDouble;

like this:
String newString = (new StringBuffer(aString)).append(anInt).append(aChar).append(aDouble).toString();
Note: StringBuffer not override equals method of object class, so StringBuffer objects should be converted into string
objects if you want to compare StringBuffer class objects.
Constructors of StringBuffer class.
1. public StringBuffer():creates a string buffer with no characters and with default capacity 16 i.e. it can contain 16
characters.
2. public StringBuffer(int capacity): creates a string buffer with no characters and with specified capacity.
Note: capacity should not be less than zero , otherwise it will throw NegativeArraySizeException.
3. public StringBuffer(String str):creates a string buffer with specified string as initial content.
Initial capacity = Default capacity + length of the string.
Note:
1. string should not be null otherwise it will throw NullPointerException.
2. if string length is equal to zero than string buffer with no content and default capacity is return.
4. public StringBuffer(CharSequence charSquence):creates a string buffer with specified character sequence as its
initial content.
Note:
1. charSquence should not be null otherwise it will throw NullPointerException.
2. if charSquence length is equal to zero than string buffer with no content and default capacity is return.
Commonly used methods of StringBuffer class.
S.No.
1.
2.
3.
4.
5.
6.
7.

Method

Description
Append the specified string at the end of
append(String str)
this string.
Insert specified string at the offset indicated
insert(int offset, String str)
position.
Replace the substring of the string buffer
replace(int startIndex, int endIndex, String str) from startIndex to endIndex-1 with
specified string.
delete the substring of the string buffer
delete(int startIndex, int endIndex)
from startIndex to endIndex-1.
replace the string buffers character
reverse()
sequence by reverse character sequence.
returns the current capacity of string buffer.
capacity()
Capacity refers to the amount of available
storage.
ensures that the capacity is at least equal to
ensureCapacity(int minCapacity)
the specified minimum.

append(String str) StringBuffer method in java

append(String str): append the specified string at the end of this string.
Syntax: public synchronized StringBuffer append(String str).
Note: if specified string is null than it append null string at the end.
If append has object, int, double etc as an argument than argument value first converted into string using
String.valueOf()before appending.
Example:
StringBufferAppendExample.java
/**
* This program is used to show the use of append() method.
* @author javawithease
*/
class TestStringBuffer{
StringBuffer sb = new StringBuffer("Hello ");
/**
* This method is used to show the use of append() method.
* @author javawithease
*/
public void appendTest(){
//concatenate the argument string
//at the end of this string.
System.out.println(sb.append("www.javawithease.com"));
}
}
public class StringBufferAppendExample {
public static void main(String args[]){
//creating TestStringBuffer object
TestStringBuffer obj = new TestStringBuffer();
//method call
obj.appendTest();
}
}
Output:
Hello www.javawithease.com
Download this example.
insert(int offset, String str) StringBuffer method in java
insert(int offset, String str): insert specified string at the offset indicated position.
Syntax: public synchronized StringBuffer insert(int offset, String str).

Note: if specified string is null than it insert null string at the offset indicated position.
If insert has object, int, double etc instead of string than argument value first converted into string using
String.valueOf()before inserting.
Offset should be between 0 to length of string, if it is not StringIndexOutOfBoundsException will be thrown.

Example:
StringBufferInsertExample.java
/**
* This program is used to show the use of insert() method.
* @author javawithease
*/
class TestStringBuffer{
StringBuffer sb = new StringBuffer("www.com");
/**
* This method is used to show the use of insert() method.
* @author javawithease
*/
public void insertTest(){
//insert specified string at
//the offset indicated position.
System.out.println(sb.insert(3,".javawithease"));
}
}
public class StringBufferInsertExample {
public static void main(String args[]){
//creating TestStringBuffer object
TestStringBuffer obj = new TestStringBuffer();
//method call
obj.insertTest();
}
}
Output:
www.javawithease.com
Download this example.
replace(int startIndex, int endIndex, String str) StringBuffer method in java
replace(int startIndex, int endIndex, String str): replace the substring of the string buffer from startIndex to endIndex1 with specified string.
Syntax: public synchronized StringBuffer replace(int startIndex, int endIndex, String str).
Note: startIndex should be between 0 to length of string or less than endIndex, if it is not
StringIndexOutOfBoundsException will be thrown.
Example:

StringBufferReplaceExample.java
/**
* This program is used to show the use of replace() method.
* @author javawithease
*/
class TestStringBuffer{
StringBuffer sb = new StringBuffer("www.abc.com");
/**
* This method is used to show the use of replace() method.
* @author javawithease
*/
public void replaceTest(){
//replace the substring of the string buffer from
//startIndex to endIndex-1 with specified string.
System.out.println(sb.replace(4,7,"javawithease"));
}
}
public class StringBufferReplaceExample {
public static void main(String args[]){
//creating TestStringBuffer object
TestStringBuffer obj = new TestStringBuffer();
//method call
obj.replaceTest();
}
}
Output:
www.javawithease.com
Download this example.
delete(int startIndex, int endIndex) StringBuffer method in java
delete(int startIndex, int endIndex): delete the substring of the string buffer from startIndex to endIndex-1.
Syntax: public synchronized StringBuffer delete(int startIndex, int endIndex).
Note: startIndex should be between 0 to length of string or less than endIndex, if it is not
StringIndexOutOfBoundsException will be thrown.
Example:
StringBufferDeleteExample.java
/**
* This program is used to show the use of delete() method.
* @author javawithease
*/
class TestStringBuffer{
StringBuffer sb = new StringBuffer("Hello www.javawithease.com");

/**
* This method is used to show the use of delete() method.
* @author javawithease
*/
public void deleteTest(){
//delete the substring of the string
//buffer from startIndex to endIndex-1.
System.out.println(sb.delete(0,6));
}
}
public class StringBufferDeleteExample {
public static void main(String args[]){
//creating TestStringBuffer object
TestStringBuffer obj = new TestStringBuffer();
//method call
obj.deleteTest();
}
}
Output:
www.javawithease.com
Download this example.
reverse() StringBuffer method in java
reverse(): replace the string buffers character sequence by reverse character sequence.
Syntax: public synchronized StringBuffer reverse().
Example:
StringBufferReverseExample.java
/**
* This program is used to show the use of reverse() method.
* @author javawithease
*/
class TestStringBuffer{
StringBuffer sb = new StringBuffer("www.javawithease.com");
/**
* This method is used to show the use of reverse() method.
* @author javawithease
*/
public void reverseTest(){
//replace the string buffers character
//sequence by reverse character sequence.
System.out.println(sb.reverse());
}
}
public class StringBufferReverseExample {
public static void main(String args[]){

//creating TestStringBuffer object


TestStringBuffer obj = new TestStringBuffer();
//method call
obj.reverseTest();
}
}
Output:
moc.esaehtiwavaj.www
Download this example.
capacity() StringBuffer method in java
capacity(): returns the current capacity of string buffer. Capacity refers to the amount of available storage.
Syntax: public int capacity().
Example:
StringBufferCapacityExample.java
/**
* This program is used to show the use of capacity() method.
* @author javawithease
*/
class TestStringBuffer{
StringBuffer sb = new StringBuffer();
/**
* This method is used to show the use of capacity() method.
* @author javawithease
*/
public void capacityTest(){
//default capacity.
System.out.println(sb.capacity());
sb.append("Hello ");
//current capacity 16.
System.out.println(sb.capacity());
sb.append("www.javawithease.com");
//current capacity (16*2)+2=34 i.e (oldcapacity*2)+2.
System.out.println(sb.capacity());
}
}
public class StringBufferCapacityExample {
public static void main(String args[]){
//creating TestStringBuffer object
TestStringBuffer obj = new TestStringBuffer();
//method call
obj.capacityTest();
}

}
Output:
16
16
34
Download this example.
ensureCapacity(int minCapacity) StringBuffer method in java
ensureCapacity(int minCapacity): ensures that the capacity is at least equal to the specified minimum.
Syntax: public void ensureCapacity(int minCapacity).
Note:
1. If current capacity is greater than the argument there will be no change in the current capacity.
2. If current capacity is less than the argument there will be change in the current capacity using below rule.
newcapacity = (oldcapacity*2) + 2.
Example:
StringBufferEnsureCapacityExample.java
/**
* This program is used to show the use of ensureCapacity() method.
* @author javawithease
*/
class TestStringBuffer{
StringBuffer sb = new StringBuffer();
/**
* This method is used to show the use of ensureCapacity() method.
* @author javawithease
*/
public void ensureCapacityTest(){
//default capacity.
System.out.println(sb.capacity());
sb.append("Hello ");
//current capacity 16.
System.out.println(sb.capacity());
sb.append("www.javawithease.com");
//current capacity (16*2)+2=34 i.e (oldcapacity*2)+2.
System.out.println(sb.capacity());
sb.ensureCapacity(10);
//now no change in capacity because
//minimum is already set to 34.
System.out.println(sb.capacity());
sb.ensureCapacity(50);
//now (34*2)+2 = 70 as 50 is greater than 34.
System.out.println(sb.capacity());
}

}
public class StringBufferEnsureCapacityExample {
public static void main(String args[]){
//creating TestStringBuffer object
TestStringBuffer obj = new TestStringBuffer();
//method call
obj.ensureCapacityTest();
}
}
Output:
16
34
34
70
Download this example.
StringTokenizer in java
StringTokenizer class is used to break a string into tokens using specified delimiter.
Note: space is the default delimiter.
Constructors of StringTokenizer class:
1. public StringTokenizer(String str): creates a string tokenizer for the specified string. By default space is taken as
delimiter here.
2. public StringTokenizer(String str, String delimiter): creates a string tokenizer for the specified string by using
specified delimiter. Delimiter character will be treated as separator only and not be treated as tokens.
3. public StringTokenizer(String str, String delimiter, boolean returnDelimiters): creates a string tokenizer for the
specified string by using specified delimiter. Delimiter character can be treated as separator returnDelimiters is true.
Commonly used methods of StringTokenizer:
1. hasMoreTokens(): checks whether more tokens are available or not. It returns true if more takens are available else
return false.
Syntax: public boolean hasMoreTokens().
2. hasMoreElements(): same as hasMoreTokens() , mainly used in case of enumeration.
Syntax: public boolean hasMoreElements().
3. nextToken(): returns the next token from this string tokenizer.

Note: It will throw NoSuchElementException if no more token is available.


Syntax: public String nextToken().
4. nextToken(String delimiter): returns the next token from this string tokenizer using specified delimeter.It is mainly
used when we want to separate tokens using differen delimiters in single string tokenizer.
Syntax: public String nextToken(String delim).
Note: It will throw NoSuchElementException if no more token is available.
5. nextElement(): same as nextToken() except that it returns an object rather than string. It is mainly used in case of
enumeration.
Syntax: public Object nextElement().
Note: It will throw NoSuchElementException if no more token is available.
6. countTokens(): returns the number of times nextToken method can be called on this string tokenizer before an
exception occur.
Syntax: public int countTokens().
Example 1:
StringTokenizerExample.java
import java.util.StringTokenizer;
/**
* This program is used to print all tokens of a string.
* @author javawithease
*/
class TestStringTokenizer{
//By default whitespace will act as separator.
StringTokenizer str = new StringTokenizer("Hello i am here");
/**
* This method is used to print all tokens of a string.
* @author javawithease
*/
public void displayTokens(){
while(str.hasMoreTokens()){
System.out.println(str.nextToken());
}
}
}
public class StringTokenizerExample {
public static void main(String args[]){
//creating TestStringTokenizer object.
TestStringTokenizer obj = new TestStringTokenizer();
//method call
obj.displayTokens();
}

}
Output:
Hello
i
am
here
Download this example.
Example 2:
StringTokenizerExample.java
import java.util.StringTokenizer;
/**
* This program is used to print all tokens
* of a string on the bases of comma.
* @author javawithease
*/
class TestStringTokenizer{
//Using comma as separator.
StringTokenizer str =
new StringTokenizer("Hello ,i ,am ,here", ",");
/**
* This method is used to print all tokens
* of a string on the bases of comma.
* @author javawithease
*/
public void displayTokens(){
while(str.hasMoreTokens()){
System.out.println(str.nextToken());
}
}
}
public class StringTokenizerExample {
public static void main(String args[]){
//creating TestStringTokenizer object.
TestStringTokenizer obj = new TestStringTokenizer();
//method call
obj.displayTokens();
}
}
Output:
Hello
i
am
here
Download this example.

Example 3:
StringTokenizerExample.java
import java.util.StringTokenizer;
/**
* This program is used to print all tokens of
* a string on the bases of multiple separators.
* @author javawithease
*/
class TestStringTokenizer{
//Using multiple separators.
StringTokenizer str =
new StringTokenizer("Hello ,i ;am :here", ", ; :");
/**
* This method is used to print all tokens of
* a string on the bases of multiple separators.
* @author javawithease
*/
public void displayTokens(){
while(str.hasMoreTokens()){
System.out.println(str.nextToken());
}
}
}
public class StringTokenizerExample {
public static void main(String args[]){
//creating TestStringTokenizer object.
TestStringTokenizer obj = new TestStringTokenizer();
//method call
obj.displayTokens();
}
}
Output:
Hello
i
am
here
Download this example.
StringBuilder in java
StringBuilder is same as StringBuffer except that StringBuilder is not synchronized, hence it is not thread-safe.
i.e. StringBuilder class objects are non-thread-safe , mutable sequence of characters.
Note: StringBuilder not override equals method of object class, so StringBuilder objects should be converted into string
objects if you want to compare StringBuilder class objects.
Constructors of StringBuffer class:

1. public StringBuilder (): creates a string builder with no characters and with default capacity 16 i.e. it can contain 16
characters.
2. public StringBuilder (int capacity): creates a string builder with no characters and with specified capacity.
Note: capacity should not be less than zero , otherwise it will throw NegativeArraySizeException.
public StringBuilder (String str):creates a string builder with specified string as initial content.
Initial capacity = Default capacity + length of the string.
Note:
1. string should not be null otherwise it will throw NullPointerException.
2. if string length is equal to zero than string builder with no content and default capacity is return.
3. public StringBuilder (CharSequence charSquence):creates a string builder with specified character sequence as its
initial content.
Note:
1. charSquence should not be null otherwise it will throw NullPointerException.
2. if charSquence length is equal to zero than string builder with no content and default capacity is return.

Commonly used methods of StringBuilder class:


S.No.
1.
2.
3.
4.
5.
6.
7.

Method

Description
Append the specified string at the end of
append(String str)
this string.
Insert specified string at the offset indicated
insert(int offset, String str)
position.
Replace the substring of the string builder
replace(int startIndex, int endIndex, String str) from startIndex to endIndex-1 with
specified string.
delete the substring of the string builder
delete(int startIndex, int endIndex)
from startIndex to endIndex-1.
replace the string builders character
reverse()
sequence by reverse character sequence.
returns the current capacity of string
capacity()
builder. Capacity refers to the amount of
available storage.
ensures that the capacity is at least equal to
ensureCapacity(int minCapacity)
the specified minimum.

append(String str) StringBuilder method in java


append(String str): append the specified string at the end of this string.
Syntax: public StringBuilder append(String str).

Note: if specified string is null than it append null string at the end.
If append has object, int, double etc as an argument than argument value first converted into string using
String.valueOf()before appending.
Example:
StringBuilderAppendExample.java
/**
* This program is used to show the use of append() method.
* @author javawithease
*/
class TestStringBuilder{
StringBuilder sb = new StringBuilder("Hello ");
/**
* This method is used to show the use of append() method.
* @author javawithease
*/
public void appendTest(){
//concatenate the argument string
//at the end of this string.
System.out.println(sb.append("www.javawithease.com"));
}
}
public class StringBuilderAppendExample {
public static void main(String args[]){
//creating TestStringBuilder object
TestStringBuilder obj = new TestStringBuilder();
//method call
obj.appendTest();
}
}
Output:
Hello www.javawithease.com
Download this example.
insert(int offset, String str) StringBuilder method in java
insert(int offset, String str): insert specified string at the offset indicated position.
Syntax: public StringBuilder insert(int offset, String str).
Note: if specified string is null than it insert null string at the offset indicated position.
If insert has object, int, double etc instead of string than argument value first converted into string using
String.valueOf()before inserting.
Offset should be between 0 to length of string, if it is not StringIndexOutOfBoundsException will be thrown.
Example:
StringBuilderInsertExample.java

/**
* This program is used to show the use of insert() method.
* @author javawithease
*/
class TestStringBuilder{
StringBuilder sb = new StringBuilder("www.com");
/**
* This method is used to show the use of insert() method.
* @author javawithease
*/
public void insertTest(){
//insert specified string at
//the offset indicated position.
System.out.println(sb.insert(3,".javawithease"));
}
}
public class StringBuilderInsertExample {
public static void main(String args[]){
//creating TestStringBuilder object
TestStringBuilder obj = new TestStringBuilder();
//method call
obj.insertTest();
}
}
Output:
www.javawithease.com
Download this example.

replace(int startIndex, int endIndex, String str) StringBuilder method in java


replace(int startIndex, int endIndex, String str): replace the substring of the string builder from startIndex to
endIndex-1 with specified string.
Syntax: public StringBuilder replace(int startIndex, int endIndex, String str).
Note: startIndex should be between 0 to length of string or less than endIndex, if it is not
StringIndexOutOfBoundsException will be thrown.
Example:
StringBuilderReplaceExample.java
/**
* This program is used to show the use of replace() method.
* @author javawithease
*/
class TestStringBuilder{
StringBuilder sb = new StringBuilder("www.abc.com");

/**
* This method is used to show the use of replace() method.
* @author javawithease
*/
public void replaceTest(){
//replace the substring of the string buffer from
//startIndex to endIndex-1 with specified string.
System.out.println(sb.replace(4,7,"javawithease"));
}
}
public class StringBuilderReplaceExample {
public static void main(String args[]){
//creating TestStringBuilder object
TestStringBuilder obj = new TestStringBuilder();
//method call
obj.replaceTest();
}
}
Output:
www.javawithease.com
Download this example.
delete(int startIndex, int endIndex) StringBuilder method in java
delete(int startIndex, int endIndex): delete the substring of the string builder from startIndex to endIndex-1.
Syntax: public StringBuilder delete(int startIndex, int endIndex).
Note: startIndex should be between 0 to length of string or less than endIndex, if it is not
StringIndexOutOfBoundsException will be thrown.
Example:
StringBuilderDeleteExample.java
/**
* This program is used to show the use of delete() method.
* @author javawithease
*/
class TestStringBuilder{
StringBuilder sb =
new StringBuilder("Hello www.javawithease.com");
/**
* This method is used to show the use of delete() method.
* @author javawithease
*/
public void deleteTest(){
//delete the substring of the string
//buffer from startIndex to endIndex-1.
System.out.println(sb.delete(0,6));

}
}
public class StringBuilderDeleteExample {
public static void main(String args[]){
//creating TestStringBuilder object
TestStringBuilder obj = new TestStringBuilder();
//method call
obj.deleteTest();
}
}
Output:
www.javawithease.com
Download this example.
reverse() StringBuilder method in java
reverse(): replace the string builders character sequence by reverse character sequence.
Syntax: public StringBuilder reverse().
Example:
StringBuilderReverseExample.java
/**
* This program is used to show the use of reverse() method.
* @author javawithease
*/
class TestStringBuilder{
StringBuilder sb =
new StringBuilder("www.javawithease.com");
/**
* This method is used to show the use of reverse() method.
* @author javawithease
*/
public void reverseTest(){
//replace the string buffers character
//sequence by reverse character sequence.
System.out.println(sb.reverse());
}
}
public class StringBuilderReverseExample {
public static void main(String args[]){
//creating TestStringBuilder object
TestStringBuilder obj = new TestStringBuilder();
//method call
obj.reverseTest();
}
}

Output:
moc.esaehtiwavaj.www
Download this example.
capacity() StringBuilder method in java
capacity(): returns the current capacity of string builder. Capacity refers to the amount of available storage.
Syntax: public int capacity().
Example:
StringBuilderCapacityExample.java
/**
* This program is used to show the use of capacity() method.
* @author javawithease
*/
class TestStringBuilder{
StringBuilder sb = new StringBuilder();
/**
* This method is used to show the use of capacity() method.
* @author javawithease
*/
public void capacityTest(){
//default capacity.
System.out.println(sb.capacity());
sb.append("Hello ");
//current capacity 16.
System.out.println(sb.capacity());
sb.append("www.javawithease.com");
//current capacity (16*2)+2=34 i.e (oldcapacity*2)+2.
System.out.println(sb.capacity());
}
}
public class StringBuilderCapacityExample {
public static void main(String args[]){
//creating TestStringBuilder object
TestStringBuilder obj = new TestStringBuilder();
//method call
obj.capacityTest();
}
}
Output:
16
16
34

Download this example.

ensureCapacity(int minCapacity) StringBuilder method in java


ensureCapacity(int minCapacity): ensures that the capacity is at least equal to the specified minimum.
Syntax: public void ensureCapacity(int minCapacity).
Note:
1. If current capacity is greater than the argument there will be no change in the current capacity.
2. If current capacity is less than the argument there will be change in the current capacity using below rule.
newcapacity = (oldcapacity*2) + 2.
Example:
StringBufferEnsureCapacityExample.java
/**
* This program is used to show the use of ensureCapacity() method.
* @author javawithease
*/
class TestStringBuilder{
StringBuilder sb = new StringBuilder();
/**
* This method is used to show the
* use of ensureCapacity() method.
* @author javawithease
*/
public void ensureCapacityTest(){
//default capacity.
System.out.println(sb.capacity());
sb.append("Hello ");
//current capacity 16.
System.out.println(sb.capacity());
sb.append("www.javawithease.com");
//current capacity (16*2)+2=34 i.e (oldcapacity*2)+2.
System.out.println(sb.capacity());
sb.ensureCapacity(10);
//now no change in capacity because
//minimum is already set to 34.
System.out.println(sb.capacity());
sb.ensureCapacity(50);
//now (34*2)+2 = 70 as 50 is greater than 34.
System.out.println(sb.capacity());
}
}
public class StringBufferEnsureCapacityExample {

public static void main(String args[]){


//creating TestStringBuilder object
TestStringBuilder obj = new TestStringBuilder();
//method call
obj.ensureCapacityTest();
}
}

Output:
16
34
34
70
Download this example.
StringTokenizer in java
StringTokenizer class is used to break a string into tokens using specified delimiter.
Note: space is the default delimiter.
Constructors of StringTokenizer class:
1. public StringTokenizer(String str): creates a string tokenizer for the specified string. By default space is taken as
delimiter here.
2. public StringTokenizer(String str, String delimiter): creates a string tokenizer for the specified string by using
specified delimiter. Delimiter character will be treated as separator only and not be treated as tokens.
3. public StringTokenizer(String str, String delimiter, boolean returnDelimiters): creates a string tokenizer for the
specified string by using specified delimiter. Delimiter character can be treated as separator returnDelimiters is true.
Commonly used methods of StringTokenizer:
1. hasMoreTokens(): checks whether more tokens are available or not. It returns true if more takens are available else
return false.
Syntax: public boolean hasMoreTokens().
2. hasMoreElements(): same as hasMoreTokens() , mainly used in case of enumeration.
Syntax: public boolean hasMoreElements().
3. nextToken(): returns the next token from this string tokenizer.
Note: It will throw NoSuchElementException if no more token is available.
Syntax: public String nextToken().

4. nextToken(String delimiter): returns the next token from this string tokenizer using specified delimeter.It is mainly
used when we want to separate tokens using differen delimiters in single string tokenizer.
Syntax: public String nextToken(String delim).
Note: It will throw NoSuchElementException if no more token is available.
5. nextElement(): same as nextToken() except that it returns an object rather than string. It is mainly used in case of
enumeration.
Syntax: public Object nextElement().
Note: It will throw NoSuchElementException if no more token is available.
6. countTokens(): returns the number of times nextToken method can be called on this string tokenizer before an
exception occur.
Syntax: public int countTokens().
Example 1:
StringTokenizerExample.java
import java.util.StringTokenizer;
/**
* This program is used to print all tokens of a string.
* @author javawithease
*/
class TestStringTokenizer{
//By default whitespace will act as separator.
StringTokenizer str = new StringTokenizer("Hello i am here");
/**
* This method is used to print all tokens of a string.
* @author javawithease
*/
public void displayTokens(){
while(str.hasMoreTokens()){
System.out.println(str.nextToken());
}
}
}
public class StringTokenizerExample {
public static void main(String args[]){
//creating TestStringTokenizer object.
TestStringTokenizer obj = new TestStringTokenizer();
//method call
obj.displayTokens();
}
}
Output:

Hello
i
am
here
Download this example.
Example 2:
StringTokenizerExample.java
import java.util.StringTokenizer;
/**
* This program is used to print all tokens
* of a string on the bases of comma.
* @author javawithease
*/
class TestStringTokenizer{
//Using comma as separator.
StringTokenizer str =
new StringTokenizer("Hello ,i ,am ,here", ",");
/**
* This method is used to print all tokens
* of a string on the bases of comma.
* @author javawithease
*/
public void displayTokens(){
while(str.hasMoreTokens()){
System.out.println(str.nextToken());
}
}
}
public class StringTokenizerExample {
public static void main(String args[]){
//creating TestStringTokenizer object.
TestStringTokenizer obj = new TestStringTokenizer();
//method call
obj.displayTokens();
}
}
Output:
Hello
i
am
here
Download this example.
Example 3:
StringTokenizerExample.java

import java.util.StringTokenizer;
/**
* This program is used to print all tokens of
* a string on the bases of multiple separators.
* @author javawithease
*/
class TestStringTokenizer{
//Using multiple separators.
StringTokenizer str =
new StringTokenizer("Hello ,i ;am :here", ", ; :");
/**
* This method is used to print all tokens of
* a string on the bases of multiple separators.
* @author javawithease
*/
public void displayTokens(){
while(str.hasMoreTokens()){
System.out.println(str.nextToken());
}
}
}
public class StringTokenizerExample {
public static void main(String args[]){
//creating TestStringTokenizer object.
TestStringTokenizer obj = new TestStringTokenizer();
//method call
obj.displayTokens();
}
}
Output:
Hello
i
am
here
Download this example.
Some important terms for exception handling
Exception:
Exception refers to an exceptional event. Exception is an event that disrupts the normal flow of the program, during
program execution.
Exception object:
When an error occurs within a method, the method creates an object and hands it to the runtime system. This object is
known as exception object. It contains the information of the error.
Throwing an exception:
It is a process of handing an exception object to the runtime system.
Catch the exception:
It is a process of finding something which can handle exception object.
Exception handler:
It is a block of code that can handle the exception is known as exception handler.
Exception handling in java

Exceptional handling:
Exception handling is a mechanism to handle runtime errors, so that normal flow of the program can be maintained.
Exception Hierarchy:
Throwable is the super class.

Advantages/Benefits of exceptional handling:


1.
2.
3.

1. Using exceptional handling we can separate the error handling code from normal code.
2. Using exceptional handling we can differentiate the error types.
3. Normal flow of program can be maintained.
Types of Exception:

1.
2.
3.

1. Checked exception.
2. Unchecked exception.
3. Error.
Checked exceptions:
Checked exceptions are those exceptional conditions that are checked by compiler at the compile time. A checked
exception forces you to either use try-catch or throws. All exceptions except Error, RuntimeException, and their
subclasses are checked exceptions.
e.g. IOException, SQLException etc.
Unchecked exceptions:

Unchecked exceptions are those exceptional conditions that are not checked by compiler at the compile time. Unchecked
exceptions are checked at runtime. An unchecked exception not forces you to either use try-catch or throws.
RuntimeException and their subclasses are unchecked exceptions. This Exception can be avoided by programmer.
e.g. NullPointerException, ArithmeticException etc.
Error:
Errors are those exceptional conditions that are not checked by compiler at the compile time. Errors are checked at
runtime. An error not forces you to either use try-catch or throws. Error and their subclasses are represents errors. Error
cant be avoided by programmer, it is irrecoverable.
e.g. OutOfMemoryError etc.

How to write an exception handler?


To write a simple exception handler, first enclose the code that might throw an exception within try block. When an
exception occurs in try block, it will be handled by an appropriate exception handler. Exception handler can associate
with try block by using catch block or finally block after it.
Note: catch and finally block both can be attached with single try block. Hierarchy should be try-catch-finally.
To understand more, let us see the keywords used in exception handling.
1.
2.
3.
4.
5.

1. try
2. catch
3. finally
4. throw
5. throws
try and catch blocks in java
try block :
try block is used to enclose the code that might throw an exception. It must be followed by either catch or finally or both
blocks.
Syntax of try block with catch block:
try{
//block of statements
}catch(Exception handler class){

Syntax of try block with finally block:


try{
//block of statements
} finally {
}

Syntax of try block with catch and finally block:


try{
//block of statements
}catch(Exception handler class){
}finally{
}

catch block:
Catch block is used for exception handler. It is used after try block.
Syntax :
try{
//block of statements
}catch(Exception handler class){
}

Problem without exception handling.


ExceptionHandlingExample1.java
/**
* This is a simple program which result
* into java.lang.ArithmeticException.
* @author javawithease

*/
class ArithmaticTest{
/**
* This method is used to divide two integers.
* @param num1
* @param num2
*/
public void division(int num1, int num2){
//java.lang.ArithmeticException here
//and remaining code will not execute.
int result = num1/num2;
//this statement will not execute.
System.out.println("Division = " + result);
}
}
public class ExceptionHandlingExample1 {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.division(20, 0);
}
}
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at com.javawithease.business.ArithmaticTest.division
(ExceptionHandlingExample1.java:15)
at com.javawithease.business.ExceptionHandlingExample1.main
(ExceptionHandlingExample1.java:27)
Download this example.
Solution of the above problem using exception handling.
ExceptionHandlingExample2.java
/**
* This is a simple program of handling
* java.lang.ArithmeticException.
* @author javawithease
*/
class ArithmaticTest{
/**
* This method is used to divide two integers.
* @param num1
* @param num2
* @author javawithease
*/
public void division(int num1, int num2){
try{
//java.lang.ArithmeticException here.
System.out.println(num1/num2);
//catch ArithmeticException here.

}catch(ArithmeticException e){
//print exception.
System.out.println(e);
}
System.out.println("Remaining code after exception handling.");
}
}
public class ExceptionHandlingExample2 {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.division(20, 0);
}
}
Output:
java.lang.ArithmeticException: / by zero
Remaining code after exception handling.
Download this example.
Multiple catch blocks in java
Multiple catch blocks:
If more than one exception can occur in one try block, than we can use multiple catch blocks to provide appropriate
handler to different exception objects.
Note: in case of multiple catch blocks, blocks must be placed from specific handler to general handler.
Syntax of try block with multiple catch blocks:
try{
//block of statements
}catch(Exception handler class subclass ){
} catch(Exception handler super class){
}

Example:
MultipleCatchExample.java

/**
* This is a simple program of handling multiple exception.
* @author javawithease
*/
class ArithmaticTest{
int array[]={10,20,30,40};
int num1 = 50;
int num2 = 10;
/**
* This method is used to show the handling multiple exception.
* @author javawithease
*/
public void multipleCatchTest(){
try{
//java.lang.ArithmeticException here if num2 = 0.
System.out.println(num1/num2);
System.out.println("4th element of given array = " + array[3]);
//ArrayIndexOutOfBoundsException here.
System.out.println("5th element of given array = " + array[4]);
//catch ArrayIndexOutOfBoundsException here.
}catch(ArrayIndexOutOfBoundsException e){
//print exception.
System.out.println(e);
}catch(ArithmeticException e){//catch ArithmeticException here.
//print exception.
System.out.println(e);
}catch(Exception e){//catch exception here.
//print exception.
System.out.println(e);
}
System.out.println("Remaining code after exception handling.");
}
}
public class MultipleCatchExample {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.multipleCatchTest();
}
}
Output:
5
4th element of given array = 40
java.lang.ArrayIndexOutOfBoundsException: 4
Remaining code after exception handling.
Download this example.
Compile time error if catch blocks are not placed from specific handler to general
handler.

Example:
ExceptionHandlingExample.java
/**
* This is a simple program used to show
* the handling multiple exception.
* @author javawithease
*/
class ArithmaticTest{
int array[]={10,20,30,40};
int num1 = 50;
int num2 = 10;
/**
* This method is used to show the handling multiple exception.
* @author javawithease
*/
public void multipleCatchTest(){
try{
//java.lang.ArithmeticException here if num2 = 0.
System.out.println(num1/num2);
System.out.println("4th element of given array = " + array[3]);
//ArrayIndexOutOfBoundsException here.
System.out.println("5th element of given array = " + array[4]);
}catch(Exception e){//catch exception here.
//print exception.
System.out.println(e);
//Compile time error here.
}catch(ArrayIndexOutOfBoundsException e){
//print exception.
System.out.println(e);
}catch(ArithmeticException e){//catch ArithmeticException here.
//print exception.
System.out.println(e);
}
System.out.println("Remaining code after exception handling.");
}
}
public class ExceptionHandlingExample {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.multipleCatchTest();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problems:
Unreachable catch block for ArrayIndexOutOfBoundsException.
It is already handled by the catch block for Exception
Unreachable catch block for ArithmeticException.

It is already handled by the catch block for Exception


at com.javawithease.business.ArithmaticTest.multipleCatchTest
(ExceptionHandlingExample.java:28)
at com.javawithease.business.ExceptionHandlingExample.main
(ExceptionHandlingExample.java:46)
Download this example.
Nested try block in java
Nested try block:
try block inside try block is known as nested try block.
Note: Exception handler must be also nested in case try block is nested.
Syntax of nested try block:
try{

//block of statements

try{
//block of statements
}catch(Exception handler class){
}
}catch(Exception handler class){
}

Example:
NestedTryExample.java
/**
* This is a simple program used to show
* the use of nested try block.
* @author javawithease
*/
class ArithmaticTest{
int array[]={10,20,30,40};
int num1 = 50;
int num2 = 10;
/**
* This method is used to show the use of nested try block.
* @author javawithease
*/
public void multipleCatchTest(){
try{
try{

//java.lang.ArithmeticException here if num2 = 0.


System.out.println(num1/num2);
System.out.println("4th element of given array = " + array[3]);
//ArrayIndexOutOfBoundsException here.
System.out.println("5th element of given array = " + array[4]);
//Compile time error here.
}catch(ArrayIndexOutOfBoundsException e){
//print exception.
System.out.println(e);
}catch(ArithmeticException e){//catch ArithmeticException here.
//print exception.
System.out.println(e);
}
int num = Integer.parseInt("30");
System.out.println(num);
//catch NumberFormatException here.
}catch(NumberFormatException e){
//print exception.
System.out.println(e);
}
System.out.println("Remaining code after exception handling.");
}
}
public class NestedTryExample {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.multipleCatchTest();
}
}
Output:
5
4th element of given array = 40
java.lang.ArrayIndexOutOfBoundsException: 4
30
Remaining code after exception handling.
Download this example.
Finally in java
finally:
finally block is mainly used to do clean-up task. It is always executed even when no exception occur. It will not execute
only in case program exits using System.exit() or because of some fatal error cause program to abort. It is followed by
either catch or try block.

Note: A try block can have one or more catch block associated with it, but only one finally block can be associates with
it.
Syntax of finally without catch:
try{
//block of statements
}finally{
}

Syntax of finally with catch:


try{
//block of statements
}catch(){
}finally{
}

Example: finally block when exception occur and handled.


FinallyExceptionExample2.java
/**
* This program used to show the use of finally block
* when exception occur and handled.
* @author javawithease
*/
class ArithmaticTest{
/**
* This method is used to divide two integers.
* @param num1
* @param num2
* @author javawithease
*/
public void division(int num1, int num2){
try{
//java.lang.ArithmeticException here.
System.out.println(num1/num2);
//catch ArithmeticException here.
}catch(ArithmeticException e){
//print exception.
System.out.println(e);
}finally{//It will always execute.
System.out.println("Finally will always execute.");
}

System.out.println("Remaining code after exception handling.");


}
}
public class FinallyExceptionExample2 {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.division(20, 0);
}
}
Output:
java.lang.ArithmeticException: / by zero
Finally will always execute.
Remaining code after exception handling.
Download this example.
Example: finally block when exception occur but not handled.
FinallyExceptionExample3.java
/**
* This program used to show the use of finally block
* when exception occur but not handled.
* @author javawithease
*/
class ArithmaticTest{
/**
* This method is used to divide two integers.
* @param num1
* @param num2
* @author javawithease
*/
public void division(int num1, int num2){
try{
//java.lang.ArithmeticException here.
System.out.println(num1/num2);
}finally{//It will always execute.
System.out.println("Finally will always execute.");
}
System.out.println("Remaining code after exception handling.");
}
}
public class FinallyExceptionExample3 {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.division(20, 0);
}

}
Output:
Finally will always execute.
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at com.javawithease.business.ArithmaticTest.division
(FinallyExceptionExample3.java:17)
at com.javawithease.business.FinallyExceptionExample3.main
(FinallyExceptionExample3.java:32)
Download this example.
Example: finally block when no exception occur.
FinallyExceptionExample1.java
/**
* This program used to show the use of finally block
* when no exception occur.
* @author javawithease
*/
class ArithmaticTest{
/**
* This method is used to divide two integers.
* @param num1
* @param num2
* @author javawithease
*/
public void division(int num1, int num2){
try{
//java.lang.ArithmeticException here.
System.out.println(num1/num2);
//catch ArithmeticException here.
}catch(ArithmeticException e){
//print exception.
System.out.println(e);
}finally{//It will always execute.
System.out.println("Finally will always execute.");
}
System.out.println("Remaining code after exception handling.");
}
}
public class FinallyExceptionExample1 {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.division(20, 10);
}
}
Output:

2
Finally will always execute.
Remaining code after exception handling.
Download this example.
throw keyword in java
throw:
throw is used to throw an exception object explicitly. It can take only one argument and that will be an exception object.
Exception object to be thrown can be of either checked or unchecked exception type.
Syntax:
throw exception_object;
Example:
ExceptionThrowExample.java
/**
* This program used to show the use of throw exception.
* @author javawithease
*/
class ArithmaticTest{
/**
* This method is used to divide two integers.
* @param num1
* @param num2
* @author javawithease
*/
public void division(int num1, int num2){
try{
//java.lang.ArithmeticException here.
System.out.println(num1/num2);
//catch ArithmeticException here.
}catch(ArithmeticException e){
//throw exception.
throw e;
}
System.out.println("Remaining code after exception handling.");
}
}
public class ExceptionThrowExample {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.division(20, 0);
}
}

Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at com.javawithease.business.ArithmaticTest.division
(ExceptionThrowExample.java:17)
at com.javawithease.business.ExceptionThrowExample.main
(ExceptionThrowExample.java:33)
Download this example.
throws keyword in java
throws:
throws is used to throw an exception object implicitly. It is used with the method signature. More than one type of
exception can be declared with method signature, they should be comma separated.
Note:
1.
2.
3.

1. throws is mainly used to throw checked exception.


2. If you are calling a method that declares an exception, you must either caught or declare the exception.
3. We can rethrow the exception.
Syntax:
methodName () throws comma separated list of exceptionClassNames{}
Example:
ExceptionThrowsExample.java
/**
* This program used to show the use of throws exception.
* @author javawithease
*/
class ArithmaticTest{
/**
* This method is used to divide two integers.
* @param num1
* @param num2
* @author javawithease
*/
public void division(int num1, int num2)
throws ArithmeticException{
//java.lang.ArithmeticException here.
System.out.println(num1/num2);
}
public void method1(int num1, int num2) throws Exception{
division(num1, num2);
}
public void method2(int num1, int num2){
try{
method1(num1, num2);
}catch(Exception e){

System.out.println("Exception Handled");
}
}
}
public class ExceptionThrowsExample {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.method2(20, 0);
}
}
Output:
Exception Handled
Download this example.
Difference between throw and throws.
throw keyword
throws keyword
1. Used to explicitly throw an exception.
1. Used to implicitly throw an exception.
2. Only unchecked exception can propagate Both checked and unchecked exception can
using throw.
propagate using throws.
3. Used within the method.
3. Used with the method signature.
4. Cannot throw multiple exceptions.
4. Can declare multiple exceptions.
Exception propagation in java
Exception propagation:
Exception propagation is a way of propagating exception from method to method. Let an exception occur in a method at
the top of the call stack and if it is not caught then it propagates to previous method in the call stack, if it is not caught
here then it again propagates to previous method in the call stack and so on until either it is caught or reach the bottom of
the stack.
Example: Exception propagation in case of unchecked exception.
ExceptionPropagationExample1.java
/**
* This program used to show the use of
* unchecked exception propagation.
* @author javawithease
*/
class ArithmaticTest{
/**
* This method is used to divide two integers.
* @param num1
* @param num2
* @author javawithease
*/

public void division(int num1, int num2) {


//java.lang.ArithmeticException here
//and not caught hence propagate to method1.
System.out.println(num1/num2);
}
public void method1(int num1, int num2) {
//not caught here and hence propagate to method2.
division(num1, num2);
}
public void method2(int num1, int num2){
try{
method1(num1, num2);
}catch(Exception e){//caught exception here.
System.out.println("Exception Handled");
}
}
}
public class ExceptionPropagationExample1 {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.method2(20, 0);
}
}
Output:
Exception Handled
Download this example.
Example: Exception propagation in case of checked exception.
Note: Checked exceptions are not propagated in exception change.
ExceptionPropagationExample2.java
import java.io.IOException;
/**
* This program used to show the use of
* checked exception propagation.
* @author javawithease
*/
class Test{
public void method3() {
//compile time error here because
//checked exceptions can't be propagated.
throw new IOException();
}
public void method1(){

method3();
}
public void method2(){
try{
method1();
}catch(Exception e){
System.out.println("Exception Handled");
}
}
}
public class ExceptionPropagationExample2 {
public static void main(String args[]){
//creating Test object
Test obj = new Test();
//method call
obj.method2();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Unhandled exception type IOException
at com.javawithease.business.Test.method3
(ExceptionPropagationExample2.java:13)
at com.javawithease.business.Test.method1
(ExceptionPropagationExample2.java:17)
at com.javawithease.business.Test.method2
(ExceptionPropagationExample2.java:22)
at com.javawithease.business.ExceptionPropagationExample2.main
(ExceptionPropagationExample2.java:35)
Download this example.
Exception handling with method overriding in java
If the super class method does not declare an exception then subclass overridden method cannot declare the checked
exception but it can declare unchecked exception.
If the super class method declares an exception then subclass overridden method can declare same exception, subclass
exception or no exception but cannot declare parent exception of the exception thrown by super class method.
Example: If the super class method does not declare an exception then subclass overridden
method cannot declare the checked exception.
ExceptionHandlingInOverriding1.java
import java.io.IOException;
/**
* This program is used to show that If
* the super class method does not declare

* an exception then subclass overridden


* method cannot declare the checked exception
* @author javawithease
*/
class SuperClass{
public void display(){
System.out.println("Super class.");
}
}
class SubClass extends SuperClass {
//Compile time error here.
public void display() throws IOException{
System.out.println("Sub class.");
}
}
public class ExceptionHandlingInOverriding1 {
public static void main(String args[]){
//Creating subclass object.
SuperClass obj = new SubClass();
//method call.
obj.display();
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Exception IOException is not compatible with
throws clause in SuperClass.display()
Download this example.
Example: If the super class method does not declare an exception then subclass overridden
method can declare unchecked exception.
ExceptionHandlingInOverriding2.java
/**
* This program is used to show that
* If the super class method does not declare
* an exception then subclass overridden
* method can declare the unchecked exception
* @author javawithease
*/
class SuperClass{
public void display(){
System.out.println("Super class.");
}
}
class SubClass extends SuperClass {
//No Compile time error here.
public void display() throws ArithmeticException{

System.out.println("Sub class.");
}
}
public class ExceptionHandlingInOverriding2 {
public static void main(String args[]){
//Creating subclass object.
SuperClass obj = new SubClass();
//method call.
obj.display();
}
}
Output:
Sub class.
Download this example.
Example: If the super class method declares an exception then subclass overridden method can
declare same exception.
ExceptionHandlingInOverriding3.java
/**
* This program is used to show that
* If the super class method declares
* an exception then subclass overridden
* method can declare same exception.
* @author javawithease
*/
class SuperClass{
public void display()throws ArithmeticException{
System.out.println("Super class.");
}
}
class SubClass extends SuperClass {
//can declare same exception.
public void display() throws ArithmeticException{
System.out.println("Sub class.");
}
}
public class ExceptionHandlingInOverriding3 {
public static void main(String args[]){
//Creating subclass object.
SuperClass obj = new SubClass();
//method call.
try {
obj.display();
} catch (Exception e) {
System.out.println(e);
}
}
}

Output:
Sub class.
Download this example.
Example: If the super class method declares an exception then subclass overridden method can
declare subclass exception.
ExceptionHandlingInOverriding4.java
/**
* This program is used to show that
* If the super class method declares
* an exception then subclass overridden
* method can declare sub class exception.
* @author javawithease
*/
class SuperClass{
public void display()throws Exception{
System.out.println("Super class.");
}
}
class SubClass extends SuperClass {
//can declare same exception.
public void display() throws ArithmeticException{
System.out.println("Sub class.");
}
}
public class ExceptionHandlingInOverriding4 {
public static void main(String args[]){
//Creating subclass object.
SuperClass obj = new SubClass();
//method call.
try {
obj.display();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Sub class.
Download this example.
Example: If the super class method declares an exception then subclass overridden method can
declare no exception.
ExceptionHandlingInOverriding5.java

/**
* This program is used to show that
* If the super class method declares
* an exception then subclass overridden
* method can declare with no exception.
* @author javawithease
*/
class SuperClass{
public void display()throws Exception{
System.out.println("Super class.");
}
}
class SubClass extends SuperClass {
//can declare with no exception.
public void display(){
System.out.println("Sub class.");
}
}
public class ExceptionHandlingInOverriding5 {
public static void main(String args[]){
//Creating subclass object.
SuperClass obj = new SubClass();
//method call.
try {
obj.display();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Sub class.
Download this example.
Example: If the super class method declares an exception then subclass overridden method
cannot declare parent exception.
ExceptionHandlingInOverriding6.java
/**
* This program is used to show that
* If the super class method declares
* an exception then subclass overridden
* method cannot declare parent exception.
* @author javawithease
*/
class SuperClass{
public void display()throws ArithmeticException{
System.out.println("Super class.");
}

}
class SubClass extends SuperClass {
//Compile time error here.
public void display() throws Exception{
System.out.println("Sub class.");
}
}
public class ExceptionHandlingInOverriding6 {
public static void main(String args[]){
//Creating subclass object.
SuperClass obj = new SubClass();
//method call.
try {
obj.display();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Exception Exception is not compatible with
throws clause in SuperClass.display()
Download this example.
Custom exception in java
Custom exception:
You can define your own exception also. These exceptions are known as custom exceptions.
Note:
1. For writing custom checked exception, extend Exception class.
2. For writing custom unchecked exception, extend RuntimeException class.
Example:
CustomExceptionExample.java
/**
* This program is used to create custom exception.
* @author javawithease
*/
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
class Test{

public void display() throws MyException {


throw new MyException("This is a custom exception.");
}
}
public class CustomExceptionExample {
public static void main(String args[]){
//creating Test object.
Test obj = new Test();
//method call.
try{
obj.display();
}catch(Exception e){
System.out.println(e);
}
}
}
Output:
com.javawithease.business.MyException: This is a custom exception.
Download this example.
Commonly used exception methods of Throwable class in java
1. getMessage(): returns the message string about the exception.
Syntax: public String getMessage()
2. getCause(): returns the cause of the exception. It will return null is cause is unknown or non-existent.
Syntax : public Throwable getCause()
3. toString(): returns a short description of the exception.
Discription of the exception = class name + : + message.
Syntax: public String toString()
4. printStackTrace(): prints the short description of the exception(using toString()) + a stack trace for this exception on
the error output stream(System.err).
Syntax: public void printStackTrace(PrintStream s)
Example:
ExceptionHandlingExample.java
/**
* This program is used to show the use
* of Commonly used methods of Throwable class.
* @author javawithease

*/
class ArithmaticTest{
/**
* This method is used to divide two integers.
* @param num1
* @param num2
* @author javawithease
*/
public void division(int num1, int num2){
try{
//java.lang.ArithmeticException here.
System.out.println(num1/num2);
//catch ArithmeticException here.
}catch(ArithmeticException e){
//print the message string about the exception.
System.out.println("getMessage(): " + e.getMessage());
//print the cause of the exception.
System.out.println("getCause(): " + e.getCause());
//print class name + : + message.
System.out.println("toString(): " + e.toString());
System.out.println("printStackTrace(): ");
//prints the short description of the exception
//+ a stack trace for this exception.
e.printStackTrace();
}
}
}
public class ExceptionHandlingExample {
public static void main(String args[]){
//creating ArithmaticTest object
ArithmaticTest obj = new ArithmaticTest();
//method call
obj.division(20, 0);
}
}
Output:
getMessage(): / by zero
getCause(): null
toString(): java.lang.ArithmeticException: / by zero
printStackTrace():
java.lang.ArithmeticException: / by zero
at com.javawithease.business.ArithmaticTest.division
(ExceptionHandlingExample.java:17)
at com.javawithease.business.ExceptionHandlingExample.main
(ExceptionHandlingExample.java:38)
Download this example.
Multithreading in java
Multitasking:
Multitasking is a way of executing multiple tasks during the same period of time. Multiple tasks use common resources
like CPU and main memory.

With a single CPU only one task can be running at one point of time, so CPU uses context switching to perform
multitasking. Context switch (Context means state) is the process of storing and restoring the state of a process so that
execution can be resumed from the same point at a later time.
Types of Multitasking:
1. Multiprocessing.
2. Multithreading.

Multiprocessing:
Multiprocessing is a type of multitasking based upon processes i.e. context switching is done in-between processes.
Process:
A process has a self-contained execution environment i.e. allocates separate memory area. Context switch time is more in
case of processes because switch is done between different memory areas.
Multithreading:
Multithreading is a type of multitasking based upon threads i.e. context switching is done in-between threads.
Thread:
A thread is a lightweight process. Thread uses processs execution environment i.e. memory area. Context switch time is
less in case of processes because switch is done within the same processs memory area.
Note: A thread cant be exist without process, it exist within the process.
Difference between process and thread in java:

1.
2.
3.
4.
5.

Process

Thread

1. Process has its own main memory for


execution.
2. Process is considered as heavyweight
component.
3. One process can have multiple threads.
4. Context switch time is more.
Thread life cycle in java
Thread life cycle:
1. New.
2. Runnable.
3. Running.
4. Blocked(Non-Runnable).
5. Dead.

1. Thread use processs main memory for


execution and share it with other threads.
2. Thread is considered as lightweight
component.
3. One thread cant have multiple process.
4. Context switch time is less.

Diagram:

1. New: A new thread is created but not working. A thread after creation and before invocation of start() method will be
in new state.
2. Runnable: A thread after invocation of start() method will be in runnable state. A thread in runnable state will be
available for thread scheduler.
3. Running: A thread in execution after thread scheduler select it, it will be in running state.
4. Blocked: A thread which is alive but not in runnable or running state will be in blocked state. A thread can be in
blocked state because of suspend(), sleep(), wait() methods or implicitly by JVM to perform I/O operations.
5. Dead: A thread after exiting from run() method will be in dead state. We can use stop() method to forcefully killed a
thread.
Way of creating thread in java
Way of creating thread:
1.
2.

1. By implementing Runnable interface.


2. By extending Thread class.
1. By implementing Runnable interface:
To create a thread using Runnable interface, create a class which implements Runnable interface. Runnable interface
have only one method run().
Syntax: public void run().
run() method will contain the code for created thread.
Now create a thread class object explicitly because our class is not extending thread class and hence its object cant be
treated as thread object. Pass class object that implements Runnable interface into thread class constructor to execute run
method.
Example:
CreateThreadExample1.java
/**
* This program is used to create thread using Thread class.

* @author javawithease
*/
class Test extends Thread{
public void run(){
System.out.println("thread started.");
}
}
public class CreateThreadExample1 {
public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
//start the thread.
thrd1.start();
}
}
Output:
thread started.
Download this example.
2. By extending Thread class:
Thread class provides methods to perform operations on threads.
Thread class is in Java.lang package.
Syntax: public class Thread extends Object implements Runnable.
Commonly used constructors of Thread class:
1. Thread().
2. Thread(Runnable target).
target the class object whose run method is invoked when this thread is started. If null, this threads run method is
invoked.
3. Thread(String name).
name the name of the new thread.
4. Thread(Runnable target, String name).
target the class object whose run method is invoked when this thread is started. If null, this threads run method is
invoked.
name the name of the new thread.
Example:
/**
* This program is used to create thread using Runnable interface.
* @author javawithease
*/
class Test implements Runnable{
public void run(){
System.out.println("thread started.");
}

}
public class CreateThreadExample2 {
public static void main(String args[]){
//creating Test object.
Test obj = new Test();
//creating thread
Thread thrd = new Thread(obj);
//start the thread.
thrd.start();
}
}
Output:
thread started.
Download this example.
Commonly used methods of Thread class
1. public void start()
starts thread to begin execution, JVM calls run method of this thread.
IllegalThreadStateException if the thread was already started.
2. public void run()
run method is used to perform operations by thread.
3. public final void setName(String name)
Changes the name of the thread.
name new name for this thread.
4. public final String getName()
Returns this threads name.
5. public final void setPriority(int newPriority)
Changes the priority of the thread.
IllegalArgumentException If the priority is not in the range MIN_PRIORITY to MAX_PRIORITY.
6. public final int getPriority()
Returns threads priority.
7. public final void join()
The current thread invokes this method on a second thread, causing the current thread to block until the second thread
terminates.
8. public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread
terminates or the specified number of milliseconds passes.
9. public final void setDaemon(boolean on)
Marks this thread as daemon thread if on is true.
10. public final boolean isDaemon()
Returns true if thread is daemon.
11. public final boolean isAlive()
returns true if thread is alive.
12. public long getId()
Returns the ID of the thread(A long number generated at the time of thread creation).
13. public void interrupt()
Interrupts this thread and causing it to continue execution if it was blocked.
14. public boolean isInterrupted()
Returns true if thread is interrupted else return false.
15. public static void dumpStack()
Prints a stack trace of the current thread.
16. public static void sleep(long millis)
Causes the currently executing thread to sleep for the specified number of milliseconds.

17. public static void yield()


Causes the currently executing thread object to temporarily pause and allow other threads to execute.
18. public static Thread currentThread()
Returns a reference to the currently running thread.
Thread Scheduling in java
Thread Scheduling:
Execution of multiple threads on a single CPU in some order is called thread scheduling.
What is the difference between preemptive scheduling and time slicing?
In case of preemptive scheduling the highest priority task executes until it enters the waiting or dead states or a higher
priority task comes into existence.
Time slicing: In case of time slicing a task executes for a predefined slice of time and then re-enters the pool of ready
tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Note: if run() method is called directly without calling start() method than program will execute without any error but
objects are treated as normal objects not thread objects.
Thread priority in java
Thread priority:
Thread priority represents a number between 1 to 10. It helps the operating system to determine the order in which
threads are scheduled.
Static fields for thread priority defined in Thread class:
1. public static final int MIN_PRIORITY
The minimum priority that a thread can have.
Default value : 1
2. public static final int NORM_PRIORITY
The default priority that is assigned to a thread.
Default value : 5
3. public static final int MAX_PRIORITY
The maximum priority that a thread can have.
Default value : 10
Example:
ThreadPriorityExample.java

/**
* This program is used to show the thread priority example.
* @author javawithease
*/
class Test extends Thread{
public void run(){
System.out.println("Priority of running thread: " +
Thread.currentThread().getPriority());
}
}
public class ThreadPriorityExample {
public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();
Test thrd3 = new Test();
//set thread priority.
thrd1.setPriority(Thread.MIN_PRIORITY);
thrd2.setPriority(Thread.NORM_PRIORITY);
thrd3.setPriority(Thread.MAX_PRIORITY);
//start the thread.
thrd1.start();
thrd2.start();
thrd3.start();
}
}
Output:
Priority of running thread: 1
Priority of running thread: 5
Priority of running thread: 10
Download this example.
Naming a thread in java
1. public final void setName(String name)
Changes the name of the thread.
name new name for this thread.
2. public final String getName()
Returns this threads name.
Example:
ThreadExample.java
/**
* This program is used to show the thread naming example.

* @author javawithease
*/
class Test extends Thread{
public void run(){
//Thread.currentThread()returns the current thread.
System.out.println("Id of running thread: " +
Thread.currentThread().getId() +
" Name of running thread: " +
Thread.currentThread().getName());
}
}
public class ThreadExample {
public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();
//set thread priority.
thrd1.setName("My Thread1");
thrd2.setName("My Thread2");
//start the thread.
thrd1.start();
thrd2.start();
}
}
Output:
Id of running thread: 9 Name of running thread: My Thread2
Id of running thread: 8 Name of running thread: My Thread1
Download this example.
Joining a thread in java
public final void join()
The current thread invokes this method on a second thread, causing the current thread to block until the second thread
terminates.
Example:
JoinThreadExample.java
/**
* This program is used to show the join() method example.
* @author javawithease
*/
class Test extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(600);
}catch(Exception e){
System.out.println(e);

}
System.out.println(i);
}
}
}
public class JoinThreadExample {
public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();
Test thrd3 = new Test();
thrd1.start();
try{
thrd1.join();
}catch(Exception e){
System.out.println(e);
}
thrd2.start();
thrd3.start();
}
}
Output:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
Download this example.
Daemon thread in java
Daemon thread:
Daemon threads are low priority threads which are act as a service provider for user threads. Life of a daemon thread is
depends upon the user threads. JVM automatically terminates daemon thread when all user threads are died. Daemon
threads are used for background supporting tasks.
Methods used for daemon threads:
1. public final void setDaemon(boolean on)

Marks this thread as daemon thread if on is true.


2. public final boolean isDaemon()
Returns true if thread is daemon.
Example:
DaemonThreadExample1.java
/**
* This program is used to show daemon thread example.
* @author javawithease
*/
class Test extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName() + " "
+ Thread.currentThread().isDaemon());
}
}
public class DaemonThreadExample1 {
public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();
//set names
thrd1.setName("My Thread1");
thrd2.setName("My Thread2");
//set thrd1 as daemon thread.
thrd1.setDaemon(true);
//start threads.
thrd1.start();
thrd2.start();
}
}
Output:
My Thread1 true
My Thread2 false
Download this example.
Example: After starting a thread it cant be set as daemon thread.
DaemonThreadExample2.java
/**
* This program is used to show that after starting a thread
* it can't be set as daemon thread.
* @author javawithease
*/

class Test extends Thread{


public void run(){
System.out.println(Thread.currentThread().getName() + " "
+ Thread.currentThread().isDaemon());
}
}
public class DaemonThreadExample2 {
public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();
//set names
thrd1.setName("My Thread1");
thrd2.setName("My Thread2");
//start thrd1.
thrd1.start();
//set thrd1 as daemon thread.
//java.lang.IllegalThreadStateException here.
thrd1.setDaemon(true);
//start thread2.
thrd2.start();
}
}
Output:
Exception in thread "main" My Thread1 false
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Unknown Source)
at com.javawithease.business.DaemonThreadExample2.main
(DaemonThreadExample2.java:30)
Download this example.
Can we start a thread twice?
No, A thread can never be started again after starting once. It will throw IllegalThreadStateException.
Example:
ThreadExample.java
/**
* This program is used to show that we can not start
* a thread which is already started.
* @author javawithease
*/
class Test extends Thread{
public void run(){
System.out.println("thread started.");
}
}

public class ThreadExample {


public static void main(String args[]){
//creating thread.
Test thrd = new Test();
//start the thread.
thrd.start();
//again start the thread which is already started.
//IllegalThreadStateException here.
thrd.start();
}
}
Output:
Exception in thread "main" thread started.
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at com.javawithease.business.ThreadExample.main
(ThreadExample.java:24)
Download this example.
Can we call run method directly?
Yes, we can call run method directly. Only difference is that when start method is called it creates a separate call stack for
that thread but in case when run method is called directly from main method it will not create a new call stack. Run
method is goes into current call stack.
Example:
ThreadExample.java
/**
* This program is used to show that
* we can call run method directly.
* @author javawithease
*/
class Test extends Thread{
public void run(){
System.out.println("thread started.");
}
}
public class ThreadExample {
public static void main(String args[]){
//creating thread.
Test thrd = new Test();
//call run method.
thrd.run();
}
}
Output:

thread started.
Download this example.
Difference between Thread.yield() and Thread.sleep() methods
yield():
Causes the currently executing thread object to temporarily pause for giving a chance to the remaining waiting threads of
the same priority to execute. If no such thread than same thread will continue its execution.
Syntax: public static void yield().
Example:
ThreadYieldExample.java
/**
* This program is used to show the yield() method example.
* @author javawithease
*/
class Test extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.yield();
}catch(Exception e){
System.out.println(e);
}
System.out.println(i);
}
}
}
public class ThreadYieldExample {
public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();
Test thrd3 = new Test();
//start threads.
thrd1.start();
thrd2.start();
thrd3.start();
}
}
Output:
1
2
3
4
5
1

2
3
4
1
2
3
4
5
5
Download this example.
sleep(long millis):
Causes the currently executing thread to sleep for the specified time as per our requirement.
Syntax: public static void sleep(long millis) .
Example:
ThreadSleepExample.java
/**
* This program is used to show the sleep() method example.
* @author javawithease
*/
class Test extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(600);
}catch(Exception e){
System.out.println(e);
}
System.out.println(i);
}
}
}
public class ThreadSleepExample {
public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();
Test thrd3 = new Test();
//start threads.
thrd1.start();
thrd2.start();
thrd3.start();
}
}
Output:
1
1

1
2
2
2
3
3
3
4
4
4
5
5
5
Download this example.
Deadlock in java
Deadlock:
when n threads are in waiting state in such a way that thread1 is waiting for some resource which is held by thread2 and
thread2 is waiting for some resource held by thread3 and so on thread n is waiting for some resources held by thread1,
this situation when all threads are in waiting state and no thread release the lock because it is also in waiting state is
known as deadlock.
Diagram:

Example:
DeadLockExample.java
/**
* This program is used to show deadlock situation in multithreading.
* @author javawithease
*/
public class DeadLockExample {
public static void main(String[] args) {

final String resource1 = "Amani";


final String resource2 = "Nidhi";
final String resource3 = "Prabhjot";
Thread thread1 = new Thread() {
public void run() {
//thread1 tries to lock on resource1.
synchronized (resource1) {
System.out.println("Thread1 locked resource1: " + resource1);
try {
Thread.sleep(500);
} catch (Exception e) {
System.out.println(e);
}
//thread1 tries to lock on resource2.
synchronized (resource2) {
System.out.println("Thread2 locked resource2: " + resource2);
}
//thread1 tries to lock on resource3.
synchronized (resource2) {
System.out.println("Thread2 locked resource3: " + resource3);
}
}
}
};
Thread thread2 = new Thread() {
public void run() {
//thread1 tries to lock on resource2.
synchronized (resource2) {
System.out.println("Thread1 locked resource2: " + resource2);
try {
Thread.sleep(500);
} catch (Exception e) {
System.out.println(e);
}
//thread1 tries to lock on resource1.
synchronized (resource1) {
System.out.println("Thread2 locked resource1: " + resource1);
}
//thread1 tries to lock on resource3.
synchronized (resource3) {
System.out.println("Thread2 locked resource3: " + resource3);
}
}
}
};
Thread thread3 = new Thread() {
public void run() {
//thread1 tries to lock on resource3.
synchronized (resource3) {
System.out.println("Thread1 locked resource3: " + resource3);
try {
Thread.sleep(500);

} catch (Exception e) {
System.out.println(e);
}
//thread1 tries to lock on resource1.
synchronized (resource1) {
System.out.println("Thread2 locked resource1: " + resource1);
}
//thread1 tries to lock on resource2.
synchronized (resource2) {
System.out.println("Thread2 locked resource2: " + resource2);
}
}
}
};
//start threads.
thread1.start();
thread2.start();
thread3.start();
}
}
Output:
Thread1 locked resource3: Prabhjot
Thread1 locked resource2: Nidhi
Thread1 locked resource1: Amani
Download this example.
Starvation in java
Starvation:
Starvation is a situation when a thread is in waiting state from long period because it not getting access of shared
resources or because higher priority threads are coming.
Example:
StarvationExample.java
/**
* This program is used to show the starvation problem.
* @author javawithease
*/
public class StarvationExample implements Runnable{
private final Object resource;
private final String message;
private final boolean fair;
public static void main(String[] args)
{
boolean fair = false;
if (args != null && args.length >= 1 && args[0].equals("fair")) {
fair = true;

}
// get the number of available CPUs, do twice as much threads.
final int cpus = Runtime.getRuntime().availableProcessors();
System.out.println("" + cpus + " available CPUs found");
final int runners = cpus * 2;
System.out.println("starting " + runners + " runners");
final Object resource = new Object();
// create sample runners and start them
for (int i = 1; i <= runners; i++) {
(new Thread(new StarvationExample(resource, String.valueOf(i), fair))).start();
}
// suspend main thread
synchronized (StarvationExample.class) {
try {
StarvationExample.class.wait();
} catch (InterruptedException ignored) {
}
}
}
public StarvationExample(Object resource, String message, boolean fair)
{
this.resource = resource;
this.message = message;
this.fair = fair;
}
public void run()
{
synchronized (this) {
for (;;) {
synchronized (resource) {
print(message);
try {
(fair ? resource : this).wait(100);
} catch (InterruptedException ignored) {
}
}
}
}
}
private static void print(String str)
{
synchronized (System.out) {
System.out.print(str);
System.out.flush();
}
}
}
Output:
4 available CPUs found
starting 8 runners

1222222222222222222222222222222222222222222222222222222222222222...
Download this example.
Inter-thread communication in java
Inter-thread communication:
Inter-thread communication is a process in which a thread is paused running in its critical region and another thread is
allowed to enter (or lock) in the same critical region to be executed. i.e. synchronized threads communicate with each
other.
Below object class methods are used for Inter-thread communication process:
1. wait(): this method instructs the current thread to release the monitor held by it and to get suspended until some other
threads sends a notification from the same monitor.
Syntax: public void wait() throws InterruptedException.
2. notify(): this method is used to send the notification to the thread that is suspended by the wait() method.
Syntax: public void notify().
3. notifyAll(): this method is used to send the notification to all the threads that are suspended by wait() method.
Syntax: public void notifyAll().
Producer-consumer problem to understand Inter-thread communication.
Example:
ProducerConsumerExample.java
/**
* This program is used to show the inter thread communication.
* @author javawithease
*/
class Buffer{
int a;
boolean produced = false;
public synchronized void produce(int x){
if(produced){
System.out.println("Producer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
a=x;
System.out.println("Product" + a + " is produced.");
produced = true;
notify();

}
public synchronized void consume(){
if(!produced){
System.out.println("Consumer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
System.out.println("Product" + a + " is consumed.");
produced = false;
notify();
}
}
class Producer extends Thread{
Buffer b;
public Producer(Buffer b){
this.b = b;
}
public void run(){
System.out.println("Producer start producing...");
for(int i = 1; i <= 10; i++){
b.produce(i);
}
}
}
class Consumer extends Thread{
Buffer b;
public Consumer(Buffer b){
this.b = b;
}
public void run(){
System.out.println("Consumer start consuming...");
for(int i = 1; i <= 10; i++){
b.consume();
}
}
}
public class ProducerConsumerExample {
public static void main(String args[]){
//Create Buffer object.
Buffer b = new Buffer();
//creating producer thread.
Producer p = new Producer(b);
//creating consumer thread.
Consumer c = new Consumer(b);
//starting threads.
p.start();
c.start();
}

}
Output:
Consumer start consuming...
Producer start producing...
Consumer is waiting...
Product1 is produced.
Producer is waiting...
Product1 is consumed.
Consumer is waiting...
Product2 is produced.
Producer is waiting...
Product2 is consumed.
Consumer is waiting...
Product3 is produced.
Producer is waiting...
Product3 is consumed.
Consumer is waiting...
Product4 is produced.
Producer is waiting...
Product4 is consumed.
Consumer is waiting...
Product5 is produced.
Producer is waiting...
Product5 is consumed.
Consumer is waiting...
Product6 is produced.
Producer is waiting...
Product6 is consumed.
Consumer is waiting...
Product7 is produced.
Producer is waiting...
Product7 is consumed.
Consumer is waiting...
Product8 is produced.
Producer is waiting...
Product8 is consumed.
Consumer is waiting...
Product9 is produced.
Producer is waiting...
Product9 is consumed.
Consumer is waiting...
Product10 is produced.
Product10 is consumed.
Download this example.
Synchronization in java
Synchronization:
Synchronization is a process of controlling mutual exclusive problem in multithreading environment. Only one thread
can access a resource at a particular instance of time. When a thread accesses a synchronized block or method, it acquires
a lock on it and release the lock either after completion of method/block or any exception occur.

Note:
1.
2.
3.

1. Synchronization in java is not needed in case of immutable objects.


2. Synchronized keyword is used for performing synchronization in java.
3. Variables cant be synchronized in java. It will give compile time error.
How to implement Synchronization:

1.
1.
2.
2.

1. Using synchronized method.


a. Using non-static synchronized method.
b. static synchronized method.
2. Using synchronized block.
Synchronized method in java
Synchronized method:
A method declared with synchronized keyword is known as synchronized method. A synchronized method can be static
or non-static.
Example: multithreading example without synchronization.
MultiThreadExample.java
/**
* This program is used to show the multithreading
* example without synchronization.
* @author javawithease
*/
class PrintTable{
//not-synchronized method.
public void printTable(int n){
System.out.println("Table of " + n);
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread{
PrintTable pt;
MyThread1(PrintTable pt){
this.pt=pt;
}
public void run(){
pt.printTable(2);
}
}
class MyThread2 extends Thread{
PrintTable pt;
MyThread2(PrintTable pt){
this.pt=pt;

}
public void run(){
pt.printTable(5);
}
}
public class MultiThreadExample{
public static void main(String args[]){
//creating PrintTable object.
PrintTable obj = new PrintTable();
//creating threads.
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
//start threads.
t1.start();
t2.start();
}
}
Output:
Table of 5
Table of 2
2
5
4
10
6
15
8
20
10
25
12
30
14
35
16
40
18
45
50
20
Download this example.
Example: Non-static synchronized method.
MultiThreadExample.java
/**
* This program is used to show the multithreading
* example with synchronization.
* @author javawithease
*/
class PrintTable{

//synchronized method.
public synchronized void printTable(int n){
System.out.println("Table of " + n);
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread{
PrintTable pt;
MyThread1(PrintTable pt){
this.pt=pt;
}
public void run(){
pt.printTable(2);
}
}
class MyThread2 extends Thread{
PrintTable pt;
MyThread2(PrintTable pt){
this.pt=pt;
}
public void run(){
pt.printTable(5);
}
}
public class MultiThreadExample{
public static void main(String args[]){
//creating PrintTable object.
PrintTable obj = new PrintTable();
//creating threads.
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
//start threads.
t1.start();
t2.start();
}
}
Output:
Table of 2
2
4
6
8
10
12
14

16
18
20
Table of 5
5
10
15
20
25
30
35
40
45
50
Download this example.
Static synchronization in java
Static synchronization is achieved by static synchronized methods. Static synchronized method locked on class and nonstatic synchronized method locked on current object i.e. static and non-static synchronized methods can run at same time.
It can produce inconsistency problem.
If static synchronized method is called a class level lock is acquired and then if an object is tries to access non-static
synchronized method at the same time it will not be accessible because class level lock is already acquired.
Example:
MultiThreadExample.java
/**
* This program is used to show the multithreading
* example with synchronization using static synchronized method.
* @author javawithease
*/
class PrintTable{
public synchronized static void printTable(int n){
System.out.println("Table of " + n);
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread{
public void run(){
PrintTable.printTable(2);
}
}
class MyThread2 extends Thread{
public void run(){

PrintTable.printTable(5);
}
}
public class MultiThreadExample{
public static void main(String args[]){
//creating threads.
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
//start threads.
t1.start();
t2.start();
}
}
Output:
Table of 2
2
4
6
8
10
12
14
16
18
20
Table of 5
5
10
15
20
25
30
35
40
45
50
Download this example.
Difference between static and non-static synchronized method.
Non-Static synchronized method
1. Lock is on object.
2. Commonly used.
3. Static keyword is not used.

Static synchronized method


1. Lock is on class.
2. Not commonly used.
3. Used with static keyword.

Synchronized block in java


Synchronized block:
Synchronized block is used to synchronize a critical block of code instead of whole method.

Note: Synchronized block is preferred over synchronized method because in case synchronized block only critical block
of code is locked not whole method, hence performance will be better in this case.
Throw NullPointerException if object passed in synchronized block is null.
Example:
MultiThreadExample.java
/**
* This program is used to show the multithreading
* example with synchronization using synchronized block.
* @author javawithease
*/
class PrintTable{
public void printTable(int n){
synchronized(this){
System.out.println("Table of " + n);
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
}
}
}
}
class MyThread1 extends Thread{
PrintTable pt;
MyThread1(PrintTable pt){
this.pt=pt;
}
public void run(){
pt.printTable(2);
}
}
class MyThread2 extends Thread{
PrintTable pt;
MyThread2(PrintTable pt){
this.pt=pt;
}
public void run(){
pt.printTable(5);
}
}
public class MultiThreadExample{
public static void main(String args[]){
//creating PrintTable object.
PrintTable obj = new PrintTable();
//creating threads.
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
//start threads.

t1.start();
t2.start();
}
}
Output:
Table of 2
2
4
6
8
10
12
14
16
18
20
Table of 5
5
10
15
20
25
30
35
40
45
50
Download this example.
Difference between synchronized method and synchronized block.
Synchronized method

1.
2.
3.

Synchronized block
1. Lock is acquired on critical block of code
1. Lock is acquired on whole method.
only.
2. Less preferred.
2. preferred.
3. Performance will be less as compared to
3. Performance will be better as compared
synchronized block.
to synchronized method.
Input output (I/O) in java
In java Input output operations are based on the concept of stream. The java.io package contains all the required classes
to perform I/O operations.
A stream is defined as a sequence of data.
Automatically created streams in java:
1. System.in: standard input stream.
2. System.out: standard output stream.
3. System.err: standard error.
Input stream:
InputStream is used to read data from a source like file, peripheral device etc.
InputStream class:
InputStream class is the super class of all classes representing an input stream. It is an abstract class.
Commonly used methods of InputStream class:
1. read(): Reads the next byte of data from the input stream. It returns -1 at the end of file.
Syntax: public abstract int read()throws IOException.
2. available(): Returns an estimate of the number of bytes that can be read from the current input stream.
Syntax: public int available()throws IOException.
3. close(): It is used to close the current input stream.

Syntax: public void close()throws IOException.


Output Stream:
OutputStream is used for writing data to a destination like file, peripheral device etc.
OutputStream class:
OutputStream class is the super class of all classes representing an output stream. It is an abstract class.
Commonly used methods of OutputStream class:
1. write(int): This method is used to write a byte to the current output stream.
Syntax: public void write(int)throws IOException.
2. write(byte[]): This method is used to write an array of byte to the current output stream.
Syntax: public void write(byte[])throws IOException.
3. flush():flushes the current output stream.
Syntax: public void flush()throws IOException.
4. close(): This method is used to close the current output stream.
Syntax: public void close()throws IOException.
FileInputStream and FileOutputStream in java
FileInputStream:
FileInputStream stream is used for reading data from the files.
Commonly used constructors of FileInputStream:
1. FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file
system.

2. FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file
system.
Example:
FileInputStreamExample.java
import java.io.FileInputStream;
/**
* This program is used to read a file using FileInputStream.
* @author javawithease
*/
class IOTest{
public void readFile(){
try {
//creating FileInputStream object.
FileInputStream fis =
new FileInputStream("F:\\New folder\\data1.txt");
int i;
//read file.

while((i=fis.read())!=-1){
System.out.print((char)i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class FileInputStreamExample {
public static void main(String args[]){
//creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.readFile();
}
}
Output:
Hello World.
Download this example.
FileOutputStream:
FileOutputStream is used to create a file and write data into it. It will create a file, if it does not exist.
Commonly used constructors of FileOutputStream:
1. FileOutputStream(File file)
Creates a file output stream to write to the file represented by the specified File object.
2. FileOutputStream(String name)
Creates a file output stream to write to the file with the specified name.
Example:
FileOutPutStreamExample.java

import java.io.FileOutputStream;
/**
* This program is used to write data into
* a file using FileOutputStream.
* @author javawithease
*/
class IOTest{
String str = "Hello www.javawithease.com";
public void writeFile(){

try {
//Creating FileOutputStream object.
//It will create a new file before writing if not exist.
FileOutputStream fos =
new FileOutputStream("F:\\New folder\\data2.txt");
byte b[]=str.getBytes();
fos.write(b);
fos.flush();
//Close file after write operation.
fos.close();
System.out.println("Contents written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class FileOutPutStreamExample {
public static void main(String args[]){
//Creating IOTest object.
IOTest obj = new IOTest();
//method call
obj.writeFile();
}
}
Output:
Hello.
This is a text file.
Download this example.
Example: Reading the data from one file and writing it into another file.
ReadWriteExample.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* This program is used to read a file and write into another file.
* @author javawithease
*/
class IOTest{
public void readFile(){
try {
//Creating FileInputStream object.
FileInputStream fis =
new FileInputStream("F:\\New folder\\data1.txt");
//Creating FileOutputStream object.
FileOutputStream fos =
new FileOutputStream("F:\\New folder\\data7.txt");
int i;

//read file.
while((i=fis.read())!=-1){
fos.write(i);
}
System.out.println("Content writen successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ReadWriteExample {
public static void main(String args[]){
//creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.readFile();
}
}
Output:
Contents written successfully.
Download this example.
Byte Streams in java
Byte Streams in java:
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended
from InputStream and OutputStream.
Always close the files to avoid serious resource leaks.
Byte streams should only be used for the most primitive I/O. It represents a kind of low-level I/O so you should
avoid in case complicated data types like text or graphics.
ByteArrayInputStream:
A ByteArrayInputStream class provides an internal buffer for the bytes read from input stream.
Commonly used constructors of ByteArrayInputStream:
1. ByteArrayInputStream(byte[] buf)
Creates a ByteArrayInputStream so that it uses buf as its buffer array.
2. ByteArrayInputStream(byte[] buf, int offset, int length)
Creates ByteArrayInputStream that uses buf as its buffer array.

Commonly used methods of ByteArrayInputStream:


1. public int read()
This method reads the next byte of data from the InputStream. Returns an int as the next byte of data. If it is end of file
then it returns -1.
Example:
ByteArrayInputStreamExample.java
import java.io.ByteArrayInputStream;
/**
* This program is used to read byte array
* input using ByteArrayInputStream.
* @author javawithease
*/
class IOTest{
String str = "www.javawithease.com";
public void readFile(){
try {
//Converting string into byte array.
byte b[] = str.getBytes();
//Creating ByteArrayInputStream object.
ByteArrayInputStream bais =
new ByteArrayInputStream(b);
int i;
//read file.
while((i=bais.read())!=-1){
System.out.print((char)i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ByteArrayInputStreamExample {
public static void main(String args[]){
//creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.readFile();
}
}
Output:
www.javawithease.com
Download this example.
ByteArrayOutputStream:
ByteArrayOutputStream class uses byte array to write data. The buffer automatically grows as data is written to it.

Commonly used to constructors of ByteArrayOutputStream:


1. ByteArrayOutputStream ()
Creates a new byte array output stream.
2. ByteArrayOutputStream (int size)
Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
Commonly used methods of ByteArrayOutputStream:
1. public void writeTo(OutputStream outSt)
Writes the entire content of this Stream to the specified stream argument.
Example:
ByteArrayOutputStreamExample.java
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
/**
* This program is used to write data into
* a file using ByteArrayOutputStream.
* @author javawithease
*/
class IOTest{
String str = "Hello www.javawithease.com";
public void writeFile(){
try {
//Creating FileOutputStream object.
//It will create a new file before writing if not exist.
FileOutputStream fos =
new FileOutputStream("F:\\New folder\\data5.txt");
//Creating ByteArrayOutputStream object.
ByteArrayOutputStream baos=new ByteArrayOutputStream();
baos.write(str.getBytes());
baos.writeTo(fos);
baos.flush();
//Close file after write operation.
baos.close();
System.out.println("Contents written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ByteArrayOutputStreamExample {
public static void main(String args[]){
//Creating IOTest object.
IOTest obj = new IOTest();

//method call
obj.writeFile();
}
}
Output:

Download this example.


DataInputStream and DataOutputStream in java
DataInputStream:
DataInputStream used to read primitive data types from an input source.
Commonly used constructors of DataInputStream:
DataInputStream(InputStream in)
Creates a DataInputStream that uses the specified underlying InputStream.
Commonly used methods of DataInputStream:
public String readLine() throws IOException
Reads the next line of text from the input stream. It reads successive bytes, converting each byte separately into a
character, until it encounters a line terminator or end of file; the characters read are then returned as a String.
i. public final Boolean readBooolean()throws IOException
ii. public final byte readByte()throws IOException
iii.

public final short readShort()throws IOException

iv. public final Int readInt()throws IOException


These methods will read the bytes from the contained InputStream. Returns the next two bytes of the InputStream as the
specific primitive type.
Example:
DataInputStreamExample.java
import java.io.DataInputStream;
import java.io.FileInputStream;
/**
* This program is used to read a file using DataInputStream.
* @author javawithease
*/
class IOTest{
public void readFile(){

try {
//creating FileInputStream object.
FileInputStream fis =
new FileInputStream("F:\\New folder\\data1.txt");
//Creating DataInputStream object.
DataInputStream dis = new DataInputStream(fis);
int i;
//read file.
while((i=dis.read())!=-1){
System.out.print((char)i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class DataInputStreamExample {
public static void main(String args[]){
//creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.readFile();
}
}
Output:
Hello.
This is a text file.
Download this example.

DataOutputStream:
DataOutputStream used to write primitive data types to an output source.
Commonly used constructors of DataOutputStream:
DataOutputStream(OutputStream out)
Creates a new data output stream to write data to the specified underlying output stream.
Commonly used methods of DataOutputStream:
public final void writeBytes(String s) throws IOException
Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in
sequence, by discarding its high eight bits.
i.

public final void writeBooolean()throws IOException

ii.
iii.

public final void writeByte()throws IOException


public final void writeShort()throws IOException

iv. public final void writeInt()throws IOException


These methods will write the specific primitive type data into the output stream as bytes.
Example:
import java.io.DataOutputStream;
import java.io.FileOutputStream;
/**
* This program is used to write data
* into a file using DataOutputStream.
* @author javawithease
*/
class IOTest{
String str = "Hello www.javawithease.com";
public void writeFile(){
try {
//Creating FileOutputStream object.
//It will create a new file before writing if not exist.
FileOutputStream fos =
new FileOutputStream("F:\\New folder\\data4.txt");
//Creating DataOutputStream object.
DataOutputStream dos = new DataOutputStream(fos);
byte b[]=str.getBytes();
dos.write(b);
dos.flush();
//Close file after write operation.
dos.close();
System.out.println("Contents written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class DataOutputStreamExample {
public static void main(String args[]){
//Creating IOTest object.
IOTest obj = new IOTest();
//method call
obj.writeFile();
}
}
Output:
Contents written successfully.

Download this example.


BufferedInputStream and BufferedOutputStream in java
BufferedInputStream and BufferedOutputStream used an internal buffer to store date for read and write operations.
Commonly used constructors of BufferedInputStream:
1. BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves its argument, the input stream in, for later use.
2. BufferedInputStream(InputStream in, int size)
Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use.
Example:
BufferedInputStreamExample.java
import java.io.BufferedInputStream;
import java.io.FileInputStream;
/**
* This program is used to read a
* file using BufferedInputStream.
* @author javawithease
*/
class IOTest{
public void readFile(){
try {
//creating FileInputStream object.
FileInputStream fis =
new FileInputStream("F:\\New folder\\data1.txt");
//Creating BufferedInputStream object.
BufferedInputStream bis =
new BufferedInputStream(fis);
int i;
//read file.
while((i=bis.read())!=-1){
System.out.print((char)i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class BufferedInputStreamExample {
public static void main(String args[]){
//creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.readFile();

}
}
Output:
Hello.
This is a text file.
Download this example.
Commonly used constructors of BufferedOutputStream:
1. BufferedOutputStream(OutputStream out)
Creates a new buffered output stream to write data to the specified underlying output stream.
2. BufferedOutputStream(OutputStream out, int size)
Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer
size.
Example:
BufferedOutputStreamExample.java
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
/**
* This program is used to write data into
* a file using BufferedOutputStream.
* @author javawithease
*/
class IOTest{
String str = "Hello www.javawithease.com";
public void writeFile(){
try {
//Creating FileOutputStream object.
//It will create a new file
//before writing if not exist.
FileOutputStream fos =
new FileOutputStream("F:\\New folder\\data3.txt");
//Creating BufferedOutputStream object.
BufferedOutputStream bos =
new BufferedOutputStream(fos);
byte b[]=str.getBytes();
bos.write(b);
bos.flush();
//Close file after write operation.
bos.close();
System.out.println("Contents written successfully.");
} catch (Exception e) {

e.printStackTrace();
}
}
}
public class BufferedOutputStreamExample {
public static void main(String args[]){
//Creating IOTest object.
IOTest obj = new IOTest();
//method call
obj.writeFile();
}
}
Output:
Contents written successfully.
Download this example.
FileReader and FileWriter in java
FileReader:
FileReader class is used for reading streams of characters from a file.
Commonly used constructors of FileReader:
1. FileReader(File file)
Creates a new FileReader, given the File to read from.
2. FileReader(String fileName)
Creates a new FileReader, given the name of the file to read from.
Example:
FileReaderExample.java
import java.io.FileReader;
/**
* This program is used to read a file using FileReader.
* @author javawithease
*/
class IOTest{
public void readFile(){
try {
//creating FileReader object.
FileReader fr =
new FileReader("F:\\New folder\\data1.txt");
int i;

//read file.
while((i=fr.read())!=-1){
System.out.print((char)i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class FileReaderExample {
public static void main(String args[]){
//creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.readFile();
}
}
Output:
Hello.
This is a text file.
Download this example.
FileWriter:
FileWriter class is used for streams of characters to a file.
Commonly used constructors of FileWriter:
1. FileWriter(File file)
Creates a FileWriter object given a File object.
2. FileWriter(String fileName)
Creates a FileWriter object given a file name.
Example:
FileWriterExample.java
import java.io.FileWriter;
/**
* This program is used to write data into
* a file using FileOutputStream.
* @author javawithease
*/
class IOTest{
String str = "Hello www.javawithease.com";

public void writeFile(){


try {
//Creating FileWriter object.
//It will create a new file before writing if not exist.
FileWriter fw =
new FileWriter("F:\\New folder\\data6.txt");
fw.write(str);
fw.flush();
//Close file after write operation.
fw.close();
System.out.println("Contents written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class FileWriterExample {
public static void main(String args[]){
//Creating IOTest object.
IOTest obj = new IOTest();
//method call
obj.writeFile();
}
}
Output:
Contents written successfully.
Download this example.
How To Check If A File Exists In Java
Example:
FileCheckExample.java
import java.io.File;
/**
* This program is used to check that file
* exists or not at given location.
* @author javawithease
*/
class IOTest{
public void checkFileExistance(){
//Creating File object.
File file =
new File("F:\\New folder\\data1.txt");
if(file.exists()){
System.out.println("file exist.");
}else{
System.out.println("file not exist.");
}

}
}
public class FileCheckExample {
public static void main(String args[]){
//Creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.checkFileExistance();
}
}
Output:
file exist.
Download this example.
Serialization and Deserialization in java
In java serialization is way used to convert an object into a byte stream which can be transported to any other running
JVM through a network or can be persisted into disk and that object can be rebuilt again. Java provides serialization API
for this.
How to make a class serializable in java?
To make a java class Serializable implements java.io.Serializable interface. JVM will take care of serializing objects.
What is Serializable interface?
Serializable interface is a marker interface. A marker interface doesnt have any method i.e. Serializable interface doesnt
have any method, it gives indication to compiler that use Java Serialization mechanism to serialize this object.

Example:
SerializationExample.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* This program is used to show the serialization process.
* @author javawithease
*/
class Student implements Serializable{

//Serial Version UID.


private static final long serialVersionUID = 1L;
String name;
String className;
String rollNo;
//Constructor.
Student(String name, String className, String rollNo){
this.name = name;
this.className = className;
this.rollNo = rollNo;
}
}
class Test{
//Write serialized object into objectoutputstream.
public void objectSerialization(Student stu){
try
{
//Creating FileOutputStream object.
FileOutputStream fos =
new FileOutputStream("F:\\New folder\\student.ser");
//Creating ObjectOutputStream object.
ObjectOutputStream oos = new ObjectOutputStream(fos);
//write object.
oos.writeObject(stu);
//close streams.
oos.close();
fos.close();
System.out.println("Serialized data is saved in " +
"F:\\New folder\\student.ser");
}catch(IOException e)
{
System.out.println(e);
}
}
}
public class SerializationExample {
public static void main(String args[]){
//Creating Student object.
Student stu =
new Student("Parmander", "MCA", "MCA/07/27");
//Creating Test object.
Test obj = new Test();
//Method call.
obj.objectSerialization(stu);
}
}
Output:
Serialized data is saved in F:\New folder\student.ser
Download this example.

Deserialization:
Deserialization is the reverse process of serialization. It is the process of rebuilding object from serialized state.
Example:
DeSerializationExample.java
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
/**
* This program is used to show the deserialization process.
* @author javawithease
*/
class Student implements Serializable{
//Serial Version UID.
private static final long serialVersionUID = 1L;
String name;
String className;
String rollNo;
//Constructor.
Student(String name, String className, String rollNo){
this.name = name;
this.className = className;
this.rollNo = rollNo;
}
}
class Test{
//Deserialize a serialize object.
public void objectDeSerialization(){
try
{
Student stu = null;
//Creating FileOutputStream object.
FileInputStream fis =
new FileInputStream("F:\\New folder\\student.ser");
//Creating ObjectOutputStream object.
ObjectInputStream ois = new ObjectInputStream(fis);
//write object.
stu = (Student) ois.readObject();
//close streams.
ois.close();
fis.close();
System.out.println("Name = " + stu.name);
System.out.println("Class Name = " + stu.className);
System.out.println("RollNo = " + stu.rollNo);
}catch(Exception e)
{
System.out.println(e);
}
}

}
public class DeSerializationExample {
public static void main(String args[]){
//Creating Test object.
Test obj = new Test();
//Method call.
obj.objectDeSerialization();
}
}
Output:
Name = Parmander
Class Name = MCA
RollNo = MCA/07/27
Download this example.
What is the difference between Serializable and Externalizable interface in Java?
Serializable
1. Serializable interface is a marker
interface.
2. Only unchecked exception can propagate
using throw.
3. Serializable interface write state of an
object in non-compress format.

Externalizable
1. Externalizable interface is not a marker
interface.
2. Serializable interface doesnt have any
method.
3. Externalizable interface writes state of an
object in compress format.

Related Topics:
Transient keyword in java
Transient variable:
A variable declared with transient keyword is a transient variable. It is used in serialization process to provide flexibility
for excluding some variables from serialization process. A variable declared with transient keyword will not be serialized.
Example:
TransientExample.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* This program is used to show that transient variables
* are not saved in serialization process.
* @author javawithease
*/
class Student implements Serializable{

//Serial Version UID.


private static final long serialVersionUID = 1L;
String name;
transient String className;
String rollNo;
//Constructor.
Student(String name, String className, String rollNo){
this.name = name;
this.className = className;
this.rollNo = rollNo;
}
}
class Test{
//Write serialized object into objectoutputstream.
public void objectSerialization(Student stu){
try{
//Creating FileOutputStream object.
FileOutputStream fos =
new FileOutputStream("F:\\New folder\\studentTransient.ser");
//Creating ObjectOutputStream object.
ObjectOutputStream oos = new ObjectOutputStream(fos);
//write object.
oos.writeObject(stu);
//close streams.
oos.close();
fos.close();
System.out.println("Serialized data is saved in " +
"F:\\New folder\\studentTransient.ser");
}catch(IOException e){
System.out.println(e);
}
}
//Deserialize a serialize object.
public void objectDeSerialization(){
try{
Student stu = null;
//Creating FileOutputStream object.
FileInputStream fis =
new FileInputStream("F:\\New folder\\studentTransient.ser");
//Creating ObjectOutputStream object.
ObjectInputStream ois = new ObjectInputStream(fis);
//write object.
stu = (Student) ois.readObject();
//close streams.
ois.close();
fis.close();
System.out.println("Name = " + stu.name);
System.out.println("Class Name = " + stu.className);

System.out.println("RollNo = " + stu.rollNo);


}catch(Exception e){
System.out.println(e);
}
}
}
public class TransientExample {
public static void main(String args[]){
//Creating Student object.
Student stu =
new Student("Parmander", "MCA", "MCA/07/27");
//Creating Test object.
Test obj = new Test();
//Method call.
obj.objectSerialization(stu);
obj.objectDeSerialization();
}
}
Output:
Serialized data is saved in F:\New folder\studentTransient.ser
Name = Parmander
Class Name = null
RollNo = MCA/07/27
Download this example.
Which types of variables are not serialized during Java Serialization?
Static and transient variables are not serialized during Java Serialization. As static are associated to the class and not to an
object hence they are not the part of the state of object so they are not saved during Java Serialization process.

Collection framework in java


Collection is a simply an object that represents a group of objects into a single unit.
Collection framework:
Collection framework is a unified architecture or a set classes and interfaces for representing and manipulating
collections. i.e. collection framework is used to store, retrieve and manipulate collections.
Collection framework contains following:
1.
2.
3.

1. Interfaces: are abstract data types that represent collections and allow collections to be manipulated
independently of the details of their representation.
2. Classes/Implementations: are the concrete implementations of the collection interfaces.
3. Algorithms: are the methods used for collection computations, like searching and sorting.
Advantages/Benefits of collection framework:

1.
2.
3.
4.

1. Reduces programming effort: Collection framework provides useful data structure and algorithms for
collection manipulation, you not have to write them.
2. Increases program speed and quality: Collection framework provides high-performance and high-quality
implementations of useful data structures and algorithms which increase the speed and quality.
3. Resizable: Collection is resizable.
4. Reduces effort to design new APIs: becausecollection framework eliminates the need to produce ad hoc
collections APIs.
Disadvantages of collection framework:

1.
2.

1. It must cast to correct type.


2. It cant be done compile-time type checking.
Note: Above two disadvantages can be removed from collection framework by using generics.
Core Collection Framework interfaces are categories into two sets collections and maps.
Note: Maps are not the integral part of collection framework but are considered as collection because they can store and
manipulate group of objects like collections.
Collection interfaces in java
Collection interfaces:
Collection interfaces are abstract data types that represent collections and allow collections to be manipulated
independently of the details of their representation.
Collection interfaces are given below:
1. Collection Interface:
Collection interface is the root interface in the collection hierarchy. It declares the core methods for all collections.
2. List Interface:
A List represents an ordered or sequenced group of elements. It may contain duplicate elements. It extends the collection
interface.
3. Set Interface:
A set represents a group of elements which cant contain a duplicate element. It extends the collection interface.
4. SortedSet Interface:
SortedSet interface extends Set interface. SortedSet interface maintain ascending order in its elements.
5. Map Interface:
A map represents an object with key value pair. A map cannot contain duplicate keys and one key can map to at most
one value.
6. Map.Entry Interface:
It provides the facility to work with a map entry.
7. SortedMap Interface:
SortedMap interface extends Map interface. It maintains its entries in ascending key order.
8. Queue interface:
Queue represents a collection for holding elements prior to processing.
9. Deque interface:
Deque interface provides the methods to manipulate double-ended-queue or deque. A deque represents a linear collection
of elements that support insertion, retrieval and removal of elements at both ends.
10. Enumeration Interface:
It provides the methods to get a series of elements from a collection of object taking one at a time.
Collection interface in java
Collection interface:
Collection interface is the root interface in the collection hierarchy. It declares the core methods for all collections.
Commonly used methods of Collection interface:
1. add(Object obj): Add object to the calling collection. It returns true if collection changed after this call otherwise
returns false.

Syntax: public boolean add(Object obj)


2. addAll(Collection c): Add all objects to the calling collection. It returns true if collection changed after this call
otherwise returns false.
Syntax: public boolean addAll(Collection c)
3. clear(): Remove all elements from the calling collection.
Syntax: public void clear()
4. contains(Object obj): It returns true if this collection contains the specified object otherwise returns false.
Syntax: public boolean contains(Object obj)
5. containsAll(Collection c):It returns true if this collection contains all elements of the specified collection otherwise
returns false.
Syntax: public boolean containsAll(Collection c)
6. equals(Object obj): It returns true if this collection equals to the specified object otherwise returns false.
Syntax: public boolean equals(Object obj)
7. hashCode(): It returns the hash code of the calling collection.
Syntax: public int hashCode()
8. isEmpty(): It returns true if the calling collection is empty otherwise returns false.
Syntax: public boolean isEmpty()
9. iterator(): It returns an iterator instance for the calling collection.
Syntax: public Iterator iterator()
10. remove(Object obj): It remove the specified object from the calling collection. It returns true if collection changed
after this call otherwise returns false.
Syntax: public boolean remove(Object obj)
11. removeAll(Collection c): It remove all elements of the specified collection from the calling collection. It returns true
if collection changed after this call otherwise returns false.
Syntax: public boolean removeAll(Collection c)
12. retainAll(Collection c): It remove all elements except those of the specified collection from the calling collection. It
returns true if collection changed after this call otherwise returns false.
Syntax: public boolean retainAll(Collection c)

13. size(): It returns the number of elements in the calling collection.


Syntax: public int size()
14. toArray( ): It returns an array of containing all elements of the calling collection.
Syntax: public Object[ ] toArray()
A simple example of HashSet class to explain few methods of Collection interface.
HashSetTest.java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* This class is used to show the HashSet functionality.
* @author javawithease
*/
public class HashSetTest {
public static void main(String args[]){
//Create HashSet object.
Set hashSet = new HashSet();
//Add objects to the HashSet.
hashSet.add("Roxy");
hashSet.add("Sunil");
hashSet.add("Sandy");
hashSet.add("Munish");
hashSet.add("Pardeep");
//Print the HashSet object.
System.out.println("HashSet elements:");
System.out.println(hashSet);
//Print the HashSet elements using iterator.
Iterator iterator=hashSet.iterator();
System.out.println("HashSet elements using iterator:");
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
Output
HashSet elements:
[Sandy, Pardeep, Munish, Sunil, Roxy]
HashSet elements using iterator:
Sandy
Pardeep
Munish
Sunil
Roxy
Download this example.

Set interface in java


Set interface:
A set represents a group of elements which cant contain a duplicate element. It extends the collection interface.
Note: Set interface contains only methods inherited from Collection interface and adds the restriction that cant
contain a duplicate element.
Commonly Used methods of Set interface:
1. add(Object obj): Add object to the calling collection. It returns true if collection changed after this call otherwise
returns false.
Syntax: public boolean add(Object obj)
2. addAll(Collection c): Add all objects to the calling collection. It returns true if collection changed after this call
otherwise returns false.
Syntax: public boolean addAll(Collection c)
3. clear(): Remove all elements from the calling collection.
Syntax: public void clear()
4. contains(Object obj): It returns true if this collection contains the specified object otherwise returns false.
Syntax: public boolean contains(Object obj)
5. containsAll(Collection c):It returns true if this collection contains all elements of the specified collection otherwise
returns false.
Syntax: public boolean containsAll(Collection c)
6. equals(Object obj): It returns true if this collection equals to the specified object otherwise returns false.
Syntax: public boolean equals(Object obj)
7. hashCode(): It returns the hash code of the calling collection.
Syntax: public int hashCode()
8. isEmpty(): It returns true if the calling collection is empty otherwise returns false.
Syntax: public boolean isEmpty()
9. iterator(): It returns an iterator instance for the calling collection.
Syntax: public Iterator iterator()

10. remove(Object obj): It remove the specified object from the calling collection. It returns true if collection changed
after this call otherwise returns false.
Syntax: public boolean remove(Object obj)
11. removeAll(Collection c): It remove all elements of the specified collection from the calling collection. It returns true
if collection changed after this call otherwise returns false.
Syntax: public boolean removeAll(Collection c)
12. retainAll(Collection c): It remove all elements except those of the specified collection from the calling collection. It
returns true if collection changed after this call otherwise returns false.
Syntax: public boolean retainAll(Collection c)
13. size(): It returns the number of elements in the calling collection.
Syntax: public int size()
14. toArray( ): It returns an array of containing all elements of the calling collection.
Syntax: public Object[ ] toArray()
A simple example of HashSet class to explain few methods of Set interface.
HashSetTest.java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* This class is used to show the HashSet functionality.
* @author javawithease
*/
public class HashSetTest {
public static void main(String args[]){
//Create HashSet object.
Set hashSet = new HashSet();
//Add objects to the HashSet.
hashSet.add("Roxy");
hashSet.add("Sunil");
hashSet.add("Sandy");
hashSet.add("Munish");
hashSet.add("Pardeep");
//Print the HashSet object.
System.out.println("HashSet elements:");
System.out.println(hashSet);
//Print the HashSet elements using iterator.
Iterator iterator=hashSet.iterator();
System.out.println("HashSet elements using iterator:");
while(iterator.hasNext()){

System.out.println(iterator.next());
}
}
}
Output:
HashSet elements:
[Sandy, Pardeep, Munish, Sunil, Roxy]
HashSet elements using iterator:
Sandy
Pardeep
Munish
Sunil
Roxy
Download this example.
SortedSet interface in java
SortedSet interface:
SortedSet interface extends Set interface. SortedSet interface maintain ascending order in its elements.
Note: SortedSet interface declares its own methods in addition of methods declared in Set interface.
Commonly used methods of SortedSet interface:
1. comparator(): Returns comparator for this sorted set. It returns null if the natural ordering is used for this set.
Syntax: public Comparator comparator().
2. first(): Returns the first element in this sorted set.
Syntax: public Object first().
3. headSet(Object end): Returns a SortedSet containing those elements less than end that are contained in this sorted set.
Syntax: public SortedSet headSet(Object end).
4. last(): Returns the last element in this sorted set.
Syntax: public Object last().
5. subSet(Object start, Object end): Returns a SortedSet containing those elements between start and end -1.
Syntax: public SortedSet subSet(Object start, Object end).
6. tailSet(Object start): Returns a SortedSet that contains those elements greater than or equal to start that are contained
in this sorted set.
Syntax: public SortedSet tailSet(Object start).

A simple example of TreeSet class to explain few methods of SortedSet interface.


TreeSetTest.java
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
/**
* This class is used to show the TreeSet functionality.
* @author javawithease
*/
public class TreeSetTest {
public static void main(String args[]){
//Create TreeSet object.
Set treeSet = new TreeSet();
//Add objects to the HashSet.
treeSet.add("Roxy");
treeSet.add("Sunil");
treeSet.add("Sandy");
treeSet.add("Munish");
treeSet.add("Pardeep");
//Print the TreeSet object.
System.out.println("TreeSet elements:");
System.out.println(treeSet);
//Print the TreeSet elements using iterator.
Iterator iterator=treeSet.iterator();
System.out.println("TreeSet elements using iterator:");
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
Output:
TreeSet elements:
[Munish, Pardeep, Roxy, Sandy, Sunil]
TreeSet elements using iterator:
Munish
Pardeep
Roxy
Sandy
Sunil
Download this example.

List interface in java


List interface:

A List represents an ordered or sequenced group of elements. It may contain duplicate elements. It extends the collection
interface.
Note:
1. Elements can be inserted or retrieved by their position in the list. Position or index value starts from 0.
2. List interface defines its own methods in addition to the methods of collection interface.
Commonly used methods of List interface:
1. add(int index, Object obj): Insert obj at the specified index position into this list. All pre-existing elements at or
beyond the specified index are shifted up.
Syntax: public void add(int index, Object obj)
2. addAll(int index, Collection c): Insert all elements of the specified collection at the specified index position into this
collection. All pre-existing elements at or beyond the specified index are shifted up. Returns true is this list changes after
the operation otherwise returns false.
Syntax: public boolean addAll(int index, Collection c)
3. get(int index): Returns the object stored at specified index position into this list.
Syntax: public Object get(int index)
4. indexOf(Object obj): Returns index of first occurrence of obj in this list. It returns -1 if obj is not exist in this list.
Syntax: public int indexOf(Object obj)
5. lastIndexOf(Object obj): Returns index of last occurrence of obj in this list. It returns -1 if obj is not exist in this list.
Syntax: public int lastIndexOf(Object obj)
6. listIterator( ): Returns an ListIterator object to the start of the this list.
Syntax: public ListIterator listIterator( )
7. listIterator(int index): Returns an ListIterator object to this list that begins at the specified index.
Syntax: public ListIterator listIterator(int index)
8. remove(int index): Removes the element at specified index position from the this list and returns the deleted element.
Indexes of all elements beyond index are decremented by one.
Syntax: public Object remove(int index)
9. set(int index, Object obj): Assigns obj to the specified index location within the this list.
Syntax: public Object set(int index, Object obj)
10. subList(int start, int end): Returns a list that contains the elements from start to end-1 index position in this list.
Syntax: public List subList(int start, int end)

A simple example of ArrayList class to explain few methods of List interface.


ArrayListTest.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* This class is used to show the ArrayList functionality.
* @author javawithease
*/
public class ArrayListTest {
public static void main(String args[]){
//Create ArrayList object.
List arrayList = new ArrayList();
//Add objects to the HashSet.
arrayList.add("Amani");
arrayList.add("Prabhjot");
arrayList.add("Nidhi");
arrayList.add("Vandana");
arrayList.add("Poonam");
//Size of the ArrayList object.
System.out.println("Size: "
+ arrayList.size());
//Print the ArrayList object.
System.out.println("ArrayList elements:");
System.out.println(arrayList);
//Print the ArrayList elements using iterator.
Iterator iterator1=arrayList.iterator();
System.out.println("ArrayList elements " +
"using iterator:");
while(iterator1.hasNext()){
System.out.println(iterator1.next());
}
//Add an object at the specific position.
arrayList.add(2,"Jagdeep");
//Remove a element from a specific position.
arrayList.remove(3);
arrayList.remove(4);
//Size of the ArrayList object.
System.out.println("Size after manipulation: "
+ arrayList.size());
//Print the ArrayList object.
System.out.println("ArrayList elements" +
" after manipulation:");
System.out.println(arrayList);
//Print the ArrayList elements using iterator.
Iterator iterator2=arrayList.iterator();
System.out.println("ArrayList elements after" +

" manipulation using iterator:");


while(iterator2.hasNext()){
System.out.println(iterator2.next());
}
}
}
Output:
Size: 5
ArrayList elements:
[Amani, Prabhjot, Nidhi, Vandana, Poonam]
ArrayList elements using iterator:
Amani
Prabhjot
Nidhi
Vandana
Poonam
Size after manipulation: 4
ArrayList elements after manipulation:
[Amani, Prabhjot, Jagdeep, Vandana]
ArrayList elements after manipulation using iterator:
Amani
Prabhjot
Jagdeep
Vandana
Download this example.
Map interface in java
Map interface:
A map represents an object with key value pair. A map cannot contain duplicate keys and one key can map to at most
one value.
Commonly used methods of Map interface:
1. clear(): Removes all key-value pairs from this map.
Syntax: public void clear()
2. containsKey(Object k): Returns true if this map contains specified key otherwise returns false.
Syntax: public boolean containsKey(Object k)
3. (Object v): Returns true if this map contains specified value otherwise returns false.
Syntax: public boolean containsValue(Object v)
4. entrySet(): Returns a Set that contains the entries of this map. The set contains objects of type Map.Entry. It provides
a set-view of this map.
Syntax: public Set entrySet().

5. equals(Object obj): Returns true if specified object is equals to this map otherwise returns false.
Syntax: public boolean equals(Object obj)
6. get(Object k): Returns the value associated with the specified key.
Syntax: public Object get(Object k)
7. hashCode(): Returns the hash code for this map.
Syntax: public int hashCode()
8. isEmpty(): Returns true if this map is empty otherwise returns false.
Syntax: public boolean isEmpty()
9. keySet(): Returns a Set that contains the keys in this map. This method provides a set-view of the keys in this map.
Syntax: public Set keySet()
10. put(Object k, Object v): Puts an entry in this map, overwriting any previous value associated with the specified key.
Returns previous value linked to the key. Return null if key does not already exist.
Syntax: public Object put(Object k, Object v)
11. putAll(Map m): Puts all the entries from m into this map.
Syntax: public void putAll(Map m)
12. remove(Object k): Removes the entry whose key equals to specified key from this map. Returns the value to which
this map previously associated with specified key, or null if the map contained no mapping for the key.
Syntax: public Object remove(Object k)
13. size(): Returns the number of entries in this map.
Syntax: public int size()
14. values(): Returns a collection containing the values in this map. This method provides a collection-view of the values
in this map.
Syntax: public Collection values()
A simple example of HashMap class to explain few methods of Map interface.
HashMapTest.java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
* This class is used to show the HashMap functionality.
* @author javawithease
*/
public class HashMapTest {
public static void main(String args[]){
//Create HashMap object.
Map hashMap = new HashMap();
//Add objects to the HashSet.
hashMap.put(4, "Roxy");
hashMap.put(2, "Sunil");
hashMap.put(5, "Sandy");
hashMap.put(1, "Munish");
hashMap.put(3, "Pardeep");
//Print the HashMap object.
System.out.println("HashMap elements:");
System.out.println(hashMap);
//Get iterator
Set set=hashMap.entrySet();
Iterator iterator=set.iterator();
//Print the HashMap elements using iterator.
System.out.println("HashMap elements using iterator:");
while(iterator.hasNext()){
Map.Entry mapEntry=(Map.Entry)iterator.next();
System.out.println("Key: " + mapEntry.getKey() + ", " +
"Value: " + mapEntry.getValue());
}
}
}
Output:
HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
HashMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy
Download this example.
Map.Entry interface in java
Map.Entry interface:
Map.Entry interface provides the facility to work with a map entry. The entrySet( ) method of the Map interface returns
the set of map entries i.e. set of Map.Entry objects.
Commonly used methods of Map.Entry interface:
1. equals(Object obj): Returns true if specified object is equals to this map otherwise returns false.

Syntax: public boolean equals(Object obj).


2. getKey(): It returns the key of the calling map entry.
Syntax: Object getKey()
3. getValue(): It returns the value of the calling map entry.
Syntax: Object getValue()
4. hashCode(): It returns the hash code of the calling map entry.
Syntax: int hashCode()
5. setValue(Object v): It sets the value of the calling map entry to v. It throws NullPointerException if v is null.
Syntax: Object setValue(Object v)
A simple example of HashMap class to explain few methods of Map.Entry interface.
HashMapTest.java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* This class is used to show the HashMap functionality.
* @author javawithease
*/
public class HashMapTest {
public static void main(String args[]){
//Create HashMap object.
Map hashMap = new HashMap();
//Add objects to the HashSet.
hashMap.put(4, "Roxy");
hashMap.put(2, "Sunil");
hashMap.put(5, "Sandy");
hashMap.put(1, "Munish");
hashMap.put(3, "Pardeep");
//Print the HashMap object.
System.out.println("HashMap elements:");
System.out.println(hashMap);
//Get iterator
Set set=hashMap.entrySet();
Iterator iterator=set.iterator();
//Print the HashMap elements using iterator.
System.out.println("HashMap elements using iterator:");
while(iterator.hasNext()){
Map.Entry mapEntry=(Map.Entry)iterator.next();
System.out.println("Key: " + mapEntry.getKey() + ", " +

"Value: " + mapEntry.getValue());


}
}
}
Output:
HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
HashMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy
Download this example.
SortedMap interface in java
SortedMap interface:
SortedMap interface extends Map interface. It maintains its entries in ascending key order.
Commonly used methods of SortedMap interface:
1. comparator(): Returns comparator for this sorted map. It returns null if the natural ordering is used for this map.
Syntax: public Comparator comparator().
2. firstKey(): Returns the first key in this map.
Syntax: public Object firstKey ( ).
3. headMap(Object end): Returns a SortedMap containing those elements less than end that are contained in this sorted
map.
Syntax: public SortedMap headMap(Object end).
4. lastKey(): Returns the last key in this sorted map.
Syntax: public Object lastKey().
5. subMap(Object start, Object end): Returns a SortedMap containing those elements between start and end -1.
Syntax: public SortedMap subMap(Object start, Object end).
6. tailMap(Object start): Returns a map containing those entries with keys that are greater than or equal to start.
Syntax: public SortedMap tailMap(Object start)
A simple example of TreeMap class to explain few methods of SortedMap interface.

TreeMapTest.java
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* This class is used to show the TreeMap functionality.
* @author javawithease
*/
public class TreeMapTest {
public static void main(String args[]){
//Create TreeMap object.
Map treeMap = new TreeMap();
//Add objects to the TreeMap.
treeMap.put(4, "Roxy");
treeMap.put(2, "Sunil");
treeMap.put(5, "Sandy");
treeMap.put(1, "Munish");
treeMap.put(3, "Pardeep");
//Print the TreeMap object.
System.out.println("TreeMap elements:");
System.out.println(treeMap);
//Get iterator
Set set=treeMap.entrySet();
Iterator iterator=set.iterator();
//Print the TreeMap elements using iterator.
System.out.println("TreeMap elements using iterator:");
while(iterator.hasNext()){
Map.Entry mapEntry=(Map.Entry)iterator.next();
System.out.println("Key: " + mapEntry.getKey() + ", " +
"Value: " + mapEntry.getValue());
}
}
}
Output:
TreeMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
TreeMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy
Download this example.
Queue interface in java
Queue interface:

Queue represents a collection for holding elements prior to processing.


Note: Queue declares its own methods in addition with methods declared in Collection interface.
Commonly used methods of Queue Interface:
1. add(Object obj): Inserts the specified element into this queue. Returns true if queue changed after the operation
otherwise returns false.
Syntax: public boolean add(Object obj)
2. offer(Object obj): Inserts the specified element into this queue. Returns true if the element was added to this queue
otherwise returns false.
Syntax: public boolean offerr(Object obj)
3. remove(): Returns and removes the head of this queue. It throws an exception if this queue is empty.
Syntax: public Object remove()
4. poll(): Returns and removes the head of this queue. Returns null if this queue is empty.
Syntax: public Object poll()
5. element(): Returns but does not removes the head of this queue. It throws an exception if this queue is empty.
Syntax: public Object element()
6. peek(): Returns but does not removes the head of this queue. Returns null if this queue is empty.
Syntax: public Object peek()
A simple example of PriorityQueue class to explain few methods of Queue interface.
PriorityQueueTest.java
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* This class is used to show the PriorityQueue functionality.
* @author javawithease
*/
public class PriorityQueueTest {
public static void main(String args[]){
//Create PriorityQueue object.
Queue priorityQueue = new PriorityQueue();
//Add objects to the PriorityQueue .
priorityQueue.add("Gourav");
priorityQueue.add("Neeraj");
priorityQueue.add("Deepak");
priorityQueue.add("Mohan");

priorityQueue.add("Parmender");
//Print the PriorityQueue object.
System.out.println("HasPriorityQueue elements:");
System.out.println(priorityQueue);
//Print the PriorityQueue elements using iterator.
Iterator iterator1=priorityQueue.iterator();
System.out.println("PriorityQueue elements " +
"using iterator:");
while(iterator1.hasNext()){
System.out.println(iterator1.next());
}
//Print the head element of the PriorityQueue
System.out.println("Head element: "
+ priorityQueue.element());
System.out.println("Head element: "
+ priorityQueue.peek());
//Remove the head element of the PriorityQueue
priorityQueue.poll();
priorityQueue.remove();
//Print the PriorityQueue object.
System.out.println("HasPriorityQueue elements " +
"after manipulation:");
System.out.println(priorityQueue);
//Print the PriorityQueue elements using iterator.
Iterator iterator2=priorityQueue.iterator();
System.out.println("PriorityQueue elements after " +
"manipulation using iterator:");
while(iterator2.hasNext()){
System.out.println(iterator2.next());
}
}
}
Output:
HasPriorityQueue elements:
[Deepak, Mohan, Gourav, Neeraj, Parmender]
PriorityQueue elements using iterator:
Deepak
Mohan
Gourav
Neeraj
Parmender
Head element: Deepak
Head element: Deepak
HasPriorityQueue elements after manipulation:
[Mohan, Neeraj, Parmender]
PriorityQueue elements after manipulation using iterator:
Mohan
Neeraj
Parmender
Download this example.

Deque interface in java


Deque interface:
Deque interface represents a double-ended-queue. A deque represents a linear collection of elements that support
insertion, retrieval and removal of elements at both ends.
Deques can be used both as FIFO (first-in, first-out) and LIFO (last-in, first-out). In a deque all new elements can be
inserted, retrieved and removed at both ends.
Commonly used methods of Deque interface:
1. addFirst(Object obj): Inserts the specified element at the front of this deque.
Syntax: public void addFirst(Object obj)
2. addLast(Object obj): Inserts the specified element at the end of this deque.
Syntax: public void addLast(Object obj)
3. offerFirst(Object obj): Inserts the specified element at the front of this deque. Returns true if the element was added
to this deque, else false.
Syntax: public boolean offerFirst(Object obj)
4. offerLast(Object obj): Inserts the specified element at the end of this deque. Returns true if the element was added to
this deque, else false.
Syntax: public boolean offerLast(Object obj)
5. removeFirst(): Returns and removes the first element of this deque. It throws an exception if this deque is empty.
Syntax: public Object removeFirst()
6. removeLast(): Returns and removes the last element of this deque. It throws an exception if this deque is empty.
Syntax: public Object removeLast()
7. pollFirst(): Returns and removes the first element of this deque. Returns null if this deque is empty.
Syntax: public Object pollFirst()
8. pollLast(): Returns and removes the last element of this deque. Returns null if this deque is empty.
Syntax: public Object pollLast()
9. getFirst(): Returns but does not removes the first element of this deque. It throws an exception if this deque is empty.
Syntax: public Object getFirst()
10. getLast(): Returns but does not removes the last element of this deque. It throws an exception if this deque is empty.

Syntax: public Object getLast()


11. peekFirst(): Returns but does not removes the first element of this deque. Returns null if this deque is empty.
Syntax: public Object peakFirst()
12. peekLast(): Returns but does not removes the last element of this deque. Returns null if this deque is empty.
Syntax: public Object peekLast()
13. removeFirstOccurrence(): Removes the first occurrence of the specified element from this deque. Returns true if
specified element is removed from this deque otherwise returns false.
Syntax: public boolean removeFirstOccurrence()
14. removeLastOccurrence(): Removes the last occurrence of the specified element from this deque. Returns true if
specified element is removed from this deque otherwise returns false.
Syntax: public boolean removeLastOccurrence()
A simple example of ArrayDeque class to explain few methods of Deque interface.
ArrayDequeTest.java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
/**
* This class is used to show the ArrayDeque functionality.
* @author javawithease
*/
public class ArrayDequeTest {
public static void main(String args[]){
//Create ArrayDeque object.
Deque arrayDeque = new ArrayDeque();
//Add objects to the ArrayDeque.
arrayDeque.add("Gourav");
arrayDeque.add("Neeraj");
arrayDeque.add("Deepak");
arrayDeque.add("Mohan");
arrayDeque.add("Parmender");
//Print the ArrayDeque object.
System.out.println("ArrayDeque elements:");
System.out.println(arrayDeque);
//Print the ArrayDeque elements using iterator.
Iterator iterator1=arrayDeque.iterator();
System.out.println("ArrayDeque elements " +
"using iterator:");
while(iterator1.hasNext()){
System.out.println(iterator1.next());
}

//Print the first element of the ArrayDeque.


System.out.println("First element: "
+ arrayDeque.getFirst());
//Print the last element of the ArrayDeque.
System.out.println("Last element: "
+ arrayDeque.getLast());
//Remove the first element of the ArrayDeque.
arrayDeque.pollFirst();
//Remove the last element of the ArrayDeque.
arrayDeque.pollLast();
//Print the ArrayDeque object.
System.out.println("ArrayDeque elements " +
"after manipulation:");
System.out.println(arrayDeque);
//Print the ArrayDeque elements using iterator.
Iterator iterator2=arrayDeque.iterator();
System.out.println("ArrayDeque elements after " +
"manipulation using iterator:");
while(iterator2.hasNext()){
System.out.println(iterator2.next());
}
}
}
Output:
ArrayDeque elements:
[Gourav, Neeraj, Deepak, Mohan, Parmender]
ArrayDeque elements using iterator:
Gourav
Neeraj
Deepak
Mohan
Parmender
First element: Gourav
Last element: Parmender
ArrayDeque elements after manipulation:
[Neeraj, Deepak, Mohan]
ArrayDeque elements after manipulation using iterator:
Neeraj
Deepak
Mohan
Download this example.

Enumeration interface in java


Enumeration Interface:
It provides the methods to get a series of elements from a collection of object taking one at a time.
Commonly used methods of Enumeration interface:
1. hasMoreElements(): It returns true if more elements are left to iterate otherwise returns false.
Syntax: public boolean hasMoreElements()
2. nextElement(): It returns the next object of the enumeration.
Syntax: public Object nextElement()
A simple example of Enumeration interface:
EnumerationTest.java
import java.util.Enumeration;
import java.util.Vector;
/**
* This class is used to show the Enumeration functionality.
* @author javawithease
*/
public class EnumerationTest{
public static void main(String args[]){
Enumeration days;
Vector weekDays = new Vector();
weekDays.add("Sunday");
weekDays.add("Monday");
weekDays.add("Tuesday");
weekDays.add("Wednesday");
weekDays.add("Thursday");
weekDays.add("Friday");
weekDays.add("Saturday");
days = weekDays.elements();
//Iterate the Enumeration object.
while (days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
}
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Download this example.


Collection classes in java
Collection classes:
Collection classes are the concrete implementations of the collection interfaces.
Collection classes are given below:
1. HashSet: HashSet extends AbstractSet and implements the Set interface. It not maintains any order for its elements. It
uses hash table for storage.
2. LinkedHashSet: LinkedHashSet extends HashSet and implements the Set interface. It maintains insertion order for its
elements.
3. TreeSet: TreeSet extends AbstractSet and implements the NavigableSet interface. It maintains ascending order for its
elements i.e. elements will be in sorted form.
4. ArrayList: ArrayList class extends AbstractList and implements the List interface. It uses dynamic arrays for storing
elements. It maintains insertion order. ArrayList can contain duplicate elements. It is not synchronized.
5. LinkedList: LinkedList class extends AbstractSequentialList and implements the List and Deque interface. It uses
linked list data structure to store elements. It can contain duplicate elements. It is not synchronized.
6. HashMap: HashMap extends AbstractMap class and implements the Map interface. It contains the elements in keyvalue pair form. It not maintains any order for its elements. It not allowed duplicate key. A HashMap can have only
one null key and multiple null values.
7. LinkedHashMap: LinkedHashMap extends HashMap class and implements the Map interface. It contains the
elements in key-value pair form. It maintains insertion order for its elements. It not allowed duplicate key. A
LinkedHashMap can have only one null key and multiple null values.
8. TreeMap: TreeMap extends AbstractMap class and implements the NavigableMap interface. It contains the elements
in key-value pair form. It maintains ascending order for its elements. It not allowed duplicate key. A TreeMap can have
only one null key but can have multiple null values.
HashSet in java
HashSet:
HashSet extends AbstractSet and implements the Set interface. It not maintains any order for its elements. It uses hash
table for storage.
HashSet example:
HashSetTest.java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* This class is used to show the HashSet functionality.
* @author javawithease
*/
public class HashSetTest {
public static void main(String args[]){
//Create HashSet object.
Set hashSet = new HashSet();
//Add objects to the HashSet.
hashSet.add("Roxy");
hashSet.add("Sunil");
hashSet.add("Sandy");
hashSet.add("Munish");
hashSet.add("Pardeep");

//Print the HashSet object.


System.out.println("HashSet elements:");
System.out.println(hashSet);
//Print the HashSet elements using iterator.
Iterator iterator=hashSet.iterator();
System.out.println("HashSet elements using iterator:");
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
Output
HashSet elements:
[Sandy, Pardeep, Munish, Sunil, Roxy]
HashSet elements using iterator:
Sandy
Pardeep
Munish
Sunil
Roxy
Download this example.
LinkedHashSet in java
LinkedHashSet:
LinkedHashSet extends HashSet and implements the Set interface. It maintains insertion order for its elements.
LinkedHashSet example:
LinkedHashSetTest.java
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* This class is used to show the LinkedHashSet functionality.
* @author javawithease
*/
public class LinkedHashSetTest {
public static void main(String args[]){
//Create LinkedHashSet object.
Set linkedHashSet = new LinkedHashSet();
//Add objects to the LinkedHashSet.
linkedHashSet.add("Roxy");
linkedHashSet.add("Sunil");
linkedHashSet.add("Sandy");
linkedHashSet.add("Munish");
linkedHashSet.add("Pardeep");
//Print the LinkedHashSet object.

System.out.println("LinkedHashSet elements:");
System.out.println(linkedHashSet);
//Print the LinkedHashSet elements using iterator.
Iterator iterator=linkedHashSet.iterator();
System.out.println("LinkedHashSet elements " +
"using iterator:");
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
Output:
LinkedHashSet elements:
[Roxy, Sunil, Sandy, Munish, Pardeep]
LinkedHashSet elements using iterator:
Roxy
Sunil
Sandy
Munish
Pardeep
Download this example.
TreeSet in java
TreeSet:
TreeSet extends AbstractSet and implements the NavigableSet interface. It maintains ascending order for its elements i.e.
elements will be in sorted form.
TreeSet example:
TreeSetTest.java
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
/**
* This class is used to show the TreeSet functionality.
* @author javawithease
*/
public class TreeSetTest {
public static void main(String args[]){
//Create TreeSet object.
Set treeSet = new TreeSet();
//Add objects to the HashSet.
treeSet.add("Roxy");
treeSet.add("Sunil");
treeSet.add("Sandy");
treeSet.add("Munish");
treeSet.add("Pardeep");

//Print the TreeSet object.


System.out.println("TreeSet elements:");
System.out.println(treeSet);
//Print the TreeSet elements using iterator.
Iterator iterator=treeSet.iterator();
System.out.println("TreeSet elements using iterator:");
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
Output:
TreeSet elements:
[Munish, Pardeep, Roxy, Sandy, Sunil]
TreeSet elements using iterator:
Munish
Pardeep
Roxy
Sandy
Sunil
Download this example.
ArrayList in java
ArrayList:
ArrayList class extends AbstractList and implements the List interface. It uses dynamic arrays for storing elements. It
maintains insertion order. ArrayList can contain duplicate elements. It is not synchronized.
Note: ArrayList provides the facility of random access because of it is index based.
ArrayList example:
ArrayListSetTest.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* This class is used to show the ArrayList functionality.
* @author javawithease
*/
public class ArrayListTest {
public static void main(String args[]){
//Create ArrayList object.
List arrayList = new ArrayList();
//Add objects to the HashSet.
arrayList.add("Amani");
arrayList.add("Prabhjot");
arrayList.add("Nidhi");

arrayList.add("Vandana");
arrayList.add("Poonam");
//Size of the ArrayList object.
System.out.println("Size: "
+ arrayList.size());
//Print the ArrayList object.
System.out.println("ArrayList elements:");
System.out.println(arrayList);
//Print the ArrayList elements using iterator.
Iterator iterator1=arrayList.iterator();
System.out.println("ArrayList elements " +
"using iterator:");
while(iterator1.hasNext()){
System.out.println(iterator1.next());
}
//Add an object at the specific position.
arrayList.add(2,"Jagdeep");
//Remove a element from a specific position.
arrayList.remove(3);
arrayList.remove(4);
//Size of the ArrayList object.
System.out.println("Size after manipulation: "
+ arrayList.size());
//Print the ArrayList object.
System.out.println("ArrayList elements" +
" after manipulation:");
System.out.println(arrayList);
//Print the ArrayList elements using iterator.
Iterator iterator2=arrayList.iterator();
System.out.println("ArrayList elements after" +
" manipulation using iterator:");
while(iterator2.hasNext()){
System.out.println(iterator2.next());
}
}
}
Output:
Size: 5
ArrayList elements:
[Amani, Prabhjot, Nidhi, Vandana, Poonam]
ArrayList elements using iterator:
Amani
Prabhjot
Nidhi
Vandana
Poonam
Size after manipulation: 4
ArrayList elements after manipulation:
[Amani, Prabhjot, Jagdeep, Vandana]

ArrayList elements after manipulation using iterator:


Amani
Prabhjot
Jagdeep
Vandana
Download this example.
LinkedList in java
LinkedList:
The LinkedList class extends AbstractSequentialList and implements the List and Deque interface. It uses linked list data
structure to store elements. It can contain duplicate elements. It is not synchronized.
Note: It not provides the random access facility.
LinkedList example:
LinkedListTest.java
import java.util.Iterator;
import java.util.LinkedList;
/**
* This class is used to show the LinkedList functionality.
* @author javawithease
*/
public class LinkedListTest {
public static void main(String args[]){
//Create LinkedList object.
LinkedList linkedList = new LinkedList();
//Add objects to the HashSet.
linkedList.add("Amani");
linkedList.add("Prabhjot");
linkedList.add("Nidhi");
linkedList.add("Vandana");
linkedList.add("Poonam");
//Size of the LinkedList object.
System.out.println("Size: "
+ linkedList.size());
//Print the LinkedList object.
System.out.println("LinkedList elements:");
System.out.println(linkedList);
//Print the LinkedList elements using iterator.
Iterator iterator1=linkedList.iterator();
System.out.println("LinkedList elements " +
"using iterator:");
while(iterator1.hasNext()){
System.out.println(iterator1.next());
}
//Add an object at the specific position.

linkedList.add(2,"Jagdeep");
//Remove a element from a specific position.
linkedList.remove(3);
//Remove last element.
linkedList.removeLast();
//Size of the LinkedList object.
System.out.println("Size after manipulation: "
+ linkedList.size());
//Print the LinkedList object.
System.out.println("LinkedList elements " +
"after manipulation:");
System.out.println(linkedList);
//Print the LinkedList elements using iterator.
Iterator iterator2=linkedList.iterator();
System.out.println("LinkedList elements after " +
"manipulation using iterator:");
while(iterator2.hasNext()){
System.out.println(iterator2.next());
}
}
}

Output:
Size: 5
LinkedList elements:
[Amani, Prabhjot, Nidhi, Vandana, Poonam]
LinkedList elements using iterator:
Amani
Prabhjot
Nidhi
Vandana
Poonam
Size after manipulation: 4
LinkedList elements after manipulation:
[Amani, Prabhjot, Jagdeep, Vandana]
LinkedList elements after manipulation using iterator:
Amani
Prabhjot
Jagdeep
Vandana
Download this example.
HashMap in java
HashMap:

HashMap extends AbstractMap class and implements the Map interface. It contains the elements in key-value pair form.
It not maintains any order for its elements. It not allowed duplicate key. A HashMap can have only one null key and
multiple null values.
HashMap example:
HashMapTest.java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* This class is used to show the HashMap functionality.
* @author javawithease
*/
public class HashMapTest {
public static void main(String args[]){
//Create HashMap object.
Map hashMap = new HashMap();
//Add objects to the HashSet.
hashMap.put(4, "Roxy");
hashMap.put(2, "Sunil");
hashMap.put(5, "Sandy");
hashMap.put(1, "Munish");
hashMap.put(3, "Pardeep");
//Print the HashMap object.
System.out.println("HashMap elements:");
System.out.println(hashMap);
//Get iterator
Set set=hashMap.entrySet();
Iterator iterator=set.iterator();
//Print the HashMap elements using iterator.
System.out.println("HashMap elements using iterator:");
while(iterator.hasNext()){
Map.Entry mapEntry=(Map.Entry)iterator.next();
System.out.println("Key: " + mapEntry.getKey() + ", " +
"Value: " + mapEntry.getValue());
}
}
}
Output:
HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
HashMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy

Download this example.


LinkedHashMap in java
LinkedHashMap:
LinkedHashMap extends HashMap class and implements the Map interface. It contains the elements in key-value pair
form. It maintains insertion order for its elements. It not allowed duplicate key. A LinkedHashMap can have only
one null key and multiple null values.
LinkedHashMap example:
LinkedHashMapTest.java
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* This class is used to show the LinkedHashMap functionality.
* @author javawithease
*/
public class LinkedHashMapTest {
public static void main(String args[]){
//Create LinkedHashMap object.
Map linkedHashMap = new LinkedHashMap();
//Add objects to the HashSet.
linkedHashMap.put(4, "Roxy");
linkedHashMap.put(2, "Sunil");
linkedHashMap.put(5, "Sandy");
linkedHashMap.put(1, "Munish");
linkedHashMap.put(3, "Pardeep");
//Print the LinkedHashMap object.
System.out.println("LinkedHashMap elements:");
System.out.println(linkedHashMap);
//Get iterator
Set set=linkedHashMap.entrySet();
Iterator iterator=set.iterator();
//Print the LinkedHashMap elements using iterator.
System.out.println("LinkedHashMap elements " +
"using iterator:");
while(iterator.hasNext()){
Map.Entry mapEntry=(Map.Entry)iterator.next();
System.out.println("Key: " + mapEntry.getKey() +
", Value: " + mapEntry.getValue());
}
}
}
Output:
LinkedHashMap elements:

{4=Roxy, 2=Sunil, 5=Sandy, 1=Munish, 3=Pardeep}


LinkedHashMap elements using iterator:
Key: 4, Value: Roxy
Key: 2, Value: Sunil
Key: 5, Value: Sandy
Key: 1, Value: Munish
Key: 3, Value: Pardeep
Download this example.
TreeMap in java
TreeMap:
TreeMap extends AbstractMap class and implements the NavigableMap interface. It contains the elements in key-value
pair form. It maintains ascending order for its elements. It not allowed duplicate key.
Note: A TreeMap can have only one null key but can have multiple null values.
TreeMap example:
TreeMapTest.java
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* This class is used to show the TreeMap functionality.
* @author javawithease
*/
public class TreeMapTest {
public static void main(String args[]){
//Create TreeMap object.
Map treeMap = new TreeMap();
//Add objects to the TreeMap.
treeMap.put(4, "Roxy");
treeMap.put(2, "Sunil");
treeMap.put(5, "Sandy");
treeMap.put(1, "Munish");
treeMap.put(3, "Pardeep");
//Print the TreeMap object.
System.out.println("TreeMap elements:");
System.out.println(treeMap);
//Get iterator
Set set=treeMap.entrySet();
Iterator iterator=set.iterator();
//Print the TreeMap elements using iterator.
System.out.println("TreeMap elements using iterator:");
while(iterator.hasNext()){
Map.Entry mapEntry=(Map.Entry)iterator.next();
System.out.println("Key: " + mapEntry.getKey() + ", " +

"Value: " + mapEntry.getValue());


}
}
}
Output:
TreeMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
TreeMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy
Download this example.
PriorityQueue in java
PriorityQueue:
PriorityQueue extends AbstactQueue. PriorityQueue is a type of queue but not provide the FIFO facility to its elements.
It not allows the null elements.
PriorityQueue example:
PriorityQueueTest.java
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* This class is used to show the
* PriorityQueue functionality.
* @author javawithease
*/
public class PriorityQueueTest {
public static void main(String args[]){
//Create PriorityQueue object.
Queue priorityQueue = new PriorityQueue();
//Add objects to the PriorityQueue .
priorityQueue.add("Gourav");
priorityQueue.add("Neeraj");
priorityQueue.add("Deepak");
priorityQueue.add("Mohan");
priorityQueue.add("Parmender");
//Print the PriorityQueue object.
System.out.println("HasPriorityQueue elements:");
System.out.println(priorityQueue);
//Print the PriorityQueue elements using iterator.
Iterator iterator1=priorityQueue.iterator();
System.out.println("PriorityQueue elements " +

"using iterator:");
while(iterator1.hasNext()){
System.out.println(iterator1.next());
}
//Print the head element of the PriorityQueue
System.out.println("Head element: "
+ priorityQueue.element());
System.out.println("Head element: "
+ priorityQueue.peek());
//Remove the head element of the PriorityQueue
priorityQueue.poll();
priorityQueue.remove();
//Print the PriorityQueue object.
System.out.println("HasPriorityQueue elements " +
"after manipulation:");
System.out.println(priorityQueue);
//Print the PriorityQueue elements using iterator.
Iterator iterator2=priorityQueue.iterator();
System.out.println("PriorityQueue elements after " +
"manipulation using iterator:");
while(iterator2.hasNext()){
System.out.println(iterator2.next());
}
}
}
Output:
HasPriorityQueue elements:
[Deepak, Mohan, Gourav, Neeraj, Parmender]
PriorityQueue elements using iterator:
Deepak
Mohan
Gourav
Neeraj
Parmender
Head element: Deepak
Head element: Deepak
HasPriorityQueue elements after manipulation:
[Mohan, Neeraj, Parmender]
PriorityQueue elements after manipulation using iterator:
Mohan
Neeraj
Parmender
Download this example.

ArrayDeque in java
ArrayDeque:

ArrayDeque extends AbstractCollection and implements Deque. ArrayDeque are not thread safe. It not allows the null
elements.
Note: ArrayDeque are faster than Stack and LinkedList.
ArrayDeque example:
ArrayDequeTest.java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
/**
* This class is used to show the ArrayDeque functionality.
* @author javawithease
*/
public class ArrayDequeTest {
public static void main(String args[]){
//Create ArrayDeque object.
Deque arrayDeque = new ArrayDeque();
//Add objects to the ArrayDeque.
arrayDeque.add("Gourav");
arrayDeque.add("Neeraj");
arrayDeque.add("Deepak");
arrayDeque.add("Mohan");
arrayDeque.add("Parmender");
//Print the ArrayDeque object.
System.out.println("ArrayDeque elements:");
System.out.println(arrayDeque);
//Print the ArrayDeque elements using iterator.
Iterator iterator1=arrayDeque.iterator();
System.out.println("ArrayDeque elements " +
"using iterator:");
while(iterator1.hasNext()){
System.out.println(iterator1.next());
}
//Print the first element of the ArrayDeque.
System.out.println("First element: "
+ arrayDeque.getFirst());
//Print the last element of the ArrayDeque.
System.out.println("Last element: "
+ arrayDeque.getLast());
//Remove the first element of the ArrayDeque.
arrayDeque.pollFirst();
//Remove the last element of the ArrayDeque.
arrayDeque.pollLast();
//Print the ArrayDeque object.
System.out.println("ArrayDeque elements " +
"after manipulation:");
System.out.println(arrayDeque);

//Print the ArrayDeque elements using iterator.


Iterator iterator2=arrayDeque.iterator();
System.out.println("ArrayDeque elements after " +
"manipulation using iterator:");
while(iterator2.hasNext()){
System.out.println(iterator2.next());
}
}
}
Output:
ArrayDeque elements:
[Gourav, Neeraj, Deepak, Mohan, Parmender]
ArrayDeque elements using iterator:
Gourav
Neeraj
Deepak
Mohan
Parmender
First element: Gourav
Last element: Parmender
ArrayDeque elements after manipulation:
[Neeraj, Deepak, Mohan]
ArrayDeque elements after manipulation using iterator:
Neeraj
Deepak
Mohan
Download this example.
Abstract classes in collection framework
1. AbstractCollection:
AbstractCollection implements most of the Collection interface.
2. AbstractList:
AbstractList extends AbstractCollection and implements most of the List interface.
3. AbstractSequentialList:
AbstractSequentialList extends AbstractList for use by a collection that uses sequential rather than random access of its
elements.
4. AbstractSet:
AbstractSet extends AbstractCollection and implements most of the Set interface.
5. AbstractMap:
AbstractMap implements most of the Map interface.
Sorting in collection framework
Sorting:
Sorting is a process of arranging data in an increasing or decreasing order.
As we discussed earlier that TreeSet and TreeMap maintains an order for its elements. But list not provides any facility of
ordering the elements. Collections classes provides the sort() method to arrange list elements.

Note: By using sort() method we can sort the String and Wrapper class objects only but not user defined objects. It is
because String and Wrapper classes implements Comparable interface.
Example of sorting the elements of List that contains string and Wrapper class objects:
SortingTest.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
/**
* This class is used to show the sorting functionality.
* @author javawithease
*/
public class SortingTest {
public static void main(String args[]){
ArrayList arrayList1 = new ArrayList();
ArrayList arrayList2 = new ArrayList();
//Add string objects to the ArrayList.
arrayList1.add("Amani");
arrayList1.add("Prabhjot");
arrayList1.add("Nidhi");
arrayList1.add("Vandana");
arrayList1.add("Poonam");
//Add Wrapper objects to the ArrayList.
arrayList2.add(Integer.valueOf(12));
arrayList2.add(Integer.valueOf(34));
arrayList2.add(Integer.valueOf(14));
arrayList2.add(Integer.valueOf(56));
arrayList2.add(Integer.valueOf(4));
//Print the Collection string elements before sorting.
Iterator iterator1=arrayList1.iterator();
System.out.println("Collection string elements " +
"before sorting:");
while(iterator1.hasNext()){
System.out.println(iterator1.next());
}
//Call the Collections sort method for sorting
Collections.sort(arrayList1);
//Print the Collection string elements before sorting.
Iterator iterator2=arrayList1.iterator();
System.out.println("Collection string elements " +
"after sorting:");
while(iterator2.hasNext()){
System.out.println(iterator2.next());
}
//Print the Collection Wrapper elements before sorting.
Iterator iterator3=arrayList2.iterator();
System.out.println("Collection Wrapper elements " +
"before sorting:");
while(iterator3.hasNext()){
System.out.println(iterator3.next());

}
//Call the Collections sort method for sorting
Collections.sort(arrayList2);
//Print the Collection Wrapper elements before sorting.
Iterator iterator4=arrayList2.iterator();
System.out.println("Collection Wrapper elements " +
"after sorting:");
while(iterator4.hasNext()){
System.out.println(iterator4.next());
}
}
}
Output
Collection string elements before sorting:
Amani
Prabhjot
Nidhi
Vandana
Poonam
Collection string elements after sorting:
Amani
Nidhi
Poonam
Prabhjot
Vandana
Collection Wrapper elements before sorting:
12
34
14
56
4
Collection Wrapper elements after sorting:
4
12
14
34
56
Download this example.
Comparable interface in java
Comparable interface:
Comparable interface is defined in java.lang package. It has only one method namedcompareTo(Object o).Itis used to
implement natural ordering of collection elements. String and wrapper classes implements Comparable interface.
Note: We can sort the elements based on single property only. Suppose we have Student class elements with name, class
and rollNo as properties then by using comparable interface we can sort student objects based on single property only
either by name or some other one.
Method of Comparable interface:

compareTo(Object obj): It is used to compare this object with the specified object. It returns +ve integer if this object is
greater than the specified object, 0 if this object is equals to the specified object and ve integer if this object is less than
the specified object.
Syntax: public int compareTo(Object obj).
Sorting example using Comparable interface:
Student.java
/**
* This class represents a Student and
* implements Comparable.
* @author javawithease
*/
public class Student implements Comparable{
//data members
private String name;
private String rollNo;
private int age;
//no-argument constructor
public Student(){
}
//argument cnstructor
public Student(String name, String rollNo, int age){
this.name = name;
this.rollNo = rollNo;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//Method for sorting logic
public int compareTo(Object obj){
Student student=(Student)obj;
return (this.name).compareTo(student.name);
}

}
Test.java
/**
* This class is used to show the sorting functionality.
* @author javawithease
*/
public class Test {
public static void main(String args[]){
ArrayList studentList = new ArrayList();
studentList.add(new Student("Sandy", "MCA/07/06", 28));
studentList.add(new Student("Roxy", "MCA/07/32", 28));
studentList.add(new Student("Sunil", "MCA/07/15", 27));
studentList.add(new Student("Munish", "MCA/07/04", 27));
Collections.sort(studentList);
Iterator iterator=studentList.iterator();
while(iterator.hasNext()){
Student student=(Student)iterator.next();
System.out.println("Name: " + student.getName()+
", " + "RollNo: "+student.getRollNo()+
", Age: "+student.getAge());
}
}
}
Output:
Name: Munish, RollNo: MCA/07/04, Age: 27
Name: Roxy, RollNo: MCA/07/32, Age: 28
Name: Sandy, RollNo: MCA/07/06, Age: 28
Name: Sunil, RollNo: MCA/07/15, Age: 27
Download this example.
Comparator interface in java
Comparator interface:
Comparator interface is defined in java.util package. It has two methods named compare(Object obj1,Object obj2) and
equals(Object element).
Note: We can sort the elements based on multiple properties. Suppose we have Student class elements with name, class
and rollNo as properties then by using comparable interface we can sort student objects based on one or more than one
properties.
Methods of Comparator interface:
compare(Object obj1,Object obj2): It is used to compare the two objects. It returns +ve integer if first object is greater
than the second object, 0 if first object is equals to the second object and ve integer if first object is less than the second
object.
Syntax: public int compare(Object obj1,Object obj2).

Sorting example using Comparable interface:


Student.java
/**
* This class represents a Student.
* @author javawithease
*/
public class Student {
//data members
private String name;
private String rollNo;
private int age;
//no-argument constructor
public Student(){
}
//argument constructor
public Student(String name, String rollNo, int age){
this.name = name;
this.rollNo = rollNo;
this.age = age;
}
//getter setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
StudentNameComparator.java
import java.util.Comparator;
/**
* This class is used to sort student objects by name.
* @author javawithease
*/
public class StudentNameComparator implements Comparator{
public int compare(Object obj1, Object obj2) {
Student student1=(Student)obj1;

Student student2=(Student)obj2;
return (student1.getName()).
compareTo(student2.getName());
}
}
StudentAgeComparator.java
import java.util.Comparator;
/**
* This class is used to sort student objects by age.
* @author javawithease
*/
public class StudentAgeComparator implements Comparator{
public int compare(Object obj1, Object obj2) {
Student student1=(Student)obj1;
Student student2=(Student)obj2;
if(student1.getAge()==student2.getAge())
return 0;
else if(student1.getAge()&gt;student2.getAge())
return 1;
else
return -1;
}
}
Output
Sorting by student name:
Name: Munish, RollNo: MCA/07/04, Age: 27
Name: Roxy, RollNo: MCA/07/32, Age: 28
Name: Sandy, RollNo: MCA/07/06, Age: 29
Name: Sunil, RollNo: MCA/07/15, Age: 26
Sorting by student age:
Name: Sunil, RollNo: MCA/07/15, Age: 26
Name: Munish, RollNo: MCA/07/04, Age: 27
Name: Roxy, RollNo: MCA/07/32, Age: 28
Name: Sandy, RollNo: MCA/07/06, Age: 29
Download this example.
Properties class in java
Properties class:
Properties class is used to maintain the data in key value form. It takes both key and value as a string. Properties class is a
subclass of Hashtable. It provides the methods to store properties in a properties file and to get the properties from the
properties file. System.getProperties() returns the all system properties.
Properties class example:
PropertiesTest.java

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
/**
* This class is used to show the simple
* Properties class example.
* @author javawithease
*/
public class PropetiesTest {
public static void main(String[] args) {
Properties prop = new Properties();
Set props;
String str;
//Set the properties value
prop.setProperty("database", "oracle10g");
prop.setProperty("username", "system");
prop.setProperty("password", "oracle");
//Get key set
props = prop.keySet();
//Print the properties
Iterator iterator = props.iterator();
while(iterator.hasNext()) {
str = (String) iterator.next();
System.out.println("Prpperty: " + str +
", Property Value: " + prop.getProperty(str));
}
}
}
Output:
Prpperty: password, Property Value: oracle
Prpperty: database, Property Value: oracle10g
Prpperty: username, Property Value: system
Download this example.
Properties class example to write properties in a properties file and read it:
PropertiesTest.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
/**
* This class is used to write properties in a properties

* file and read it.


* @author javawithease
*/
public class PropetiesTest {
public static void main(String[] args) {
Properties prop = new Properties();
Set props;
String str;
//Set the properties value
prop.setProperty("database", "oracle10g");
prop.setProperty("username", "system");
prop.setProperty("password", "oracle");
//Save properties to the project root folder
try {
OutputStream output =
new FileOutputStream("info.properties");
prop.store(output, null);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
//Load the properties file
Properties infoProp = new Properties();
try {
InputStream input =
new FileInputStream("info.properties");
infoProp.load(input);
input.close();
} catch (IOException e) {
e.printStackTrace();
}
//Get key set
props = infoProp.keySet();
//Print the properties
Iterator iterator = props.iterator();
while(iterator.hasNext()) {
str = (String) iterator.next();
System.out.println("Prpperty: " + str +
", Property Value: " + infoProp.getProperty(str));
}
}
}
Output:
Prpperty: password, Property Value: oracle
Prpperty: database, Property Value: oracle10g
Prpperty: username, Property Value: system
Download this example.
Properties class example to get system properties:

PropertiesTest.java
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
/**
* This class is used to get the system properties
* using Properties class.
* @author javawithease
*/
public class PropetiesTest {
public static void main(String[] args) {
//Get system properties.
Properties prop = System.getProperties();
Set props;
String str;
//Get key set
props = prop.keySet();
//Print the properties
Iterator iterator = props.iterator();
while(iterator.hasNext()) {
str = (String) iterator.next();
System.out.println("Prpperty: " + str +
", Property Value: " + prop.getProperty(str));
}
}
}
Output:
Prpperty: java.runtime.name, Property Value:
Java(TM) SE Runtime Environment
Prpperty: sun.boot.library.path, Property Value:
C:\Program Files (x86)\Java\jre7\bin
Prpperty: java.vm.version, Property Value: 23.25-b01
Prpperty: java.vm.vendor, Property Value:
Oracle Corporation
Prpperty: java.vendor.url, Property Value:
http://java.oracle.com/
Prpperty: path.separator, Property Value: ;
Prpperty: java.vm.name, Property Value:
Java HotSpot(TM) Client VM
Prpperty: file.encoding.pkg, Property Value: sun.io
Prpperty: user.country, Property Value: IN
Prpperty: user.script, Property Value:
Prpperty: sun.java.launcher, Property Value: SUN_STANDARD
...
Download this example.
Hashtable in java
Hashtable:

Hashtable extends Dictionary class and implements Map interface. It contains elements in key-value pair. It not allowed
duplicate key. It is synchronized. It cant contain null key or value. It uses hashcode() method for finding the position of
the elements.
Hashtable example:
HashtableTest.java
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* This class is used to show the Hashtable functionality.
* @author javawithease
*/
public class HashtableTest {
public static void main(String args[]){
//Create Hashtable object.
Hashtable hashtable = new Hashtable();
//Add objects to the Hashtable.
hashtable.put(2,"Bharat");
hashtable.put(1,"Richi");
hashtable.put(5,"Sahdev");
hashtable.put(3,"Rajesh");
hashtable.put(4,"Himanshu");
//Print the Hashtable object.
System.out.println("Hashtable elements:");
System.out.println(hashtable);
//Get iterator
Set set=hashtable.entrySet();
Iterator iterator=set.iterator();
//Print the Hashtable elements using iterator.
System.out.println("Hashtable elements using iterator:");
while(iterator.hasNext()){
Map.Entry mapEntry=(Map.Entry)iterator.next();
System.out.println("Key: " + mapEntry.getKey() +
", " + "Value: " + mapEntry.getValue());
}
}
}
Output:
Hashtable elements:
{5=Sahdev, 4=Himanshu, 3=Rajesh, 2=Bharat, 1=Richi}
Hashtable elements using iterator:
Key: 5, Value: Sahdev
Key: 4, Value: Himanshu
Key: 3, Value: Rajesh
Key: 2, Value: Bharat
Key: 1, Value: Richi

Download this example.


ListIterator interface in java
ListIterator:
ListIterator interface is used to traverse the elements in both forward and backward directions.
Note: Can traverse elements in both forward and backward directions.
Commonly Used methods of ListIterator Interface:
1. hasNext(): Returns true if iterator has more elements in forward direction otherwise returns false.
Syntax: public boolean hasNext().
2. next(): Returns the element and point to the next element.
Syntax: public object next().
3. hasPrevious(): Returns true if iterator has more elements in back direction otherwise returns false.
Syntax: public boolean hasPrevious().
4. previous(): Returns the element and point to the previous element.
Syntax: public object ne previous().
ListIterator interface example:
ListIteratorTest.java
import java.util.ArrayList;
import java.util.ListIterator;
/**
* This class is used to show the ListIterator functionality.
* @author javawithease
*/
public class ListIteratorTest {
public static void main(String args[]){
//Create ArrayList object.
ArrayList arrayList = new ArrayList();
//Add objects to the HashSet.
arrayList.add("Amani");
arrayList.add("Prabhjot");
arrayList.add("Nidhi");
arrayList.add("Vandana");
arrayList.add("Poonam");
//Get the ListIterator object.
ListIterator listIterator=arrayList.listIterator();

//Print the ArrayList elements in forward direction.


System.out.println("ArrayList elements in " +
"forward direction:");
while(listIterator.hasNext()){
System.out.println(listIterator.next());
}
//Print the ArrayList elements in backward direction.
System.out.println("ArrayList elements in " +
"backward direction:");
while(listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}
}
}
Output:
ArrayList elements in forward direction:
Amani
Prabhjot
Nidhi
Vandana
Poonam
ArrayList elements in backward direction:
Poonam
Vandana
Nidhi
Prabhjot
Amani
Download this example.

You might also like