1core Java
1core Java
1core Java
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.
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.
/*
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.
*/
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]
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.
{
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.
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.
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.
*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.
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("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.
//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.
| --->*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
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.
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:
/**
* 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.
/**
* 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
*/
}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.
}
}
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
4. Click on new.
6. Paste this path in variable value and write path in variable name. Click ok.
7. Click ok.
8. Click ok.
*/
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.
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();
1.
2.
3.
* @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();
1.
2.
* @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
*/
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:
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
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.
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.
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.
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
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.
1.
2.
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.
Output:
Name = jai
Age = 26
RollNo = 4
Download this example.
Methods of an interface are public abstract by default.
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.
2.
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
}
(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);
Method
1. It may or may not have same name as
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 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 {
* @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
*/
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
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.
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
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.
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
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);
}
}
}
//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:
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.
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("");
}
}
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
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.");
}
}
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:
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).
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";
/**
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.
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.
* @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.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16
17
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
}
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[]){
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): 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[]){
}
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.
}
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.
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.
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.
/**
* 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
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.
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.
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){
catch block:
Catch block is used for exception handler. It is used after try block.
Syntax :
try{
//block of statements
}catch(Exception handler class){
}
*/
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.
//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{
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{
}
}
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.
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
*/
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
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{
*/
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
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.
* @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.
/**
* 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)
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) {
} 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.
1.
2.
2.
}
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.
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.
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.
//method call
obj.writeFile();
}
}
Output:
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.
ii.
iii.
}
}
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 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{
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{
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.
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 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)
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.
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:
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.
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");
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]
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
"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);
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).
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()>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
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