0% found this document useful (0 votes)
465 views314 pages

Core Java

The document provides an overview of the basics of the Java programming language. It discusses what Java is, its history and origins, its major features such as being object-oriented, platform independent and secure. It also covers Java applications and versions, and provides descriptions of key concepts in Java like objects, classes, inheritance and polymorphism. The document serves as an introduction to the Java language for learning purposes.

Uploaded by

sakshi aggarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
465 views314 pages

Core Java

The document provides an overview of the basics of the Java programming language. It discusses what Java is, its history and origins, its major features such as being object-oriented, platform independent and secure. It also covers Java applications and versions, and provides descriptions of key concepts in Java like objects, classes, inheritance and polymorphism. The document serves as an introduction to the Java language for learning purposes.

Uploaded by

sakshi aggarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 314

Jai Ma Saraswati

Index
Basics of Java
 What is Java?
 History of Java
 Features of Java
 Hello Java Program
 Program Internal
 How to set path?
 Difference between JDK,JRE and JVM
 Internal Details of JVM
 Variable and Data Type
 Unicode System
 Language Fundamentals
OOPs Concepts
 Advantage of OOPs
 Naming Convention
 Object and Class
 Method Overloading
 Constructor
 static keyword
 this keyword
 Inheritance(IS-A)
 Aggregation(HAS-A)
 Method Overriding
 Covariant Return Type
 super keyword
 Instance Initializer block
 final keyword
 Runtime Polymorphism
 Dynamic Binding
 instanceof operator
 Abstract class
 Interface
 Package
 Access Modifiers
 Encapsulation
 Object class
 Object Cloning
 Java Array
 Call By Value

Jai Ma Saraswati

 strictfp keyword
 API Document
 Command Line Arg
String Handling
Exception Handling
Nested Classes
Multithreading
Synchronization
I/O
Serialization
Collection
JDBC
Java New Features

Java Tutorial
Java technology is widely used currently.
What is Java?
Java is a programming language and a platform.
Platform:- Any hardware or software environment in which a program runs, known as a platform. Since
Java has its own Runtime Environment (JRE) and API, it is called platform.

Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some
of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as www.irctc.co.in etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.

Types of Java Applications


There are mainly 4 type of applications that can be created using java:
1) Standalone Application
It is also known as desktop application or window-based application. An application that we need to
install on every machine such as media player, antivirus etc. AWT and Swing are used in java for
creating standalone applications.

Jai Ma Saraswati

2) Web Application
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage of high
level security, load balancing and clustering. In java, EJB is used for creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for creating
mobile applications.

History of Java
Java history is interesting to know. Java team members were also known as Green Team.
In 1990, Sun Microsystems Inc. (US) has conceived a project to develop software for consumer
electronic devices (digital devices such as set-top boxes, televisions) that could be controlled by a
remote. This project was called Stealth Project but later its name was changed to Green Project.
In Jan of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton and several others met
in Aspen, Colorado to discuss this project.
Mike Sheradin-Business Development,
Patrick Naughton-Graphics systems
James Gosling -proper programming language for the project.

Gosling thought C and C++ could be used to develop the project. But the problem he faced with
them is that they were system dependent languages and hence could not be used various
processors which the electronics devices might use. So he start to develop a new language
which was completely system independent. This language was initially called as OAK. Since this
name was registered by other company, later it was changed to JAVA.

James Gosling
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There
are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.

Why Oak name for java language?


Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Jai Ma Saraswati

Why Java name for java language?


Why they choosed java name for java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted something
that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to
spell and fun to say.
Note:- James Gosling and his team members were consuming a lot of coffee while developing
this language. They felt that they were able to develop a better language because of the good
quality of coffee they consumed. So the coffee had its own role in developing this language and
good quality of coffee was exported to the entire world from a place called 'JAVA ISLAND'. Hence
they fixed the name of the place for the language as JAVA. And the symbol for JAVA Language is
coffee cup and saucer.
According to James Gosling "Java was one of the top choices along with Silk". Since java was so
unique, most of the team members preferred java.
Java is an island of Indonesia where first coffee was produced (called java coffee).
Notice that Java is just a name not an acronym.
Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
In 1995, Time magazine called Java one of the Ten Best Products of 1995.
JDK 1.0 released in(January 23, 1996).

Java Version History


There are many java versions that has been released.
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 (14 april 2014)

Features of Java
There is given many features of java. They are also known as java buzzwords.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic

Jai Ma Saraswati

9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed

Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.

Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that have
both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent
A platform is the hardware or software environment in which a program runs. There are two types of
platforms software-based and hardware-based. Java provides software-based platform. The Java
platform differs from most other platforms in the sense that it's a software-based platform that runs on top
of other hardware-based platforms.It has two components:
1. Runtime Environment
2. API(Application Programming Interface)

Jai Ma Saraswati

Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc. Java code is
compiled by the compiler and converted into bytecode.This bytecode is a platform independent code
because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).

Secured
Java is secured because:
 No explicit pointer
 Programs run inside virtual machine sandbox.

 Classloader- adds security by separating the package for the classes of the local file system from
those that are imported from network sources.
 Bytecode Verifier- checks the code fragments for illegal code that can violate access right to
objects.
 Security Manager- determines what resources a class can access such as reading and writing to
the local disk.
These security are provided by java language. Some security can also be provided by application

Jai Ma Saraswati

developer through SSL,JAAS,cryptography etc.

Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that
avoids security problem. There is automatic garbage collection in java. There is exception handling and
type checking mechanism in java. All these points makes java robust.

Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.

Portable
We may carry the java bytecode to any platform.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat
slower than a compiled language (e.g., C++)

Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares
the same memory. Threads are important for multi-media, Web applications etc.

Simple Program of Java


To create a simple java program, you need to create a class that contains main method. Let's understand
the requirement first.
Requirement for Hello Java Example
For executing any java program, you need to
 install the JDK if you don't have installed it, download the JDK and install it.
 set path of the jdk/bin directory
 create the java program
 compile and run the java program

Creating hello java example


Let's create the hello java program:
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");

Jai Ma Saraswati

4. }
5. }

save this file as Simple.java

To compile: javac Simple.java


To execute: java Simple
Output:Hello Java

Understanding first java program


public static void main(String args[]).

What is the Importance of the public static void main(String args[ ])


Whether a class contains main( ) or not and whether the main( ) is declared based on requirement,
these all are things are won't be checked by compiler,these things are checked by JVM at Runtime.

Note: If JVM is unable to find main( ) then we will get a Runtime Exception saying : Exception in thread
"main" java.lang.NoSuchMethodError: main

Here we can observe that's why the main( ) prototype must be public static void main(String args[]) Let's
see .

public: JVM calls main( ) from anywhere, so it should be public

static: without creating object also JVM has to call this method.

void: here main( ) won't return anything to JVM

main( ): this is the method which has configured already in the JVM

String[] args: commandline- arguments in the form of array of instances of the class String

In this we can have several possibility changes to form main method

Change 1: The Order of the modifiers is not important, i.e instead of public static ,we can use static
public also.
Change 2: We can declare String array in any acceptable form i.e
(String[] args)

Jai Ma Saraswati

(String []args)
(String args[])
Change 3: Instead of 'args' we should take any java valid identifier

public class Test {


public static void main(String ramu[]) {
System.out.println("Hello Test");
}
}
the above code will execute without error.
Change 4: We can replace 'String[] args' with 'var-args' parameter. i.e
main(String[] args) to main(String...args)

public class Test {


public static void main(String...args) {
System.out.println("Hello Test");
}
}
Here the arguments we can pass three dots as shown above.

Change 5: We can declare main( ) with the following modifiers also

 final
 synchronized
 strictfp
The following program consits of all above changes.
public class Test {
final synchronized strictfp static public void main(String... args) {
System.out.println("This is acceptable main method");
}
}
This class will print the value without any error.
Here some more information about main method
Case 1: Overloading of the main( ) is possible,But JVM always call (String[] args) of main( ) only see
below Example.
public class Test {
public static void main(String[] args) {

Jai Ma Saraswati

System.out.println("String[]");
}

public static void main(int[] args) {


System.out.println("int[]");
}
}
Output: String[]
Here we can say that above method is Overloaded. Method names are same with different signatures.
Case 2: Inheritance is possible/applicable on main( ),while executing child class ,if child class doesn't
contains main( ),then parent main( ) will be executed.
public class Test {
public static void main(String args[]) {
System.out.println("I am from main()");
}
}
class Demo extends Test {
}
w.r.to{java test} parent class: Output: iam from main( )
w.r.to {java Demo}child class: Output: iam from main( )
Case 3: It seems Overriding concept is applicable for main( ),but it is not Overriding it is method hiding.
class Test {
public static void main(String args[]) {
System.out.println("iam from Test");
}
}

class Demo extends Test {


public static void main(String[] args) {
System.out.println("iam from Demo");
}
}
w.r.to Parent: Output: I am from Test
w.r.to Child: Output: I am from Demo
Note: Overloading and inheritence is applicable for main method. But overriding concept is not
applicable,instead of overriding concept method hiding concept is applicable.

Jai Ma Saraswati

Interview Question on main method is given below take a look on it.


Which of the following are valid main( ) declarations as shown bellow?
1) public static void Main(String args[])
[invalid because in main the letter M is Capital]
2) public static int main(String[] args )
[invalid because the main method is return int value]
3) public static void main(string args))
[invalid because the String arr[] is not declared]
4) public final synchronized strictfp void main(String...args)
[invalid because static is missing]
5) public static void main(String...args)
[Valid]
6) public static final synchronized strictfp void main(String...args)
[Valid]

Internal Details of Hello Java Program


What happens at compile time?
At compile time, java file is compiled by Java Compiler (It does not interact with OS) and converts the
java code into bytecode.

What happens at runtime?


At runtime, following steps are performed:

Jai Ma Saraswati

Classloader: is the subsystem of JVM that is used to load class files.


Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.
Interpreter: read bytecode stream then execute the instructions.
Q)Can you save a java source file by other name than the class name?
Yes, like the figure given below illustrates:

To compile: javac Hard.java


To execute: java Simple
Q)Can you have multiple classes in a java source file?
Yes, like the figure given below illustrates:

Jai Ma Saraswati

How to set path in Java


The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required to be set because all
the tools will be available in the current directory.
But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.
There are 2 ways to set java path:
1. temporary
2. permanent
1) How to set Temporary Path of JDK in Windows
To set the temporary path of JDK, you need to follow following steps:
 Open command prompt
 copy the path of jdk/bin directory
 write in command prompt: set path=copied_path
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
2) How to set Permanent Path of JDK in Windows
For setting the permanent path of JDK, you need to follow these steps:
 Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user
variable -> write path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok

Difference between JDK, JRE and JVM


Understanding the difference between JDK, JRE and JVM is important in Java.

JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment

Jai Ma Saraswati

JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the
implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at
runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.

JVM (Java Virtual Machine)


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).
Note:-Oracle Corporation, the owner of the Java trademark, produces the most widely used JVM, named
HotSpot, that is written in the C++ programming language. JVMs using the Java trademark may also be
developed by other companies as long as they adhere to the JVM specification published by Oracle
Corporation and to related contractual obligations.

Jai Ma Saraswati

What is JVM?
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation provider
is independent to choose the algorithm. Its implementation has been provided by Sun and other
companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java
class, and instance of JVM is created.
What it does?
The JVM performs following operation:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
JVM provides definitions for the:
 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

Internal Architecture of JVM


Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine
etc.

1) Classloader: (load .class files)


Classloader is a subsystem of JVM that is used to load class files.

Jai Ma Saraswati

2) Class(Method) Area(per class structure stores)


Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap: (objects are allocated)
It is the runtime data area in which objects are allocated.
4) Stack: (all the method and method data invoked)
Java Stack stores frames.It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
5) Program Counter Regiser: (contain address of JVM instruction that is currently being executed)
PC (program counter) register. It contains the address of the Java virtual machine instruction currently
being executed.
6) Native Method Stack: (contains all the native method of application)
It contains all the native methods used in the application.
7) Execution Engine: (Read bytecode stream then execute the instructions.)
It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the byte code
that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.

Variable and Datatype in Java


Variable is a name of memory location. There are three types of variables: local, instance and static.
There are two types of datatypes in java, primitive and non-primitive.

Variable
Variable is name of reserved area allocated in memory.

Jai Ma Saraswati

int data=50;//Here data is variable

Types of Variable
There are three types of variables in java
 local variable
 instance variable
 static variable

Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is not
declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
Example to understand the types of variables

class A{

int data=50;//instance variable

static int m=100;//static variable

void method(){
int n=90;//local variable
}

}//end of class

Data Types in Java


In java, there are two types of data types
 primitive data types

Jai Ma Saraswati

 non-primitive data types

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

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


because java uses unicode system rather than ASCII code system. \u0000 is the lowest range of
unicode system.
Unicode System
Unicode is a universal international standard character encoding that is capable of representing most of
the world's written languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
 ASCII (American Standard Code for Information Interchange) for the United States.
 ISO 8859-1 for Western European Language.
 KOI-8 for Russian.

Jai Ma Saraswati

 GB18030 and BIG-5 for chinese, and so on.


This caused two problems:
1. A particular code value corresponds to different letters in the various language standards.
2. The encodings for languages with large character sets have variable length.Some common
characters are encoded as single bytes, other require two or more byte.
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF

Operators in java
Operator is a special symbol that is used to perform operations. There are many types of operators in
java such as unary operator, arithmetic operator, relational operator, shift operator, bitwise operator,
ternary operator and assignment operator.

Precedence of Operators
Operators Precedence

postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

multiplicative */%

additive +-

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&



Jai Ma Saraswati

logical OR ||

ternary ?:

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Basic Operators in Java


Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators

The Arithmetic Operators:


Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then:
Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give 30
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
* Multiplication - Multiplies values on either side of the operator A * B will give 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Modulus - Divides left hand operand by right hand operand and returns
% B % A will give 0
remainder
++ Increment - Increase the value of operand by 1 B++ gives 21
-- Decrement - Decrease the value of operand by 1 B-- gives 19

The Relational Operators:


There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
Checks if the value of two operands are equal or not, if yes then condition
== (A == B) is not true.
becomes true.

Jai Ma Saraswati

Checks if the value of two operands are equal or not, if values are not
!= (A != B) is true.
equal then condition becomes true.
Checks if the value of left operand is greater than the value of right
> (A > B) is not true.
operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand,
< (A < B) is true.
if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of
<= (A <= B) is true.
right operand, if yes then condition becomes true.

The Bitwise Operators:


Java defines several bitwise operators which can be applied to the integer types, long, int, short, char,
and byte.
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in
binary format they will be as follows:

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators:

Assume integer variable A holds 60 and variable B holds 13 then:


Operator Description Example
Binary AND Operator copies a bit to the result if it exists in (A & B) will give 12 which is 0000
&
both operands. 1100
| Binary OR Operator copies a bit if it exists in eather operand. (A | B) will give 61 which is 0011

Jai Ma Saraswati

1101
Binary XOR Operator copies the bit if it is set in one operand (A ^ B) will give 49 which is 0011
^
but not both. 0001
Binary Ones Complement Operator is unary and has the (~A ) will give -60 which is 1100
~
efect of 'flipping' bits. 0011
Binary Left Shift Operator. The left operands value is moved A << 2 will give 240 which is 1111
<<
left by the number of bits specified by the right operand. 0000
Binary Right Shift Operator. The left operands value is
>> moved right by the number of bits specified by the right A >> 2 will give 15 which is 1111
operand.
Shift right zero fill operator. The left operands value is moved
A >>>2 will give 15 which is 0000
>>>> right by the number of bits specified by the right operand and
1111
shifted values are filled up with zeros.

The Logical Operators:


The following table lists the logical operators:
Assume boolean variables A holds true and variable B holds false then:
Operator Description Example
Called Logical AND operator. If both the operands are non zero then then
&& (A && B) is false.
condition becomes true.
Called Logical OR Operator. If any of the two operands are non zero then then
|| (A || B) is true.
condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state of its operand.
! !(A && B) is true.
If a condition is true then Logical NOT operator will make false.

The Assignment Operators:


There are following assignment operators supported by Java language:
Operator Description Example
Simple assignment operator, Assigns values from right C = A + B will assigne value of A + B
=
side operands to left side operand into C
Add AND assignment operator, It adds right operand to
+= C += A is equivalent to C = C + A
the left operand and assign the result to left operand
Subtract AND assignment operator, It subtracts right
-= operand from the left operand and assign the result to C -= A is equivalent to C = C - A
left operand

Jai Ma Saraswati

Multiply AND assignment operator, It multiplies right


*= operand with the left operand and assign the result to C *= A is equivalent to C = C * A
left operand
Divide AND assignment operator, It divides left
/= operand with the right operand and assign the result to C /= A is equivalent to C = C / A
left operand
Modulus AND assignment operator, It takes modulus
%= using two operands and assign the result to left C %= A is equivalent to C = C % A
operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Misc Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands and
is used to evaluate boolean expressions. The goal of the operator is to decide which value should be
assigned to the variable. The operator is written as :
view plainprint?
1. variable x = (expression) ? value if true : value if false

Following is the example:


view plainprint?
1. public class Test {
2.
3. public static void main(String args[]){
4. int a , b;
5. a = 10;
6. b = (a == 1) ? 20: 30;
7. System.out.println( "Value of b is : " + b );
8.
9. b = (a == 10) ? 20: 30;
10. System.out.println( "Value of b is : " + b );
11. }
12. }
This would produce following result:

Jai Ma Saraswati

output:
Value of b is : 30
Value of b is : 20

instanceOf Operator:
This operator is used only for object reference variables. The operator checks whether the object is of a
particular type(class type or interface type). instanceOf operator is written as:
view plainprint?
1. ( Object reference variable ) instanceOf (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side then the result will be true. Following is the example:
view plainprint?
1. String name = = "Dinesh";
2. boolean result = name instanceOf String;
3. // This will return true since name is type of String
This operator will still return true if the object being compared is the assignment compatible with the type
on the right. Following is one more example:
view plainprint?
1. class Vehicle {}
2.
3. public class Car extends Vehicle {
4. public static void main(String args[]){
5. Vehicle a = new Car();
6. boolean result = a instanceof Car;
7. System.out.println( result);
8. }
9. }
This would produce following result:
output:
true

Precedence of Java Operators:


Operator precedence determines the grouping of terms in an expression. This affects how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace
than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom. Within an expression, higher precedenace operators will be evaluated first.

Jai Ma Saraswati

Control Statements in Java


we are going to discuss the control statements. Different types of control statements: the decision
making statements (if-then, if-then-else and switch), looping statements (while, do-while and for) and
branching statements (break, continue, return) supported by the Java programming language.

Control Statements:
The control statement are used to controll the flow of execution of the program . This execution order
depends on the supplied data values and the conditional logic. Java contains the following types of
control statements:

1- Selection Statements
2- Repetition Statements
3- Branching Statements

Selection Statements(The if-then and if-then-else Statements):


The if-then Statement:
The if-then statement is the most basic of all the control flow statements. It tells your program to execute
a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could
allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible
implementation of the applyBrakes method could be as follows:

Syntax:
if(conditional_expression){
<statements>;
...;
...;
}

view plainprint?
1. void applyBrakes() {
2. // the "if" clause: bicycle must be moving
3. if (isMoving){
4. // the "then" clause: decrease current speed
5. currentSpeed--;
6. }
7. }
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-
then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause contains only
one statement:

Jai Ma Saraswati

view plainprint?
1. void applyBrakes() {
2. // same as above, but without braces
3. if (isMoving)
4. currentSpeed--;
5. }
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more
brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting
to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong
results.

The if-then-else Statement:


The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false.
You could use anif-then-else statement in the applyBrakes method to take some action if the brakes are
applied when the bicycle is not in motion. In this case, the action is to simply print an error message
stating that the bicycle has already stopped.

Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
else{
<statements>;
....;
....;
}
view plainprint?
1. void applyBrakes() {
2. if (isMoving) {
3. currentSpeed--;
4. } else {
5. System.err.println("The bicycle has " + "already stopped!");
6. }
7. }
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score
of 90% or above, a B for a score of 80% or above, and so on.
view plainprint?
1. class IfElseDemo {
2. public static void main(String[] args) {
3.
4. int testscore = 76;
5. char grade;
6.
7. if (testscore >= 90) {

Jai Ma Saraswati

8. grade = 'A';
9. } else if (testscore >= 80) {
10. grade = 'B';
11. } else if (testscore >= 70) {
12. grade = 'C';
13. } else if (testscore >= 60) {
14. grade = 'D';
15. } else {
16. grade = 'F';
17. }
18. System.out.println("Grade = " + grade);
19. }
20. }
The output from the program is:
Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the compound
statement: 76 >= 70and 76 >= 60. However, once a condition is satisfied, the appropriate statements are
executed (grade = 'C';) and the remaining conditions are not evaluated.

The switch Statement:


Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution
paths. Aswitch works with the byte, short, char, and int primitive data types. It also works
with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap
certain primitive types: Character, Byte, Short, andInteger (discussed in Numbers and Strings).
The following code example, SwitchDemo, declares an int named month whose value represents a
month. The code displays the name of the month, based on the value of month, using
the switch statement.

Syntax:
switch(control_expression){
case expression 1:
<statement>;
case expression 2:
<statement>;
...
...
case expression n:
<statement>;
default:
<statement>;

Jai Ma Saraswati

}//end switch

view plainprint?
1. public class SwitchDemo {
2. public static void main(String[] args) {
3.
4. int month = 8;
5. String monthString;
6. switch (month) {
7. case 1: monthString = "January";
8. break;
9. case 2: monthString = "February";
10. break;
11. case 3: monthString = "March";
12. break;
13. case 4: monthString = "April";
14. break;
15. case 5: monthString = "May";
16. break;
17. case 6: monthString = "June";
18. break;
19. case 7: monthString = "July";
20. break;
21. case 8: monthString = "August";
22. break;
23. case 9: monthString = "September";
24. break;
25. case 10: monthString = "October";
26. break;
27. case 11: monthString = "November";
28. break;
29. case 12: monthString = "December";
30. break;
31. default: monthString = "Invalid month";
32. break;
33. }
34. System.out.println(monthString);
35. }
36. }
In this case, August is printed to standard output.

The body of a switch statement is known as a switch block. A statement in the switch block can be
labeled with one or more case or default labels. The switch statement evaluates its expression, then
executes all statements that follow the matching case label.

You could also display the name of the month with if-then-else statements:

Jai Ma Saraswati

view plainprint?
1. int month = 8;
2. if (month == 1) {
3. System.out.println("January");
4. } else if (month == 2) {
5. System.out.println("February");
6. }
7. ... // and so on

Deciding whether to use if-then-else statements or a switch statement is based on readability and the
expression that the statement is testing. An if-then-else statement can test expressions based on ranges
of values or conditions, whereas aswitch statement tests expressions based only on a single integer,
enumerated value, or String object.
Another point of interest is the break statement. Each break statement terminates the
enclosing switch statement. Control flow continues with the first statement following the switch block.
The break statements are necessary because without them, statements in switch blocks fall through: All
statements after the matching case label are executed in sequence, regardless of the expression of
subsequent case labels, until a break statement is encountered. The
program SwitchDemoFallThroughshows statements in a switch block that fall through. The program
displays the month corresponding to the integer month and the months that follow in the year:
view plainprint?
1. public class SwitchDemoFallThrough {
2.
3. public static void main(String args[]) {
4. java.util.ArrayList<string> futureMonths =
5. new java.util.ArrayList<string>();
6.
7. int month = 8;
8.
9. switch (month) {
10. case 1: futureMonths.add("January");
11. case 2: futureMonths.add("February");
12. case 3: futureMonths.add("March");
13. case 4: futureMonths.add("April");
14. case 5: futureMonths.add("May");
15. case 6: futureMonths.add("June");
16. case 7: futureMonths.add("July");
17. case 8: futureMonths.add("August");
18. case 9: futureMonths.add("September");
19. case 10: futureMonths.add("October");
20. case 11: futureMonths.add("November");
21. case 12: futureMonths.add("December");
22. break;
23. default: break;
24. }
25.

Jai Ma Saraswati

26. if (futureMonths.isEmpty()) {
27. System.out.println("Invalid month number");
28. } else {
29. for (String monthName : futureMonths) {
30. System.out.println(monthName);
31. }
32. }
33. }
34. }
35. </string></string>

This is the output from the code:

August
September
October
November
December
Technically, the final break is not required because flow falls out of the switch statement. Using a break
is recommended so that modifying the code is easier and less error prone. The default section handles
all values that are not explicitly handled by one of the case sections.

The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The
code example calculates the number of days in a particular month:
view plainprint?
1. class SwitchDemo2 {
2. public static void main(String[] args) {
3.
4. int month = 2;
5. int year = 2000;
6. int numDays = 0;
7.
8. switch (month) {
9. case 1: case 3: case 5:
10. case 7: case 8: case 10:
11. case 12:
12. numDays = 31;
13. break;
14. case 4: case 6:
15. case 9: case 11:
16. numDays = 30;
17. break;
18. case 2:
19. if (((year % 4 == 0) &&

Jai Ma Saraswati

20. !(year % 100 == 0))


21. || (year % 400 == 0))
22. numDays = 29;
23. else
24. numDays = 28;
25. break;
26. default:
27. System.out.println("Invalid month.");
28. break;
29. }
30. System.out.println("Number of Days = "
31. + numDays);
32. }
33. }

This is the output from the code:

Number of Days = 29

Using Strings in switch Statements:

In Java SE 7 and later, you can use a String object in the switch statement's expression. The following
code example,StringSwitchDemo, displays the number of the month based on the value of the String
named month:
view plainprint?
1. public class StringSwitchDemo {
2.
3. public static int getMonthNumber(String month) {
4.
5. int monthNumber = 0;
6.
7. if (month == null) {
8. return monthNumber;
9. }
10.
11. switch (month.toLowerCase()) {
12. case "january":
13. monthNumber = 1;
14. break;
15. case "february":
16. monthNumber = 2;
17. break;
18. case "march":
19. monthNumber = 3;
20. break;

Jai Ma Saraswati

21. case "april":


22. monthNumber = 4;
23. break;
24. case "may":
25. monthNumber = 5;
26. break;
27. case "june":
28. monthNumber = 6;
29. break;
30. case "july":
31. monthNumber = 7;
32. break;
33. case "august":
34. monthNumber = 8;
35. break;
36. case "september":
37. monthNumber = 9;
38. break;
39. case "october":
40. monthNumber = 10;
41. break;
42. case "november":
43. monthNumber = 11;
44. break;
45. case "december":
46. monthNumber = 12;
47. break;
48. default:
49. monthNumber = 0;
50. break;
51. }
52.
53. return monthNumber;
54. }
55.
56. public static void main(String[] args) {
57.
58. String month = "August";
59.
60. int returnedMonthNumber =
61. StringSwitchDemo.getMonthNumber(month);
62.
63. if (returnedMonthNumber == 0) {
64. System.out.println("Invalid month");
65. } else {
66. System.out.println(returnedMonthNumber);

Jai Ma Saraswati

67. }
68. }
69. }

The output from this code is 8.

The String in the switch expression is compared with the expressions associated with each case label as
if theString.equals method were being used. In order for the StringSwitchDemo example to accept any
month regardless of case, month is converted to lowercase (with the toLowerCase method), and all the
strings associated with the case labels are in lowercase.
Note: This example checks if the expression in the switch statement is null. Ensure that the expression in
any switchstatement is not null to prevent a NullPointerException from being thrown.

Repetition Statements(The while and do-while Statements):


while loop statements:
The while statement continually executes a block of statements while a particular condition is true. Its
syntax can be expressed as:

Syntax:
while(expression){
<statement>;
...;
...;
}

The while statement evaluates expression, which must return a boolean value. If the expression
evaluates to true, the whilestatement executes the statement(s) in the while block. The while statement
continues testing the expression and executing its block until the expression evaluates to false. Using
the while statement to print the values from 1 through 10 can be accomplished as in the
following WhileDemo program:

view plainprint?
1. class WhileDemo {
2. public static void main(String[] args){
3. int count = 1;
4. while (count < 11) {
5. System.out.println("Count is: " + count);
6. count++;
7. }
8. }
9. }
You can implement an infinite loop using the while statement as follows:

Jai Ma Saraswati

view plainprint?
1. while (true){
2. // your code goes here
3. }

do-while loop statements:

This is another looping statement that tests the given condition past so you can say that the do-while
looping statement is a past-test loop statement. First the do block statements are executed then the
condition given in while statement is checked. So in this case, even the condition is false in the first
attempt, do block of code is executed at least once.
Syntax: do{ ; ...; ...; }while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the
loop instead of the top. Therefore, the statements within the do block are always executed at least once,
as shown in the following DoWhileDemoprogram:

view plainprint?
1. class DoWhileDemo {
2. public static void main(String[] args){
3. int count = 1;
4. do {
5. System.out.println("Count is: " + count);
6. count++;
7. } while (count < 11);
8. }
9. }

The for Statement:

The for statement provides a compact way to iterate over a range of values. Programmers often refer to
it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied.
The general form of the for statement can be expressed as follows:

Syntax:
for (initialization; condition; increment or decrement){
<statement>;
...;
...;
}

When using this version of the for statement, keep in mind that:
 The initialization expression initializes the loop; it's executed once, as the loop begins.
 When the termination expression evaluates to false, the loop terminates.
 The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.

Jai Ma Saraswati

The following program, ForDemo, uses the general form of the for statement to print the numbers 1
through 10 to standard output:
view plainprint?
1. class ForDemo {
2. public static void main(String[] args){
3. for(int i=1; i<11; i++){
4. System.out.println("Count is: " + i);
5. }
6. }
7. }
The output of this program is:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this variable
extends from its declaration to the end of the block governed by the for statement, so it can be used in
the termination and increment expressions as well. If the variable that controls a for statement is not
needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j,
and k are often used to control for loops; declaring them within the initialization expression limits their life
span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
view plainprint?
1. // infinite loop
2. for ( ; ; ) {
3.
4. // your code goes here
5. }
The for statement also has another form designed for iteration through Collections and arrays This form
is sometimes referred to as the enhanced for statement, and can be used to make your loops more
compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1
through 10:
view plainprint?
1. int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
view plainprint?
1. class EnhancedForDemo {
2. public static void main(String[] args){

Jai Ma Saraswati

3. int[] numbers =
4. {1,2,3,4,5,6,7,8,9,10};
5. for (int item : numbers) {
6. System.out.println("Count is: " + item);
7. }
8. }
9. }
In this example, the variable item holds the current value from the numbers array. The output from this
program is the same as before:
output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We recommend using this form of the for statement instead of the general form whenever possible.

Branching Statements:

The break Statement:


The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous
discussion of the switchstatement. You can also use an unlabeled break to terminate a for, while, or do-
while loop, as shown in the followingBreakDemo program:

Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
view plainprint?
1. class BreakDemo {
2. public static void main(String[] args) {
3.
4. int[] arrayOfInts =
5. { 32, 87, 3, 589,

Jai Ma Saraswati

6. 12, 1076, 2000,


7. 8, 622, 127 };
8. int searchfor = 12;
9.
10. int i;
11. boolean foundIt = false;
12.
13. for (i = 0; i < arrayOfInts.length; i++) {
14. if (arrayOfInts[i] == searchfor) {
15. foundIt = true;
16. break;
17. }
18. }
19.
20. if (foundIt) {
21. System.out.println("Found " + searchfor + " at index " + i);
22. } else {
23. System.out.println(searchfor + " not in the array");
24. }
25. }
26. }
This program searches for the number 12 in an array. The break statement, shown in boldface,
terminates the for loop when that value is found. Control flow then transfers to the statement after the for
loop. This program's output is:
output:
Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a
labeled breakterminates an outer statement. The following program, BreakWithLabelDemo, is similar to
the previous program, but uses nestedfor loops to search for a value in a two-dimensional array. When
the value is found, a labeled break terminates the outer for loop (labeled "search"):
view plainprint?
1. class BreakWithLabelDemo {
2. public static void main(String[] args) {
3.
4. int[][] arrayOfInts = {
5. { 32, 87, 3, 589 },
6. { 12, 1076, 2000, 8 },
7. { 622, 127, 77, 955 }
8. };
9. int searchfor = 12;
10.
11. int i;
12. int j = 0;
13. boolean foundIt = false;
14.

Jai Ma Saraswati

15. search:
16. for (i = 0; i < arrayOfInts.length; i++) {
17. for (j = 0; j < arrayOfInts[i].length;
18. j++) {
19. if (arrayOfInts[i][j] == searchfor) {
20. foundIt = true;
21. break search;
22. }
23. }
24. }
25.
26. if (foundIt) {
27. System.out.println("Found " + searchfor + " at " + i + ", " + j);
28. } else {
29. System.out.println(searchfor + " not in the array");
30. }
31. }
32. }
This is the output of the program.
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the label.
Control flow is transferred to the statement immediately following the labeled (terminated) statement.

The continue Statement:

The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form
skips to the end of the innermost loop's body and evaluates the boolean expression that controls the
loop. The following program, ContinueDemo , steps through a String, counting the occurences of the
letter "p". If the current character is not a p, the continue statement skips the rest of the loop and
proceeds to the next character. If it is a "p", the program increments the letter count.
view plainprint?
1. class ContinueDemo {
2. public static void main(String[] args) {
3.
4. String searchMe = "peter piper picked a " + "peck of pickled peppers";
5. int max = searchMe.length();
6. int numPs = 0;
7.
8. for (int i = 0; i < max; i++) {
9. // interested only in p's
10. if (searchMe.charAt(i) != 'p')
11. continue;
12.
13. // process p's
14. numPs++;

Jai Ma Saraswati

15. }
16. System.out.println("Found " + numPs + " p's in the string.");
17. }
18. }
Here is the output of this program:
Found 9 p's in the string.

To see this effect more clearly, try removing the continue statement and recompiling. When you run the
program again, the count will be wrong, saying that it found 35 p's instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The
following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within
another string. Two nested loops are required: one to iterate over the substring and one to iterate over
the string being searched. The following program,ContinueWithLabelDemo, uses the labeled form of
continue to skip an iteration in the outer loop.
view plainprint?
1. class ContinueWithLabelDemo {
2. public static void main(String[] args) {
3.
4. String searchMe = "Look for a substring in me";
5. String substring = "sub";
6. boolean foundIt = false;
7.
8. int max = searchMe.length() -
9. substring.length();
10.
11. test:
12. for (int i = 0; i <= max; i++) {
13. int n = substring.length();
14. int j = i;
15. int k = 0;
16. while (n-- != 0) {
17. if (searchMe.charAt(j++) != substring.charAt(k++)) {
18. continue test;
19. }
20. }
21. foundIt = true;
22. break test;
23. }
24. System.out.println(foundIt ? "Found it" : "Didn't find it");
25. }
26. }
Here is the output from this program.
Found it

Jai Ma Saraswati

The return Statement:

The last of the branching statements is the return statement. The return statement exits from the current
method, and control flow returns to where the method was invoked. The return statement has two forms:
one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression
that calculates the value) after the return keyword.

return ++count;

The data type of the returned value must match the type of the method's declared return value. When a
method is declared void, use the form of return that doesn't return a value.

return;

Summary of Control Flow Statements:


The if-then statement is the most basic of all the control flow statements. It tells your program to execute
a certain section of code only if a particular test evaluates to true. The if-then-else statement provides a
secondary path of execution when an "if" clause evaluates to false. Unlike if-then and if-then-else, the
switch statement allows for any number of possible execution paths. The while and do-while statements
continually execute a block of statements while a particular condition is true. The difference between do-
while and while is that do-while evaluates its expression at the bottom of the loop instead of the top.
Therefore, the statements within the do block are always executed at least once. The for statement
provides a compact way to iterate over a range of values. It has two forms, one of which was designed
for looping through collections and arrays.

Useful Programs:
1) Program of factorial number.
class Operation{

static int fact(int number){


int f=1;
for(int i=1;i<=number;i++){
f=f*i;
}
return f;
}

public static void main(String args[]){ int


result=fact(5); System.out.println("Factorial
of 5="+result);

Jai Ma Saraswati

}
}

2) Program of fibonacci series.


class Fabnoci{
public static void main(String...args){
int n=10,i,f0=1,f1=1,f2=0;
for(i=1;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
f2=f0;
System.out.println(f2);
}}
}

3) Program of armstrong number.


class ArmStrong{
public static void main(String...args)
{
int n=153,c=0,a,d;
d=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(d==c)
System.out.println("armstrong number");
else
System.out.println("it is not an armstrong number");
}
}

4) Program of checking palindrome number.


class Palindrome{
public static void main( String...args)
{
int a=242;
int n=a,b=a,rev=0;
while(n>0)

Jai Ma Saraswati

{
a=n%10;
rev=rev*10+a;
n=n/10;
}
if(rev==b)
System.out.println("it is Palindrome");
else
System.out.println("it is not palinedrome");
}
}

5) Program of swapping two numbers without using third variable.


class SwapTwoNumbers{
public static void main(String args[]){
int a=40,b=5;
a=a*b;
b=a/b;
a=a/b;
System.out.println("a= "+a);
System.out.println("b= "+b);
}
}

6) Program of factorial number by recursion


class FactRecursion{
static int fact(int n){
if(n==1)
return 1;
return n*=fact(n-1);
}
public static void main(String args[]){
int f=fact(5);
System.out.println(f);
}
}

Jai Ma Saraswati

Java OOPs Concepts

Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data
binding,polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming paradigm
where everything is represented as an object, is known as truly object-oriented programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)

Object means a real word entity such as pen,


chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies the software development and maintenance by providing some
concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical.

Class
Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

Jai Ma Saraswati

When one task is performed by different ways i.e. known as polymorphism. For example: to convense
the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.


Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call,
we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.

Advantage of OOPs over Procedure-oriented programming language


1)OOPs makes development and maintenance easier where as in Procedure-oriented programming
language it is not easy to manage if code grows as project size grows.
2)OOPs provides data hiding whereas in Procedure-oriented prgramming language a global data can be
accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide the solution
of real word problem if we are using the Object-Oriented Programming language.

Jai Ma Saraswati

What is difference between object-oriented programming language and object-based


programming language?
Object based programming language follows all the features of OOPs except Inheritance. JavaScript and
VBScript are examples of object based programming languages.

Java Naming conventions


A naming convention is a rule to follow as you decide what to name your identifiers e.g. class, package,
variable, constant, method etc.
But, it is not forced to follow. So, it is known as convention not rule.
Advantage of naming conventions in java
By using standard Java naming conventions, you make your code easier to read for yourself and for
other programmers. Readability of Java program is very important. It indicates that less time is spent to
figure out what the code does.

Name Convention

class name should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.

interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote,
ActionListener etc.

method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
print(), println() etc.

variable name should start with lowercase letter e.g. firstName, orderNumber etc.

package name should be in lowercase letter e.g. java, lang, sql, util etc.

Jai Ma Saraswati

constants should be in uppercase letter. e.g. RED, YELLOW,


name MAX_PRIORITY etc.
Understanding CamelCase in java naming conventions
Java follows camelcase syntax for naming the class, interface, method and variable.
If name is combined with two words, second word will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent, ActionListener etc.

Object and Class in Java


In object-oriented programming technique, we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It
can be physical or logical (tengible and intengible). The example of integible object is banking system.
An object has three characteristics:
 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible
to the external user. But,it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to
write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So
object is the instance(result) of a class.

Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects
are created.
A class in java can contain:
 data member
 method
 constructor

Jai Ma Saraswati

 block
 class and interface
Syntax to declare a class:
1. class <class_name>{
2. data member;
3. method;
4. }
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We are
creating the object of the Student class by new keyword and printing the objects value.
1. class Student{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6. Student s1=new Student();//creating an object of Student
7. System.out.println(s1.id+" "+s1.name);
8.
9. }
10. }
Output:0 null

Instance variable in Java


A variable that is created inside the class but outside the method, is known as instance variable.Instance
variable doesn't get memory at compile time.It gets memory at runtime when object(instance) is
created.That is why, it is known as instance variable.
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
 Code Reusability
 Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.

Example of Object and class that maintains the records of students


In this example, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method on it. Here, we are displaying the state (data) of the objects
by invoking the displayInformation method.
1. class Student{
2. int rollno;
3. String name;

Jai Ma Saraswati

4.
5. void insertRecord(int r, String n){ //method
6. rollno=r;
7. name=n;
8. }
9.
10. void displayInformation(){System.out.println(rollno+" "+name);}//method
11.
12. public static void main(String args[]){
13. Student s1=new Student();
14. Student s2=new Student();
15.
16. s1.insertRecord(111,"Karan");
17. s2.insertRecord(222,"Aryan");
18.
19. s1.displayInformation();
20. s2.displayInformation();
21.
22. }
23. }
Output:111 Karan
222 Aryan

As you see in the above figure, object gets the memory in Heap area and reference variable refers to the
object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer to the
objects allocated in memory.

Another Example of Object and Class


There is given another example that maintains the records of Rectangle class. Its exaplanation is same
as in the above Student class example.
1. class Rectangle{

Jai Ma Saraswati

2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle();
14. Rectangle r2=new Rectangle();
15.
16. r1.insert(11,5);
17. r2.insert(3,15);
18.
19. r1.calculateArea();
20. r2.calculateArea();
21. }
22. }
Output:55
45

What are the different ways to create an object in Java?


There are many ways to create an object in java. They are:
 By new keyword
 By newInstance() method
 By clone() method
 By factory method etc.

1. Using `new` keyword:

This is the most common way to create an object in Java. Almost 99% of objects are created in this way.

MyObject object = new MyObject();//normal way

2. By Using Factory Method:


ClassName ObgRef=ClassName.FactoryMethod();

Example:

RunTime rt=Runtime.getRunTime();//Static Factory Method


3. By Using Cloning Concept:

Jai Ma Saraswati

By using clone(), the clone() can be used to create a copy of an existing object.

MyObjectName anotherObject = new MyObjectName();


MyObjectName1 object = anotherObjectName.clone();//cloning Object
4. Using `Class.forName()`:-(newInstance() method)

If we know the name of the class & if it has a public default constructor we can create an object in this
way.

MyObjectName object = (MyObjectNmae) Class.forName("PackageName.ClassName").newInstance();

Example:

String st=(String)Class.forName("java.lang.String").newInstance();
5. Using object deserialization:

Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStreamName inStream = new ObjectInputStreamName(anInputStream );


MyObjectName object = (MyObjectNmae) inStream.readObject();

Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous object.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4. int fact=1;
5. for(int i=1;i<=n;i++){
6. fact=fact*i;
7. }
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120

Jai Ma Saraswati

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.
1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
Let's see the example:
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
14.
15. r1.insert(11,5);
16. r2.insert(3,15);
17.
18. r1.calculateArea();
19. r2.calculateArea();
20. }
21. }
Output:55
45

Method Overloading in Java


If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of
the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments,
if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to understand the behaviour of the method
because its name differs. So, we perform method overloading to figure out the program quickly.

Advantage of method overloading?


Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments

Jai Ma Saraswati

2. By changing the data type


In java, Methood Overloading is not possible by changing the return type of the method.

1)Example of Method Overloading by changing the no. of arguments


In this example, we have created two overloaded methods, first sum method performs addition of two
numbers and second sum method performs addition of three numbers.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
11. }
Output:30
40

2)Example of Method Overloading by changing data type of argument


In this example, we have created two overloaded methods that differs in data type. The first sum method
receives two integer arguments and second sum method receives two double arguments.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10.5,10.5);
8. obj.sum(20,20);
9.
10. }
11. }
Output:21.0
40

Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may
occur ambiguity. Let's see how ambiguity may occur:
because there was problem:
1. class Calculation{
2. int sum(int a,int b){System.out.println(a+b);}

Jai Ma Saraswati

3. double sum(int a,int b){System.out.println(a+b);}


4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10. }
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called

Can we overload main() method?


Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:
1. class Simple{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
10. }
Output:main() method invoked
10

Method Overloading and TypePromotion


One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept
by the figure given below:

Jai Ma Saraswati

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short
datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float
or double and so on.
Example of Method Overloading with TypePromotion
1. class Calculation{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9.
10. }
11. }
Output:40
60

Example of Method Overloading with TypePromotion if matching found


If there are matching type arguments in the method, type promotion is not performed.
1. class Calculation{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
Output:int arg method invoked

Example of Method Overloading with TypePromotion in case ambiguity


If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.
1. class Calculation{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Output:Compile Time Error

Jai Ma Saraswati

One type is not de-promoted implicitly for example double cannot be depromoted to any type
implicitely.

Constructor in Java

Constructor is a special type of method that is used to initialize the object.


Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the
object that is why it is known as constructor.
Rules for creating constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

Types of constructors
There are two types of constructors:
1. default constructor (no-arg constructor)
2. parameterized constructor

Jai Ma Saraswati

1) Default Constructor
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
1. <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
1. class Bike{
2.
3. Bike(){System.out.println("Bike is created");}
4.
5. public static void main(String args[]){
6. Bike b=new Bike();
7. }
8. }
Output: Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Que)What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc. depending on the type.
Example of default constructor that displays the default values
1. class Student{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student s1=new Student();
9. Student s2=new Student();
10. s1.display();
11. s2.display();
12. }
13. }

Jai Ma Saraswati

Output:0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor.Here 0 and null values are provided by default constructor.

Parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.
1. class Student{
2. int id;
3. String name;
4.
5. Student(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");
13. Student s2 = new Student(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Output:111 Karan
222 Aryan

Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists.The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
Example of Constructor Overloading
1. class Student{
2. int id;
3. String name;
4. int age;
5. Student(int i,String n){

Jai Ma Saraswati

6. id = i;
7. name = n;
8. }
9. Student(int i,String n,int a){
10. id = i;
11. name = n;
12. age=a;
13. }
14. void display(){System.out.println(id+" "+name+" "+age);}
15.
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan",25);
19. s1.display();
20. s2.display();
21. }
22. }
Output:111 Karan 0
222 Aryan 25

What is the difference between constructor and method ?


There are many differences between constructors and methods. They are given below.
Constructor Method
Constructor is used to initialize the state of an object. Method is used to expose behaviour of
an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.

Constructor name must be same as the class name. Method name may or may not be same
as class name.

Copying the values of one object to another like copy constructor in C++
There are many ways to copy the values of one object into another. They are:
 By constructor
 By assigning the values of one object into another
 By clone() method of Object class
In this example, we are going to copy the values of one object into another using constructor.

Jai Ma Saraswati

1. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
8.
9. Student(Student s){
10. id = s.id;
11. name =s.name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student s1 = new Student(111,"Karan");
17. Student s2 = new Student(s1);
18. s1.display();
19. s2.display();
20. }
21. }
Output:111 Karan
111 Karan

Copying the values of one object to another without constructor


We can copy the values of one object into another by assigning the objects values to another object. In
this case, there is no need to create the constructor.
1. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");
13. Student s2 = new Student();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }

Jai Ma Saraswati

19. }
Output:111 Karan
111 Karan

Que)Does constructor return any value?


Ans:yes,that is current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?


Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the
constructor as you perform in the method.

static keyword

The static keyword is used in java mainly for memory management. We may apply static keyword with
variables, methods, blocks and nested class. The static keyword belongs to the class than instance of
the class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class

1) static variable
If you declare any variable as static, it is known static variable.
 The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees,college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Jai Ma Saraswati

Suppose there are 500 students in my college, now all instance data members will get memory each
time when object is created.All student have its unique rollno and name so instance data member is
good.Here, college refers to the common property of all objects.If we make it static,this field will get
memory only once.
static property is shared to all objects.
Example of static variable
1. //Program of static variable
2.
3. class Student{
4. int rollno;
5. String name;
6. static String college ="ITS";
7.
8. Student(int r,String n){
9. rollno = r;
10. name = n;
11. }
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13.
14. public static void main(String args[]){
15. Student s1 = new Student (111,"Karan");
16. Student s2 = new Student (222,"Aryan");
17.
18. s1.display();
19. s2.display();
20. }
21. }
Output:111 Karan ITS
222 Aryan ITS

Jai Ma Saraswati

Program of counter without static variable


In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object will have
the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will
have the value 1 in the count variable.
1. class Counter{
2. int count=0;//will get memory when instance is created
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter c1=new Counter();
12. Counter c2=new Counter();
13. Counter c3=new Counter();
14.
15. }}
Output:1
1
1

Jai Ma Saraswati

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any object changes the
value of the static variable, it will retain its value.
1. class Counter{
2. static int count=0;//will get memory only once and retain its value
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter c1=new Counter();
12. Counter c2=new Counter();
13. Counter c3=new Counter();
14.
15. }}
Output:1
2
3

2) static method
If you apply static keyword with any method, it is known as static method
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 static method can access static data member and can change the value of it.
Example of static method
1. //Program of changing the common property of all objects(static field).
2.
3. class Student{
4. int rollno;
5. String name;
6. static String college = "ITS";
7.
8. static void change(){
9. college = "BBDIT";
10. }
11.
12. Student(int r, String n){
13. rollno = r;
14. name = n;
15. }
16.
17. void display (){System.out.println(rollno+" "+name+" "+college);}

Jai Ma Saraswati

18.
19. public static void main(String args[]){
20. Student.change();
21.
22. Student s1 = new Student (111,"Karan");
23. Student s2 = new Student (222,"Aryan");
24. Student s3 = new Student (333,"Ank");
25.
26. s1.display();
27. s2.display();
28. s3.display();
29. }
30. }
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Ank BBDIT

Another example of static method that performs normal calculation


1. //Program to get cube of a given number by static method
2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }
Output:125
Restrictions for static method
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Output:Compile Time Error

Jai Ma Saraswati

Que)why main method is static?


Ans) because object is not required to call static method if it were non-static method, jvm create object
first then call main() method that will lead the problem of extra memory allocation.

3)static block
 Is used to initialize the static data member.
 It is executed at the time of classloading.
Example of static block
1. class A{
2.
3. static{System.out.println("static block is invoked");}
4.
5. public static void main(String args[]){
6. System.out.println("Hello main");
7. }
8. }
Output:static block is invoked
Hello main

Que)Can we execute a program without main() method?


Ans)Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
1. class A{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Output:static block is invoked (if not JDK7)

this keyword
There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the
current object.
Usage of this keyword
Here is given the 6 usage of this keyword.

Jai Ma Saraswati

1. this keyword can be used to refer current class instance variable.


2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)

1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of
ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
1. class student{
2. int id;
3. String name;
4.
5. student(int id,String name){
6. id = id;
7. name = name;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. student s1 = new student(111,"Karan");
13. student s2 = new student(321,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is why we are
using this keyword to distinguish between local variable and instance variable.

Jai Ma Saraswati

Solution of the above problem by this keyword


1. //example of this keyword
2. class Student{
3. int id;
4. String name;
5.
6. student(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. void display(){System.out.println(id+" "+name);}
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");
13. Student s2 = new Student(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Output111 Karan
222 Aryan

If local variables(formal arguments) and instance variables are different, there is no need to use this
keyword like in the following program:
Program where this keyword is not required
1. class Student{

Jai Ma Saraswati

2. int id;
3. String name;
4.
5. student(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10. public static void main(String args[]){
11. Student e1 = new Student(111,"karan");
12. Student e2 = new Student(222,"Aryan");
13. e1.display();
14. e2.display();
15. }
16. }
Output:111 Karan
222 Aryan

2) this() can be used to invoked current class constructor.


The this() constructor call can be used to invoke the current class constructor (constructor chaining). This
approach is better if you have many constructors in the class and want to reuse that constructor.
1. //Program of this() constructor call (constructor chaining)
2.
3. class Student{
4. int id;
5. String name;
6. Student (){System.out.println("default constructor is invoked");}
7.
8. Student(int id,String name){
9. this ();//it is used to invoked current class constructor.
10. this.id = id;
11. this.name = name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student e1 = new Student(111,"karan");
17. Student e2 = new Student(222,"Aryan");
18. e1.display();
19. e2.display();
20. }
21. }
Output:
default constructor is invoked
default constructor is invoked
111 Karan

Jai Ma Saraswati

222 Aryan
Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor. It maintains the
chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below
that displays the actual use of this keyword.
1. class Student{
2. int id;
3. String name;
4. String city;
5.
6. Student(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. Student(int id,String name,String city){
11. this(id,name);//now no need to initialize id and name
12. this.city=city;
13. }
14. void display(){System.out.println(id+" "+name+" "+city);}
15.
16. public static void main(String args[]){
17. Student e1 = new Student(111,"karan");
18. Student e2 = new Student(222,"Aryan","delhi");
19. e1.display();
20. e2.display();
21. }
22. }
Output:111 Karan null
222 Aryan delhi
Rule: Call to this() must be the first statement in constructor.
1. class Student{
2. int id;
3. String name;
4. Student (){System.out.println("default constructor is invoked");}
5.
6. Student(int id,String name){
7. id = id;
8. name = name;
9. this ();//must be the first statement
10. }
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. Student e1 = new Student(111,"karan");
15. Student e2 = new Student(222,"Aryan");

Jai Ma Saraswati

16. e1.display();
17. e2.display();
18. }
19. }
Output:Compile Time Error

3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the this
keyword, compiler automatically adds this keyword while invoking the method. Let's see the example

1. class S{
2. void m(){
3. System.out.println("method is invoked");
4. }
5. void n(){
6. this.m();//no need because compiler does it for you.
7. }
8. void p(){
9. n();//complier will add this to invoke n() method as this.n()
10. }
11. public static void main(String args[]){
12. S s1 = new S();
13. s1.p();
14. }
15. }
Output:method is invoked

Jai Ma Saraswati

Inheritance in Java

Inheritance is a mechanism in which one object acquires all the properties and behaviours of parent
object.
The idea behind inheritance is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you reuse (or inherit) methods and fields, and you add new
methods and fields to adapt your new class to new situations.
Inheritance represents the IS-A relationship.
Why use Inheritance?
 For Method Overriding (So Runtime Polymorphism).
 For Code Reusability.
Syntax of Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The keyword extends indicates that you are making a new class that derives from an existing class. In
the terminology of Java, a class that is inherited is called a superclass. The new class is called a
subclass.

Understanding the simple example of inheritance



Jai Ma Saraswati

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type
of Employee.
1. class Employee{
2. float salary=40000;
3. }
4.
5. class Programmer extends Employee{
6. int bonus=10000;
7.
8. public static void main(String args[]){
9. Programmer p=new Programmer();
10. System.out.println("Programmer salary is:"+p.salary);
11. System.out.println("Bonus of Programmer is:"+p.bonus);
12. }
13. }
Output:Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example,Programmer object can access the field of own class as well as of Employee class
i.e. code reusability.
Types of Inheritance
On the basis of class, there can be three types of inheritance: single, multilevel and hierarchical.
Multiple and Hybrid is supported through interface only. We will learn about interfaces later.

Multiple inheritance is not supported in java in case of class.



Jai Ma Saraswati

When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Que) Why multiple inheritance is not supported in java?


 To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
For example:
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4.
5. class B{
6. void msg(){System.out.println("Welcome");}
7. }
8.
9. class C extends A,B{//suppose if it were
10.
11. Public Static void main(String args[]){
12. C obj=new C();
13. obj.msg();//Now which msg() method would be invoked?
14. }
15. }

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship.

Jai Ma Saraswati

Consider a situation, Employee object contains many informations such as id, name, emailId etc. It
contains one more object named address, which contains its own informations such as city, state,
country, zipcode etc. as given below.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.
Why use Aggregation?
 For Code Reusability.

Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.
1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);

Jai Ma Saraswati

22. System.out.println(result);
23. }
24. }
Output:78.5

When use Aggregation?


 Code reuse is also best achieved by aggregation when there is no is-a relationship.
 Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the
objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation


In this example, Employee has an object of Address, address object contains its own informations such
as city, state, country etc. In such case relationship is Employee HAS-A address.
Address.java
1. public class Address {
2. String city,state,country;
3.
4. public Address(String city, String state, String country) {
5. this.city = city;
6. this.state = state;
7. this.country = country;
8. }
9.
10. }
Emp.java
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. this.id = id;
8. this.name = name;
9. this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);

Jai Ma Saraswati

22. Emp e2=new Emp(112,"arun",address2);


23.
24. e.display();
25. e2.display();
26.
27. }
28. }
Output:111 varun
gzb UP india
112 arun
gno UP india

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding.
In other words, If subclass provides the specific implementation of the method that has been provided by
one of its parent class, it is known as Method Overriding.
Advantage of Java Method Overriding
 Method Overriding is used to provide specific implementation of a method that is already provided
by its super class.
 Method Overriding is used for Runtime Polymorphism

Rules for Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Understanding the problem without method overriding


Let's understand the problem that we may face in the program if we don't use method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Output:Vehicle is running

Jai Ma Saraswati

Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method is same and there is IS-A
relationship between the classes, so there is method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike obj = new Bike();
9. obj.run();
10. }
Output:Bike is running safely

Real example of Java Method Overriding


Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest
varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate
of interest.

1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }

Jai Ma Saraswati

8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test{
17. public static void main(String args[]){
18. SBI s=new SBI();
19. ICICI i=new ICICI();
20. AXIS a=new AXIS();
21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
24. }
25. }
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?


No, static method cannot be overridden. It can be proved by runtime polymorphism so we will learn it
later.
Why we cannot override static method?
because static method is bound with class whereas instance method is bound with object. Static belongs
to class area and instance belongs to heap area.

Can we override java main method?


No, because main is a static method.

What is the difference between method Overloading and Method Overriding?


There are three basic differences between the method overloading and method overriding. They are as
follows:
Method Overloading Method Overriding
1) Method overloading is used to Method overriding is used to provide the specific
increase the readability of the implementation of the method that is already provided by its
program. super class.

2) method overloading is performed Method overriding occurs in two classes that have IS-A

Jai Ma Saraswati

within a class. relationship.

3) In case of method overloading In case of method overriding parameter must be same.


parameter must be different.

Covariant Return Type


The covariant return type specifies that the return type may vary in the same direction as the subclass.
Before Java5, it was not possible to override any method by changing the return type. But now, since
Java5, it is possible to override method by changing the return type if subclass overrides any method
whose return type is Non-Primitive but it changes its return type to subclass type. Let's take a simple
example:
Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.

Simple example of Covariant Return Type


1. class A{
2. A get(){return this;}
3. }
4.
5. class B extends A{
6. B get(){return this;}
7. void message(){System.out.println("welcome to covariant return type");}
8.
9. public static void main(String args[]){
10. new B().get().message();
11. }
12. }
Output:welcome to covariant return type
As you can see in the above example, the return type of the get() method of A class is A but the return
type of the get() method of B class is B. Both methods have different return type but it is method
overriding. This is known as covariant return type.
super keyword
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable.
Usage of super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.
1) super is used to refer immediate parent class instance variable.
Problem without super keyword
1. class Vehicle{
2. int speed=50;

Jai Ma Saraswati

3. }
4.
5. class Bike extends Vehicle{
6. int speed=100;
7.
8. void display(){
9. System.out.println(speed);//will print speed of Bike
10. }
11. public static void main(String args[]){
12. Bike b=new Bike();
13. b.display();
14.
15. }
16. }
Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance variable of
current class is refered by instance bydefault, but I have to refer parent class instance variable that‟s why
we use super keyword to distinguish between parent class instance variable and current class instance
variable.

Solution by super keyword


1. //example of super keyword
2.
3. class Vehicle{
4. int speed=50;
5. }
6.
7. class Bike extends Vehicle{
8. int speed=100;
9.
10. void display(){
11. System.out.println(super.speed);//will print speed of Vehicle now
12. }
13. public static void main(String args[]){
14. Bike b=new Bike();
15. b.display();
16.
17. }
18. }
Output:50
2) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor as given below:
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}

Jai Ma Saraswati

3. }
4.
5. class Bike extends Vehicle{
6. Bike(){
7. super();//will invoke parent class constructor
8. System.out.println("Bike is created");
9. }
10. public static void main(String args[]){
11. Bike b=new Bike();
12.
13. }
14. }
Output:Vehicle is created
Bike is created
super() is added in each class constructor automatically by compiler.

As we know well that default constructor is provided by compiler automatically but it also adds super() for
the first statement.If you are creating your own constructor and you don't have either this() or super() as
the first statement, compiler will provide super() as the first statement of the constructor.
Another example of super keyword where super() is provided by the compiler implicitly.
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike extends Vehicle{

Jai Ma Saraswati

6. int speed;
7. Bike(int speed){
8. this.speed=speed;
9. System.out.println(speed);
10. }
11. public static void main(String args[]){
12. Bike b=new Bike(10);
13. }
14. }
Output:Vehicle is created
10
3) super can be used to invoke parent class method.
The super keyword can also be used to invoke parent class method. It should be used in case subclass
contains the same method as parent class as in the example given below:
1. class Person{
2. void message(){System.out.println("welcome");}
3. }
4.
5. class Student extends Person{
6. void message(){System.out.println("welcome to java");}
7.
8. void display(){
9. message();//will invoke current class message() method
10. super.message();//will invoke parent class message() method
11. }
12.
13. public static void main(String args[]){
14. Student s=new Student();
15. s.display();
16. }
17. }
Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if we call message()
method from Student class, it will call the message() method of Student class not of Person class
because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In the example given
below message() method is invoked from Student class but Student class does not have message()
method, so you can directly call message() method.
Program in case super is not required
1. class Person{
2. void message(){System.out.println("welcome");}
3. }

Jai Ma Saraswati

4.
5. class Student extends Person{
6.
7. void display(){
8. message();//will invoke parent class message() method
9. }
10.
11. public static void main(String args[]){
12. Student s=new Student();
13. s.display();
14. }
15. }
Output:welcome

Instance initializer block


Instance Initializer block is used to initialize the instance data member. It run each time when object of
the class is created.
The initialization of the instance variable can be directly but there can be performed extra operations
while initializing the instance variable in the instance initializer block.
Que) What is the use of instance initializer block while we can directly assign a value in instance
data member? For example:
1. class Bike{
2. int speed=100;
3. }
Why use instance initializer block?
Suppose I have to perform some operations while assigning value to instance data member e.g. a for
loop to fill a complex array or error handling etc.

Example of instance initializer block


Let's see the simple example of instance initializer block the performs initialization.
1. class Bike{
2. int speed;
3.
4. Bike(){System.out.println("speed is "+speed);}
5.
6. {speed=100;}
7.
8. public static void main(String args[]){

Jai Ma Saraswati

9. Bike b1=new Bike();


10. Bike b2=new Bike();
11. }
12. }
Output:speed is 100
speed is 100

There are three places in java where you can perform operations:
1. method
2. constructor
3. block

What is invoked firstly instance initializer block or constructor?


1. class Bike{
2. int speed;
3.
4. Bike(){System.out.println("constructor is invoked");}
5.
6. {System.out.println("instance initializer block invoked");}
7.
8. public static void main(String args[]){
9. Bike b1=new Bike();
10. Bike b2=new Bike();
11. }
12. }
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer
block is invoked at the time of object creation. The java compiler copies the instance initializer block in
the constructor after the first statement super(). So firstly, constructor is invoked. Let's understand it by
the figure given below:
Note: The java compiler copies the code of instance initializer block in every constructor.

Jai Ma Saraswati

Rules for instance initializer block :


There are mainly three rules for the instance initializer block. They are as follows:
1. The instance initializer block is created when instance of the class is created.
2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after
super() constructor call).
3. The instance initializer block comes in the order in which they appear.
Program of instance initializer block that is invoked after super()
1. class A{
2. A(){
3. System.out.println("parent class constructor invoked");
4. }
5. }
6. class B extends A{
7. B(){
8. super();
9. System.out.println("child class constructor invoked");

Jai Ma Saraswati

10. }
11.
12. {System.out.println("instance initializer block is invoked");}
13.
14. public static void main(String args[]){
15. B b=new B();
16. }
17. }
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked

Another example of instance block


1. class A{
2. A(){
3. System.out.println("parent class constructor invoked");
4. }
5. }
6.
7. class B extends A{
8. B(){
9. super();
10. System.out.println("child class constructor invoked");
11. }
12.
13. B(int a){
14. super();
15. System.out.println("child class constructor invoked "+a);
16. }
17.
18. {System.out.println("instance initializer block is invoked");}
19.
20. public static void main(String args[]){
21. B b1=new B();
22. B b2=new B(10);
23. }
24. }
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10

Jai Ma Saraswati

Final Keyword In Java

The final keyword in java is used to restrict the user. The final keyword can be used in many context.
Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only. We will have detailed learning
of these. Let's first learn the basics of final keyword.

1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
1. class Bike{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike obj=new Bike();
8. obj.run();
9. }
10. }//end of class
Output:Compile Time Error

Jai Ma Saraswati

2) final method
If you make any method as final, you cannot override it.
Example of final method
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Output:Compile Time Error

3) final class
If you make any class as final, you cannot extend it.
Example of final class
1. final class Bike{}
2.
3. class Honda extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda honda= new Honda();
8. honda.run();
9. }
10. }
Output:Compile Time Error

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda extends Bike{
5. public static void main(String args[]){
6. new Honda().run();
7. }
8. }
Output:running...

Jai Ma Saraswati

Q) What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may not
be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
Example of blank final variable
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
Que) Can we initialize blank final variable?
Yes, but only in constructor. For example:
1. class Bike{
2. final int speedlimit;//blank final variable
3.
4. Bike(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike();
11. }
12. }
Output:70

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank final variable.
It can be initialized only in static block.
Example of static blank final variable
1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }

Q) What is final parameter?


If you declare any parameter as final, you cannot change the value of it.
1. class Bike{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final

Jai Ma Saraswati

4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike b=new Bike();
8. b.cube(5);
9. }
10. }
Output:Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:

1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting

Example of Runtime Polymorphism


In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and
overrides its run() method. We are calling the run method by the reference variable of Parent class.
Since it refers to the subclass object and subclass method overrides the Parent class method, subclass
method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

Jai Ma Saraswati

1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splender extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splender();//upcasting
9. b.run();
10. }
11. }
Output:running safely with 60km.

Real example of Java Runtime Polymorphism


Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest
may differ according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9%
rate of interest.

Note: It is also given in method overriding but there was no upcasting.


1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{

Jai Ma Saraswati

13. int getRateOfInterest(){return 9;}


14. }
15.
16. class Test{
17. public static void main(String args[]){
18. Bank b1=new SBI();
19. Bank b2=new ICICI();
20. Bank b3=new AXIS();
21. System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
24. }
25. }
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Runtime Polymorphism with data member


Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data
members.
In the example given below, both the classes have a datamember speedlimit, we are accessing the
datamember by the reference variable of Parent class which refers to the subclass object. Since we are
accessing the datamember which is not overridden, hence it will access the datamember of Parent class
always.
Rule: Runtime polymorphism can't be achieved by data members.
1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda extends Bike{
5. int speedlimit=150;
6.
7. public static void main(String args[]){
8. Bike obj=new Honda();
9. System.out.println(obj.speedlimit);//90
10. }
Output:90
Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4.

Jai Ma Saraswati

5. class Dog extends Animal{


6. void eat(){System.out.println("eating fruits");}
7. }
8.
9. class BabyDog extends Dog{
10. void eat(){System.out.println("drinking milk");}
11.
12. public static void main(String args[]){
13. Animal a1,a2,a3;
14. a1=new Animal();
15. a2=new Dog();
16. a3=new BabyDog();
17.
18. a1.eat();
19. a2.eat();
20. a3.eat();
21. }
22. }
Output: eating
eating fruits
drinking Milk

Try for Output


1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7. }
8.
9. class BabyDog extends Dog{
10. public static void main(String args[]){
11. Animal a=new BabyDog();
12. a.eat();
13. }}
Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.

Static Binding and Dynamic Binding



Jai Ma Saraswati

Connecting a method call to the method body is known as binding.


There are two types of binding
1. static binding (also known as early binding).
2. dynamic binding (also known as late binding).
Understanding Type
Let's understand the type of instance.
1) variables have a type
Each variable has a type, it may be primitive and non-primitive.
1. int data=30;
Here data variable is a type of int.
2) References have a type
1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }
3) Objects have a type
An object is an instance of particular java class,but it is also an instance of its superclass.
1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Example of static binding
1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
1. class Animal{

Jai Ma Saraswati

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


3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is
also an instance of Animal.So compiler doesn't know its type, only its base type.
instanceof operator

The instanceof operator is used to test whether the object is an instance of the specified type (class or
subclass or interface).
The instanceof operator is also known as type comparison operator because it compares the instance
with type. It returns either true or false. If we apply the instanceof operator with any variable that have
null value, it returns false.
Simple example of instanceof operator
Let's see the simple example of instance operator where it tests the current class.
1. class Simple{
2. public static void main(String args[]){
3. Simple s=new Simple();
4. System.out.println(s instanceof Simple);//true
5. }
6. }
Output:true

An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object
of Dog can be referred by either Dog or Animal class.
Another example of instanceof operator
1. class Animal{}
2. class Dog extends Animal{//Dog inherits Animal
3.
4. public static void main(String args[]){
5. Dog d=new Dog();
6. System.out.println(d instanceof Animal);//true
7. }

Jai Ma Saraswati

8. }
Output:true

instanceof operator with a variable that have null value


If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example
given below where we apply instanceof operator with the variable that have null value.
1. class Dog{
2. public static void main(String args[]){
3. Dog d=null;
4. System.out.println(d instanceof Dog);//false
5. }
6. }
Output:false

Downcasting with instanceof operator


When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it
directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown
at runtime. But if we use instanceof operator, downcasting is possible.
1. Dog d=new Animal();//Compilation error
If we perform downcasting by typecasting, ClassCastException is thrown at runtime.
1. Dog d=(Dog)new Animal();
2. //Compiles successfully but ClassCastException is thrown at runtime
Possibility of downcasting with instanceof operator
Let's see the example, where downcasting is possible by instanceof operator.
1. class Animal { }
2.
3. class Dog extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog){
6. Dog d=(Dog)a;//downcasting
7. System.out.println("ok downcasting performed");
8. }
9. }
10.
11. public static void main (String [] args) {
12. Animal a=new Dog();
13. Dog.method(a);
14. }
15.
16. }
Output:ok downcasting performed

Downcasting without the use of instanceof operator


Downcasting can also be performed without the use of instanceof operator as displayed in the following
example:

Jai Ma Saraswati

1. class Animal { }
2. class Dog extends Animal {
3. static void method(Animal a) {
4. Dog d=(Dog)a;//downcasting
5. System.out.println("ok downcasting performed");
6. }
7. public static void main (String [] args) {
8. Animal a=new Dog();
9. Dog.method(a);
10. }
11. }
Output:ok downcasting performed
Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we
downcast it, it is fine. But what will happen if we write:
1. Animal a=new Animal();
2. Dog.method(a);
3. //Now ClassCastException but not in case of instanceof operator
Understanding Real use of instanceof operator
Let's see the real use of instanceof keyword by the example given below.
1. interface Printable{}
2. class A implements Printable{
3. public void a(){System.out.println("a method");}
4. }
5. class B implements Printable{
6. public void b(){System.out.println("b method");}
7. }
8.
9. class Call{
10. void invoke(Printable p){//upcasting
11. if(p instanceof A){
12. A a=(A)p;//Downcasting
13. a.a();
14. }
15. if(p instanceof B){
16. B b=(B)p;//Downcasting
17. b.b();
18. }
19.
20. }
21. }//end of Call class
22.
23. class Test{
24. public static void main(String args[]){
25. Printable p=new B();
26. Call c=new Call();
27. c.invoke(p);

Jai Ma Saraswati

28. }
29. }
Output: b method

Abstract class in Java


A class that is declared with abstract keyword, is known as abstract class. Before learning abstract class,
let's understand the abstraction first.
Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example
sending sms, you just type the text and send the message. You don't know the internal processing about
the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended and its method
implemented. It cannot be instantiated.
Syntax to declare the abstract class
1. abstract class <class_name>{}
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
Syntax to define the abstract method
1. abstract return_type <method_name>();//no braces{}
Example of abstract class that have abstract method
In this example, Bike the abstract class that contains only one abstract method run. It implementation is
provided by the Honda class.
1. abstract class Bike{
2. abstract void run();
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely..");}
7.
8. public static void main(String args[]){
9. Bike obj = new Honda();
10. obj.run();
11. }
12. }
Output:running safely..

Jai Ma Saraswati

Understanding the real scenario of abstract class


In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle
classes. Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of
the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about the factory
method later.
In this example, if you create the instance of Rectangle class, draw method of Rectangle class will be
invoked.
1. abstract class Shape{
2. abstract void draw();
3. }
4.
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class Circle extends Shape{
10. void draw(){System.out.println("drawing circle");}
11. }
12.
13. class Test{
14. public static void main(String args[]){
15. Shape s=new Circle();
16. //In real scenario, Object is provided through factory method
17. s.draw();
18. }
19. }
Output:drawing circle

Abstract class having constructor, data member, methods etc.


Note: An abstract class can have data member, abstract method, method body, constructor and
even main() method.
1. //example of abstract class that have method body
2. abstract class Bike{
3. abstract void run();
4. void changeGear(){System.out.println("gear changed");}
5. }
6.
7. class Honda extends Bike{
8. void run(){System.out.println("running safely..");}
9.
10. public static void main(String args[]){
11. Bike obj = new Honda();
12. obj.run();

Jai Ma Saraswati

13. obj.changeGear();
14. }
15. }
Output:running safely..
gear changed
1. //example of abstract class having constructor, field and method
2. abstract class Bike
3. {
4. int limit=30;
5. Bike(){System.out.println("constructor is invoked");}
6. void getDetails(){System.out.println("it has two wheels");}
7. abstract void run();
8. }
9.
10. class Honda extends Bike{
11. void run(){System.out.println("running safely..");}
12.
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.getDetails();
17. System.out.println(obj.limit);
18. }
19. }
Output:constructor is invoked
running safely..
it has two wheels
30
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike{
2. abstract void run();
3. }
Output:compile time error
Rule: If you are extending any abstact class that have abstract method, you must either provide
the implementation of the method or make this class abstract.
Another real scenario of abstract class
The abstract class can also be used to provide some implementation of the interface. In such case, the
end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();

Jai Ma Saraswati

6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am C");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Output:I am a
I am b
I am c
I am d

Interface in Java
An interface is a blueprint of a class. It has static constants and abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods
in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.
Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Interface?
There are mainly three reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and public,
static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and abstract.

Jai Ma Saraswati

Understanding relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another interface
but a class implements an interface.

Simple example of Interface



Jai Ma Saraswati

In this example, Printable interface have only one method, its implementation is provided in the A class.
1. interface printable{
2. void print();
3. }
4.
5. class A implements printable{
6. public void print(){System.out.println("Hello");}
7.
8. public static void main(String args[]){
9. A obj = new A();
10. obj.print();
11. }
12. }
Output:Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.

1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
7. }
8.
9. class A implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12. public void show(){System.out.println("Welcome");}

Jai Ma Saraswati

13.
14. public static void main(String args[]){
15. A obj = new A();
16. obj.print();
17. obj.show();
18. }
19. }
Output:Hello
Welcome

Q) Multiple inheritance is not supported in case of class but it is supported in case of interface,
why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class.
But it is supported in case of interface because there is no ambiguity as implementation is provided by
the implementation class. For example:
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void print();
7. }
8.
9. class A implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12.
13. public static void main(String args[]){
14. A obj = new A();
15. obj.print();
16. }
17. }
Output:Hello
As you can see in the above example, Printable and Showable interface have same methods but its
implementation is provided by class A, so there is no ambiguity.

Note: A class implements interface but One interface extends another interface .
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable extends Printable{
6. void show();
7. }
8.

Jai Ma Saraswati

9. class A implements Showable{


10.
11. public void print(){System.out.println("Hello");}
12. public void show(){System.out.println("Welcome");}
13.
14. public static void main(String args[]){
15. A obj = new A();
16. obj.print();
17. obj.show();
18. }
19. }
Output:Hello
Welcome

Que) What is marker or tagged interface ?


An interface that have no member is known as marker or tagged interface. For example: Serializable,
Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM
may perform some useful operation.
1. //How Serializable interface is written?
2.
3. public interface Serializable{
4. }

Nested Interface
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in
the nested classes chapter. For example:
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }

Jai Ma Saraswati

Package in Java
A package is a group of similar types of classes, interfaces and sub-packages.
Package can be categorized in two form, built-in package and user-defined package. There are many
built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Package
 Package is used to categorize the classes and interfaces so that they can be easily maintained.
 Package provids access protection.
 Package removes naming collision.

Simple example of package


The package keyword is used to create a package.
1. //save as Simple.java
2.
3. package mypack;
4. public class Simple{
5. public static void main(String args[]){
6. System.out.println("Welcome to package");
7. }
8. }

Jai Ma Saraswati

How to compile the Package (if not using IDE)


If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package
within the same directory, you can use . (dot).

How to run the Package (if not using IDE)


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .
represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
Example of package that import the packagename.*
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();

Jai Ma Saraswati

9. obj.msg();
10. }
11. }
Output:Hello

Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.A;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello

Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now there is
no need to import. But you need to use fully qualified name every time when you are accessing the class
or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example of package by import fully qualified name
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. class B{
5. public static void main(String args[]){
6. pack.A obj = new pack.A();//using fully qualified name

Jai Ma Saraswati

7. obj.msg();
8. }
9. }
Output:Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported excluding the
classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.

Subpackage
Package inside the package is called the subpackage. It should be created to categorize the package
further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g.
Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for
networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang,
net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in
net packages and so on.
The standard of defining package is domain.company.package e.g. com.hftech.bean or
org.sssit.dao.
Example of Subpackage
1. package com.hftech.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java

Jai Ma Saraswati

To Run: java com.hftech.core.Simple


Output:Hello subpackage

Rule: There can be only one public class in a java source file and it must be saved by the public
class name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one public class,
but keep the package name same. For example:
1. //save as A.java
2.
3. package hftech;
4. public class A{}
1. //save as B.java
2.
3. package hftech;
4. public class B{}

Jai Ma Saraswati

Access Modifiers
There are two types of modifiers in java: access modifier and non-access modifier. The access
modifiers specifies accessibility (scope) of a datamember, method, constructor or class.
There are 4 types of access modifiers:
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient
etc. Here, we will learn access modifiers.

1) private
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile
time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
Role of Private Constructor:
If you make any class constructor private, you cannot create the instance of that class from outside the
class. For example:
1. class A{
2. private A(){}//private constructor
3.
4. void msg(){System.out.println("Hello java");}
5. }
6.
7. public class Simple{
8. public static void main(String args[]){
9. A obj=new A();//Compile Time Error
10. }

Jai Ma Saraswati

11. }
Note: A class cannot be private or protected except nested class.

2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only
within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
1. //save by A.java
2.
3. package pack;
4. class A{
5. void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();//Compile Time Error
9. obj.msg();//Compile Time Error
10. }
11. }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.

3) protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.
1. //save by A.java
2.
3. package pack;
4. public class A{

Jai Ma Saraswati

5. protected void msg(){System.out.println("Hello");}


6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B extends A{
7. public static void main(String args[]){
8. B obj = new B();
9. obj.msg();
10. }
11. }
Output:Hello

4) public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
Access within within outside package by subclass outside
Modifier class package only package
Private Y N N N

Jai Ma Saraswati

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Applying access modifier with method overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
The default modifier is more restrictive than protected. That is why there is compile time error.
Encapsulation in Java
Encapsulation is a process of wrapping code and data together into a single unit e.g. capsule i.e mixed
of several medicines.

We can create a fully encapsulated class by making all the data


members of the class private. Now we can use setter and getter methods to set and get the data in it.
Java Bean is the example of fully encapsulated class.
Advantage of Encapsulation
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100
only, you can write the logic inside the setter method.
Simple example of encapsulation in java
Let's see the simple example of encapsulation that has only one field with its setter and getter methods.
1. //save as Student.java
2. package com.hftech;

Jai Ma Saraswati

3. public class Student{


4. private String name;
5.
6. public String getName(){
7. return name;
8. }
9. public void setName(String name){
10. this.name=name
11. }
12. }
1. //save as Test.java
2. package com.hftech;
3. class Test{
4. public static void main(String[] args){
5. Student s=new Student();
6. s.setname("vijay");
7. System.out.println(s.getName());
8. }
9. }
Compile By: javac -d . Test.java
Run By: java com.hftech.Test
Output: vijay

Object class in Java


The Object class is the parent class of all the classes in java bydefault. In other words, it is the topmost
class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that
parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't what object would be returned from this method
The Object class provides some common behaviours to all the objects such as object can be compared,
object can be cloned, object can be notified etc.

Jai Ma Saraswati

Methods of Object class


The Object class provides many methods. They are as follows:
Method Description

public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the metadata
of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's
monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.

public final void wait(long timeout)throws causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).

Jai Ma Saraswati

public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException miliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is
being garbage collected.

Object Cloning in Java

The object cloning is a way to create exact copy of an object.


For this purpose, clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to
create. If we don't implement Cloneable interface, clone() method
generatesCloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
1. protected Object clone() throws CloneNotSupportedException
Why use clone() method ?
The clone() method saves the extra processing task for creating the exact copy of an object. If we
perform it by using the new keyword, it will take a lot of processing to be performed that is why we use
object cloning.
Advantage of Object cloning
Less processing task.
Example of clone() method (Object cloning)
Let's see the simple example of object cloning
1. class Student implements Cloneable{
2. int rollno;
3. String name;
4.
5. Student(int rollno,String name){
6. this.rollno=rollno;

Jai Ma Saraswati

7. this.name=name;
8. }
9.
10. public Object clone()throws CloneNotSupportedException{
11. return super.clone();
12. }
13.
14. public static void main(String args[]){
15. try{
16. Student s1=new Student(101,"amit");
17.
18. Student s2=(Student)s1.clone();
19.
20. System.out.println(s1.rollno+" "+s1.name);
21. System.out.println(s2.rollno+" "+s2.name);
22.
23. }catch(CloneNotSupportedException c){}
24.
25. }
26. }
Output:101 amit
101 amit

As you can see in the above example, both reference variables have the same value. Thus, the clone()
copies the values of an object to another. So we don't need to write explicit code to copy the value of an
object to another.
If we create another object by new keyword and assign the values of another object to this one, it will
require a lot of processing on this object. So to save the extra processing task we use clone() method.

Array in Java
Normally, array is a collection of similar type of elements that have contiguous memory location.
In java, array is an object the contains elements of similar data type. It is a data structure where we store
similar elements. We can store only fixed elements in an array.
Array is index based, first element of the array is stored at 0 index.

Advantage of Array
 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.

Jai Ma Saraswati

Disadvantage of Array
 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in java.

Types of Array
There are two types of array.
 Single Dimensional Array
 Multidimensional Array

Single Dimensional Array


Syntax to Declare an Array in java
1. dataType[] arrayRefVar; (or)
2. dataType []arrayRefVar; (or)
3. dataType arrayRefVar[];
Instantiation of an Array in java
1. arrayRefVar=new datatype[size];
Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
1. class B{
2. public static void main(String args[]){
3.
4. int a[]=new int[5];//declaration and instantiation
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11. //printing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14.
15. }}
Output: 10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:
1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Jai Ma Saraswati

Let's see the simple example to print this array.


1. class B{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}
Output:33
3
4
5

Passing Java Array in the method


We can pass the array in the method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
1. class B{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. System.out.println(min);
9. }
10.
11. public static void main(String args[]){
12.
13. int a[]={33,3,4,5};
14. min(a);//passing array in the method
15.
16. }}
Output:3

Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in java
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Jai Ma Saraswati

Example to instantiate Multidimensional Array in java


1. int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. class B{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14.
15. }}
Output:1 2 3
245
445

What is class name of java array?


In java, array is an object. For array object, an proxy class is created whose name can be obtained by
getClass().getName() method on the object.
1. class B{
2. public static void main(String args[]){
3.
4. int arr[]={4,4,5};
5.
6. Class c=arr.getClass();
7. String name=c.getName();
8.
9. System.out.println(name);

Jai Ma Saraswati

10.
11. }}
Output:I

Copying an array
We can copy an array to another by the arraycopy method of System class.
Syntax of arraycopy method
1. public static void arraycopy(
2. Object src, int srcPos,Object dest, int destPos, int length
3. )
Example of arraycopy method
1. class ArrayCopyDemo {
2. public static void main(String[] args) {
3. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
4. 'i', 'n', 'a', 't', 'e', 'd' };
5. char[] copyTo = new char[7];
6.
7. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
8. System.out.println(new String(copyTo));
9. }
10. }
Output:caffein

Addition 2 matrices
Let's see a simple example that adds two matrices.
1. class AE{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
7. //creating another matrix to store the sum of two matrices
8. int c[][]=new int[2][3];
9.
10. //adding and printing addition of 2 matrices
11. for(int i=0;i<2;i++){
12. for(int j=0;j<3;j++){
13. c[i][j]=a[i][j]+b[i][j];
14. System.out.print(c[i][j]+" ");
15. }
16. System.out.println();//new line
17. }
18.
19. }}
Output:2 6 8

Jai Ma Saraswati

6 8 10
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known
as call by value. The changes being done in the called method, is not affected in the calling method.
Example of call by value in java
In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }
Output:before change 50
after change 50

Another Example of call by value in java


In case of call by reference original value is changed if we made changes in the called method. If we
pass object in place of any primitive value, original value will be changed. In this example we are passing
object as a value. Let's take a simple example:
1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);

Jai Ma Saraswati

15.
16. }
17. }
Output:before change 50
after change 150

strictfp keyword
The strictfp keyword ensures that you will get the same result on every platform if you perform operations
in the floating-point variable. The precision may differ from platform to platform that is why java
programming language have provided the strictfp keyword, so that you get same result on every
platform. So, now you have better control over the floating-point arithmetic.

Legal code for strictfp keyword


The strictfp keyword can be applied on methods, classes and interfaces.
1. strictfp class A{}//strictfp applied on class
1. strictfp interface M{}//strictfp applied on interface
1. class A{
2. void m(){}//strictfp applied on method
3. }

Illegal code for strictfp keyword


The strictfp keyword can be applied on abstract methods, variables or constructors.
1. class B{
2. strictfp abstract void m();//Illegal combination of modifiers
3. }
1. class B{
2. strictfp int data=10;//modifier strictfp not allowed here
3. }
1. class B{
2. strictfp B(){}//modifier strictfp not allowed here
3. }

Creating API Document


javadoc tool
We can create document api in java by the help of javadoc tool. In the java file, we must use the
documentation comment /**... */ to post information for the class, method, constructor, fields etc.
Let's see the simple class that contains documentation comment.
1. package com.abc;
2. /** This class is a user-defined class that contains one methods cube.*/
3. public class M{
4.
5. /** The cube method prints cube of the given number */
6. public static void cube(int n){System.out.println(n*n*n);}
7. }

Jai Ma Saraswati

To create the document API, you need to use the javadoc tool followed by java file name. There is no
need to compile the javafile.
On the command prompt, you need to write:
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open the index.html file to get
the information about the classes.

Java Command Line Arguments

The command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an
input.
So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must
pass at least one argument from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3.
4. System.out.println("Your first argument is: "+args[0]);
5.
6. }
7. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample ank
Output: Your first argument is: ank

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this purpose, we
have traversed the array using for loop.
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A ank 1 3 abc
Output: ank

Jai Ma Saraswati

1
3
abc

String Handling in Java


String Handling provides a lot of concepts that can be performed on a string such as concatenating
string, comparing string, substring etc.
In java, string is basically an immutable object. We will discuss about immutable string later. Let's first
understand what is string and how we can create the string object.
String
Generally string is a sequence of characters. But in java, string is an object. String class is used to create
string object.

Do You Know ?
 Why String objects are immutable ?
 How to create an immutable class ?
 What is string constant pool ?
 What code is written by the compiler if you concat any string by + (string concatenation
operator) ?
 What is the difference between StringBuffer and StringBuilder class ?
How to create String object?
There are two ways to create String object:
1. By string literal
2. By new keyword

1) String literal
String literal is created by double quote.For Example:
1. String s="Hello";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a
new String object instantiates, then is placed in the pool.For example:
1. String s1="Welcome";
2. String s2="Welcome";//no new object will be created

Jai Ma Saraswati

In the above example only one object will be created.First time JVM will find no string object with the
name "Welcome" in string constant pool,so it will create a new object.Second time it will find the string
with the name "Welcome" in string constant pool,so it will not create new object whether will return the
reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool inside the
Heap memory.

Why java uses concept of string literal?


To make Java more memory efficient (because no new objects are created if it exists already in string
constant pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal
"Welcome" will be placed in the string constant pool.The variable s will refer to the object in

Jai Ma Saraswati

Heap(nonpool).
Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
1. class Simple{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is
created with sachintendulkar. That is why string is known as immutable.

Jai Ma Saraswati

As you can see in the above figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For
example:
1. class Simple{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.

Why string objects are immutable in java?


Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one
object "sachin".If one reference variable changes the value of the object, it will be affected to all the
reference variables. That is why string objects are immutable in java.
String comparison in Java

We can compare two given strings on the basis of content and reference.
It is used in authentication (by equals() method),sorting (by compareTo() method), reference
matching (by == operator) etc.
There are three ways to compare String objects:
1. By equals() method
2. By = = operator
3. By compareTo() method
1) By equals() method
equals() method compares the original content of the string.It compares values of string for
equality.String class provides two methods:
 public boolean equals(Object another){} compares this string to the specified object.

Jai Ma Saraswati

 public boolean equalsIgnoreCase(String another){} compares this String to another String,


ignoring case.
1. class Simple{
2. public static void main(String args[]){
3.
4. String s1="Sachin";
5. String s2="Sachin";
6. String s3=new String("Sachin");
7. String s4="Saurav";
8.
9. System.out.println(s1.equals(s2));//true
10. System.out.println(s1.equals(s3));//true
11. System.out.println(s1.equals(s4));//false
12. }
13. }
Output:true
true
false
1. //Example of equalsIgnoreCase(String) method
2. class Simple{
3. public static void main(String args[]){
4.
5. String s1="Sachin";
6. String s2="SACHIN";
7.
8. System.out.println(s1.equals(s2));//false
9. System.out.println(s1.equalsIgnoreCase(s3));//true
10. }
11. }
Output:false
true

2) By == operator
The = = operator compares references not values.
1. //<b><i>Example of == operator</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="Sachin";
8. String s3=new String("Sachin");
9.
10. System.out.println(s1==s2);//true (because both refer to same instance)
11. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)

Jai Ma Saraswati

12. }
13. }
Output:true
false

3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values compare less than,
equal, or greater than.
Suppose s1 and s2 are two string variables.If:
 s1 == s2 :0
 s1 > s2 :positive value
 s1 < s2 :negative value
1. //<b><i>Example of compareTo() method:</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="Sachin";
8. String s3="Ratan";
9.
10. System.out.println(s1.compareTo(s2));//0
11. System.out.println(s1.compareTo(s3));//1(because s1>s3)
12. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
13. }
14. }
Output:0
1
-1
String Concatenation in Java
Concating strings form a new string i.e. the combination of multiple strings.
There are two ways to concat string objects:
1. By + (string concatenation) operator
2. By concat() method

1) By + (string concatenation) operator


String concatenation operator is used to add strings.For Example:
1. //Example of string concatenation operator
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin"+" Tendulkar";
7. System.out.println(s);//Sachin Tendulkar

Jai Ma Saraswati

8. }
9. }
Output:Sachin Tendulkar
The compiler transforms this to:
1. String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();
String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append
method.String concatenation operator produces a new string by appending the second operand onto the
end of the first operand.The string concatenation operator can concat not only string but primitive values
also.For Example:
1. class Simple{
2. public static void main(String args[]){
3.
4. String s=50+30+"Sachin"+40+40;
5. System.out.println(s);//80Sachin4040
6. }
7. }
Output:80Sachin4040
Note:If either operand is a string, the resulting operation will be string concatenation. If both operands
are numbers, the operator will perform an addition.

2) By concat() method
concat() method concatenates the specified string to the end of current string.
Syntax:public String concat(String another){}
1. //<b><i>Example of concat(String) method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin ";
7. String s2="Tendulkar";
8.
9. String s3=s1.concat(s2);
10.
11. System.out.println(s3);//Sachin Tendulkar
12. }
13. }
Output:Sachin Tendulkar

Substring in Java

Jai Ma Saraswati

A part of string is called substring. In other words, substring is a subset of another string.
In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is inclusive and
endIndex is exclusive.
You can get substring from the given String object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object containing the
substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex,int endIndex): This method returns new String object
containing the substring of the given string from specified startIndex to endIndex.

In case of string:
 startIndex:starts from index 0(inclusive).
 endIndex:starts from index 1(exclusive).
Example of java substring
1. //Example of substring() method
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin Tendulkar";
7. System.out.println(s.substring(6));//Tendulkar
8. System.out.println(s.substring(0,6));//Sachin
9. }
10. }
Output:Tendulkar
Sachin
Methods of String class in Java
java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can
perform operations on string such as trimming, concatenating, converting strings etc.
Let's see the important methods of String class.
Method Description

Jai Ma Saraswati

1)public boolean equals(Object anObject) Compares this string to the specified object.

2)public boolean equalsIgnoreCase(String Compares this String to another String, ignoring


another) case.

3)public String concat(String str) Concatenates the specified string to the end of
this string.

4)public int compareTo(String str) Compares two strings and returns int

5)public int compareToIgnoreCase(String str) Compares two strings, ignoring case


differences.

6)public String substring(int beginIndex) Returns a new string that is a substring of this
string.

7)public String substring(int beginIndex,int Returns a new string that is a substring of this
endIndex) string.

8)public String toUpperCase() Converts all of the characters in this String to


upper case

9)public String toLowerCase() Converts all of the characters in this String to


lower case.

10)public String trim() Returns a copy of the string, with leading and
trailing whitespace omitted.

11)public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.

12)public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.

13)public char charAt(int index) Returns the char value at the specified index.

14)public int length() Returns the length of this string.

15)public String intern() Returns a canonical representation for the string


object.

16)public byte[] getBytes() Converts string into byte array.

17)public char[] toCharArray() Converts string into char array.



Jai Ma Saraswati

18)public static String valueOf(int i) converts the int into String.

19)public static String valueOf(long i) converts the long into String.

20)public static String valueOf(float i) converts the float into String.

21)public static String valueOf(double i) converts the double into String.

22)public static String valueOf(boolean i) converts the boolean into String.

23)public static String valueOf(char i) converts the char into String.

24)public static String valueOf(char[] i) converts the char array into String.

25)public static String valueOf(Object obj) converts the Object into String.

26)public void replaceAll(String firstString,String Changes the firstString with secondString.


secondString)

First seven methods have already been discussed.Now Let's take the example of other methods:

toUpperCase() and toLowerCase() method


1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. System.out.println(s.toUpperCase());//SACHIN
6. System.out.println(s.toLowerCase());//sachin
7. System.out.println(s);//Sachin(no change in original)
8. }
9. }
Output:SACHIN
sachin
Sachin

trim() method
1. class Simple{
2. public static void main(String args[]){
3.
4. String s=" Sachin ";
5. System.out.println(s);// Sachin
6. System.out.println(s.trim());//Sachin
7. }

Jai Ma Saraswati

8. }
Output:Sachin
Sachin

startsWith() and endsWith() method


1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. System.out.println(s.startsWith("Sa"));//true
6. System.out.println(s.endsWith("n"));//true
7. }
8. }
Output:true
true

charAt() method
1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. System.out.println(s.charAt(0));//S
6. System.out.println(s.charAt(3));//h
7. }
8. }
Output:S
h

length() method
1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. System.out.println(s.length());//6
6. }
7. }
Output:6

intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as
determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String
object is added to the pool and a reference to this String object is returned.
1. class Simple{

Jai Ma Saraswati

2. public static void main(String args[]){


3.
4. String s=new String("Sachin");
5. String s2=s.intern();
6. System.out.println(s2);//Sachin
7. }
8. }
Output:Sachin

StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class is same as
String except it is mutable i.e. it can be changed.

Note: StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously .So it
is safe and will result in an order.

Commonly used Constructors of StringBuffer class:


1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.

Commonly used methods of StringBuffer class:


1. public synchronized StringBuffer append(String s): is used to append the specified string with
this string. The append() method is overloaded like append(char), append(boolean), append(int),
append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified
string with this string at the specified position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to
replace the string from specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the
string from specified startIndex and endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least
equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified position.
9. public int length(): is used to return the length of the string i.e. total number of characters.
10. public String substring(int beginIndex): is used to return the substring from the specified
beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return the substring from the
specified beginIndex and endIndex.

Jai Ma Saraswati

What is mutable string?


A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder
classes are used for creating mutable string.
simple example of StringBuffer class by append() method
The append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }

Example of insert() method of StringBuffer class


The insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }

Example of replace() method of StringBuffer class


The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }

Example of delete() method of StringBuffer class


The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
1. class A{
2. public static void main(String args[]){

Jai Ma Saraswati

3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }

Example of reverse() method of StringBuffer class


The reverse() method of StringBuilder class reverses the current string.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }

Example of capacity() method of StringBuffer class


The capacity() method of StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12. }
13. }

Example of ensureCapacity() method of StringBuffer class


The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the
current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){

Jai Ma Saraswati

3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.
13. sb.ensureCapacity(10);//now no change
14. System.out.println(sb.capacity());//now 34
15.
16. sb.ensureCapacity(50);//now (34*2)+2
17. System.out.println(sb.capacity());//now 70
18.
19. }
20. }

StringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is available since JDK1.5.
Commonly used Constructors of StringBuilder class:
1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified capacity as length.

Commonly used methods of StringBuilder class:


1. public StringBuilder append(String s): is used to append the specified string with this string.
The append() method is overloaded like append(char), append(boolean), append(int), append(float),
append(double) etc.
2. public StringBuilder insert(int offset, String s): is used to insert the specified string with this
string at the specified position. The insert() method is overloaded like insert(int, char), insert(int,
boolean), insert(int, int), insert(int, float), insert(int, double) etc.
3. public StringBuilder replace(int startIndex, int endIndex, String str): is used to replace the
string from specified startIndex and endIndex.
4. public StringBuilder delete(int startIndex, int endIndex): is used to delete the string from
specified startIndex and endIndex.
5. public StringBuilder reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least
equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified position.
9. public int length(): is used to return the length of the string i.e. total number of characters.
10. public String substring(int beginIndex): is used to return the substring from the specified

Jai Ma Saraswati

beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return the substring from the
specified beginIndex and endIndex.

simple program of StringBuilder class by append() method


The append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }

Example of insert() method of StringBuilder class


The insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }

Example of replace() method of StringBuilder class


The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }

Example of delete() method of StringBuilder class


The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
1. class A{

Jai Ma Saraswati

2. public static void main(String args[]){


3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }

Example of reverse() method of StringBuilder class


The reverse() method of StringBuilder class reverses the current string.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }

Example of capacity() method of StringBuilder class


The capacity() method of StringBuilder class returns the current capacity of the Builder. The default
capacity of the Builder is 16. If the number of character increases from its current capacity, it increases
the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12. }
13. }

Example of ensureCapacity() method of StringBuilder class


The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to
the current capacity. If it is greater than the current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
1. class A{

Jai Ma Saraswati

2. public static void main(String args[]){


3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.
13. sb.ensureCapacity(10);//now no change
14. System.out.println(sb.capacity());//now 34
15.
16. sb.ensureCapacity(50);//now (34*2)+2
17. System.out.println(sb.capacity());//now 70
18.
19. }
20. }

How to create Immutable class?


There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In
short, all the wrapper classes and String class is immutable. We can also create immutable class by
creating final class that have final data members as the example given below:
Example to create Immutable class
In this example, we have created a final class named Employee. It have one final datamember, a
parameterized constructor and getter method.
1. public final class Employee{
2. final String pancardNumber;
3.
4. public Employee(String pancardNumber){
5. this.pancardNumber=pancardNumber;
6. }
7.
8. public String getPancardNumber(){
9. return pancardNumber;
10. }
11.
12. }

The above class is immutable because:


 The instance variable of the class is final i.e. we cannot change the value of it after creating an
object.
 The class is final so we cannot create the subclass.

Jai Ma Saraswati

 There is no setter methods i.e. we have no option to change the value of the instance variable.
These points makes this class as immutable.
Understanding toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding
the toString() method, returns the desired output, it can be the state of an object etc. depends on your
implementation.
Advantage of the toString() method
By overriding the toString() method of the Object class, we can return values of the object, so we don't
need to write much code.

Understanding problem without toString() method


Let's see the simple code that prints reference.
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public static void main(String args[]){
13. Student s1=new Student(101,"Raj","lucknow");
14. Student s2=new Student(102,"Vijay","ghaziabad");
15.
16. System.out.println(s1);//compiler writes here s1.toString()
17. System.out.println(s2);//compiler writes here s2.toString()
18. }
19. }
Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I
want to print the values of these objects. Since java compiler internally calls toString() method,
overriding this method will return the specified values. Let's understand it with the example given below:

Example of toString() method


Now let's see the real example of toString() method.
1. class Student{
2. int rollno;

Jai Ma Saraswati

3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public String toString(){//overriding the toString() method
13. return rollno+" "+name+" "+city;
14. }
15. public static void main(String args[]){
16. Student s1=new Student(101,"Raj","lucknow");
17. Student s2=new Student(102,"Vijay","ghaziabad");
18.
19. System.out.println(s1);//compiler writes here s1.toString()
20. System.out.println(s2);//compiler writes here s2.toString()
21. }
22. }

Output:101 Raj lucknow


102 Vijay ghaziabad

StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break
string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer
class. We will discuss about the StreamTokenizer class in I/O chapter.
Constructors of StringTokenizer class
There are 3 constructors defined in the StringTokenizer class.
Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, creates StringTokenizer with specified string and delimeter.


String delim)

StringTokenizer(String str, creates StringTokenizer with specified string, delimeter and


String delim, boolean returnValue. If return value is true, delimiter characters are
returnValue) considered to be tokens. If it is false, delimiter characters serve

Jai Ma Saraswati

to separate tokens.

Methods of StringTokenizer class


The 6 useful methods of StringTokenizer class are as follows:
Public method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimeter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.


Simple example of StringTokenizer class
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan" on the
basis of whitespace.
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:my
name
is
khan

Example of nextToken(String delim) method of StringTokenizer class


1. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));

Jai Ma Saraswati

9. }
10. }
Output:Next token is : my
StringTokenizer class is deprecated now. It is recommended to use split() method of String class
or regex (Regular Expression).

Exception Handling in Java

The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to
handle the runtime errors so that normal flow of the application can be maintained.
Exception
 Dictionary Meaning:Exception is an abnormal condition.
 In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors.

Advantage of Exception Handling


Why we use exception handling?
The core advantage of exception handling is that normal flow of the application is maintained. Exception
normally disrupts the normal flow of the application that is why we use exception handling. Let's take a
scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of
the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of
the exception will be executed. That is why we use exception handling.

Jai Ma Saraswati

Do You Know ?
 What is the difference between checked and unchecked exceptions ?
 What happens behind the code int data=50/0; ?
 Why use multiple catch block ?
 Is there any possibility when finally block is not executed ?
 What is exception propagation ?
 What is the difference between throw and throws keyword ?
 What are the 4 rules for using exception handling with method overriding ?

Hierarchy of Exception classes

Types of Exception:
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception(compile-time)
2. Unchecked Exception(runtime)
3. Error

Jai Ma Saraswati

What is the difference between checked and unchecked exceptions ?


1)Checked Exception(Compile-time)
The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions. Checked exceptions are checked at compile-time.
Example:- IOException, SQLException, ServletException etc
2)Unchecked Exception(Runtime)
The classes that extend RuntimeException are known as unchecked exceptions. Unchecked exceptions
are not checked at compile-time rather they are checked at runtime.
Example:- ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
3)Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios of Exception Handling where exceptions may occur


There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
1. int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) Scenario where NumberFormatException occurs


The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string
variable that have characters, converting this variable into digit will occur NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as
shown below:
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException

Jai Ma Saraswati

Five keywords used in Exception handling:


1. try
2. catch
3. finally
4. throw
5. throws

try block
Enclose the code that might throw an exception in try block. It must be used within the method and must
be followed by either catch or finally block.
Syntax of try with catch block
1. try{
2. ...
3. }catch(Exception_class_Name reference){}
Syntax of try with finally block
1. try{
2. ...
3. }finally{}

catch block
Catch block is used to handle the Exception. It must be used after the try block.

Problem without exception handling


1. class Simple{
2. public static void main(String args[]){
3. int data=50/0;
4.
5. System.out.println("rest of the code...");
6. }
7. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed i.e. rest of the code... statement is
not printed. Let's see what happens behind the scene:

Jai Ma Saraswati

What happens behind the code int a=50/0;

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the exception occurred).
 Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is maintained
i.e. rest of the code is executed.

Solution by exception handling


1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=50/0;
5.
6. }catch(ArithmeticException e){System.out.println(e);}
7.
8. System.out.println("rest of the code...");
9. }
10. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is
printed.

Jai Ma Saraswati

Multiple catch block:


If you have to perform different tasks at the occrence of different Exceptions, use multple catch block.
Example of multiple catch block
1.
2. class Excep4{
3. public static void main(String args[]){
4. try{
5. int a[]=new int[5];
6. a[5]=30/0;
7. }
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10. catch(Exception e){System.out.println("common task completed");}
11.
12. System.out.println("rest of the code...");
13. }
14. }
Output:task1 completed
rest of the code...
Rule:At a time only one Exception is occured and at a time only one catch block is executed.
Rule:All catch blocks must be ordered from most specific to most general(last catch parameter
must be Exception) i.e. catch for ArithmeticException must come before catch for Exception .
1. class Excep4{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:Compile-time error

Nested try block:


try block within a try block is known as nested try block.
Why use nested try block?
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself
may cause another error. In such cases, exception handlers have to be nested

Jai Ma Saraswati

Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
Example:
1. Example of nested try block:
2.
3. class Excep6{
4. public static void main(String args[]){
5. try{
6. try{
7. System.out.println("going to divide");
8. int b =39/0;
9. }catch(ArithmeticException e){
10. System.out.println(e);}
11. try{
12. int a[]=new int[5];
13. a[5]=4;
14. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
15.
16. System.out.println("other statement);
17. }catch(Exception e){System.out.println("handeled");}
18.
19. System.out.println("normal flow..");
20. }
21. }

Jai Ma Saraswati

finally block
The finally block is a block that is always executed. It is mainly used to perform some important tasks
such as closing connection, stream etc.

Note:Before terminating the program, JVM executes finally block(if any).


Note:finally must be followed by try or catch block.

Why use finally block?


 finally block can be used to put "cleanup" code such as closing a file,closing connection etc.

case 1
Program in case exception does not occur
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.

Jai Ma Saraswati

11. System.out.println("rest of the code...");


12. }
13. }
Output:5
finally block is always executed
rest of the code...
case 2
Program in case exception occured but not handled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
case 3
Program in case exception occured and handled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...

Rule: For each try block there can be zero or more catch blocks, but only one finally block.

Jai Ma Saraswati

Note: The finally block will not be executed if program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).

throw keyword(mainly used to throw custom exception):-


The throw keyword is used to explictily throw an exception.
We can throw either checked or uncheked exception. The throw keyword is mainly used to throw custom
exception.
Example of throw keyword
In this example, we have created the validate method that takes integer value as a parameter. If the age
is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
1. class Excep13{
2.
3. static void validate(int age){
4. if(age<18)
5. throw new ArithmeticException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. validate(13);
12. System.out.println("rest of the code...");
13. }
14. }
Output:Exception in thread main java.lang.ArithmeticException:not valid

Exception propagation:
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to
the previous method,If not caught there, the exception again drops down to the previous method, and so
on until they are caught or until they reach the very bottom of the call stack.This is called exception
propagation.
Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).
Program of Exception Propagation
1. class Simple{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{

Jai Ma Saraswati

10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. Simple obj=new Simple();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Output:exception handled
normal flow...

In the above example exception occurs in m() method where it is not handled,so it is propagated to
previous n() method where it is not handled, again it is propagated to p() method where exception is
handled.
Exception can be handled in any method in call stack either in main() method,p() method,n() method or
m() method.

Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
Program which describes that checked exceptions are not propagated
1. class Simple{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }

Jai Ma Saraswati

13. public static void main(String args[]){


14. Simple obj=new Simple();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
Output:Compile Time Error

throws keyword
The throws keyword is used to declare an exception. It gives an information to the programmer that
there may occur an exception so it is better for the programmer to provide the exception handling code
so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up before
the code being used.
Syntax of throws keyword:
1. void method_name() throws exception_class_name{
2. ...
3. }

Que) Which exception should we declare?


Ans) checked exception only, because:
 unchecked Exception: under your control so correct your code.
 error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError
or StackOverflowError.

Advantage of throws keyword:


Now Checked Exception can be propagated (forwarded in call stack).

Program which describes that checked exceptions can be propagated by throws keyword.
1. import java.io.IOException;
2. class Simple{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }

Jai Ma Saraswati

14. public static void main(String args[]){


15. Simple obj=new Simple();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:exception handled
normal flow...

Rule: If you are calling a method that declares an exception, you must either caught or declare the
exception.
There are two cases:
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
 In case you handle the exception, the code will be executed fine whether exception occurs during
the program or not.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[]){
11. try{
12. Test t=new Test();
13. t.method();
14. }catch(Exception e){System.out.println("exception handled");}
15.
16. System.out.println("normal flow...");
17. }
18. }
Output:exception handled
normal flow...

Case2: You declare the exception


 A)In case you declare the exception, if exception does not occur, the code will be executed fine.
 B)In case you declare the exception if exception occures, an exception will be thrown at runtime
because throws does not handle the exception.
A)Program if exception does not occur
1. import java.io.*;

Jai Ma Saraswati

2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[])throws IOException{//declare exception
11. Test t=new Test();
12. t.method();
13.
14. System.out.println("normal flow...");
15. }
16. }
Output:device operation performed
normal flow...

B)Program if exception occurs


1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[])throws IOException{//declare exception
11. Test t=new Test();
12. t.method();
13.
14. System.out.println("normal flow...");
15. }
16. }
Output:Runtime Exception

Jai Ma Saraswati

Difference between throw and throws:


throw keyword throws keyword
1)throw is used to explicitly throw an exception. throws is used to declare an exception.

2)checked exception can not be propagated checked exception can be propagated with
without throws. throws.

3)throw is followed by an instance. throws is followed by class.

4)throw is used within the method. throws is used with the method signature.

5)You cannot throw multiple exception You can declare multiple exception e.g.
public void method()throws
IOException,SQLException.

Que) Can we rethrow an exception?


Yes by throwing same exception in catch block.

ExceptionHandling with MethodOverriding


There are many rules if we talk about methodoverriding with exception handling. The Rules are as
follows:
 If the superclass method does not declare an exception
o If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
 If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.
If the superclass method does not declare an exception
1) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws IOException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new Child();

Jai Ma Saraswati

12. p.msg();
13. }
14. }
Output:Compile Time Error

2) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new Child();
12. p.msg();
13. }
14. }
Output:child

If the superclass method declares an exception


1) Rule: If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.
Example in case subclass overridden method declares parent exception
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:Compile Time Error

Jai Ma Saraswati

Example in case subclass overridden method declares same exception


1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child

Example in case subclass overridden method declares subclass exception


1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws ArithmeticException{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child

Example in case subclass overridden method declares no exception


1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg(){System.out.println("child");}
8.
9. public static void main(String args[]){

Jai Ma Saraswati

10. Parent p=new Child();


11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child

Custom Exception
If you are creating your own Exception that is known as custom exception or user-defined exception.
1. class InvalidAgeException extends Exception{
2. InvalidAgeException(String s){
3. super(s);
4. }
5. }
1. class Excep13{
2.
3. static void validate(int age)throws InvalidAgeException{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. try{
12. validate(13);
13. }catch(Exception m){System.out.println("Exception occured: "+m);}
14.
15. System.out.println("rest of the code...");
16. }
17. }
Output:Exception occured: InvalidAgeException:not valid
rest of the code...

Nested classes in Java

A class declared inside a class is known as nested class.


We use nested classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable code.
Additionally, it can access all the members of outer class including private data members and methods.

Jai Ma Saraswati

Syntax of Nested class


1. class Outer_class_Name{
2. ...
3. class Nested_class_Name{
4. ...
5. }
6. ...
7. }
Advantage of nested classes
There are basically three advantages of nested classes. They are
 Nested classes represent a special type of relationship that is it can access all the members (data
members and methods) of outer class including private.
 Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
 Code Optimization: It requires less code to write.
Do You Know ?
 What is the internal code generated by the compiler for member inner class ?
 What are the two ways to create annonymous inner class ?
 Can we access the non-final local variable inside the local inner class ?
 How to access the static nested class ?
 Can we define an interface within the class ?
 Can we define a class within the interface ?
Q) Difference between nested class and inner class in Java?
Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested class:


There are two types of nested classes non-static and static nested classes.The non-static nested classes
are also known as inner classes.
1. non-static nested class(inner class)
 a)Member inner class
 b)Annomynous inner class
 c)Local inner class
2. static nested class

Jai Ma Saraswati

1)Member inner class


A class that is declared inside a class but outside a method is known as member inner class.
Invocation of Member Inner class
1. From within the class
2. From outside the class
Example of member inner class that is invoked inside a class
In this example, we are invoking the method of member inner class from the display method of Outer
class.
1. class Outer{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6.
7. void display(){
8. Inner in=new Inner();
9. in.msg();
10. }
11. public static void main(String args[]){
12. Outer obj=new Outer();
13. obj.display();
14. }
15. }

Jai Ma Saraswati

Output:data is 30

Internal code generated by the compiler for member inner class:


The java compiler creates a class file named Outer$Inner in this case. The Member inner class have the
reference of Outer class that is why it can access all the data members of Outer class including private.
1. import java.io.PrintStream;
2.
3. class Outer$Inner
4. {
5. final Outer this$0;
6. Outer$Inner()
7. { super();
8. this$0 = Outer.this;
9. }
10.
11. void msg()
12. {
13. System.out.println((new StringBuilder()).append("data is ")
14. .append(Outer.access$000(Outer.this)).toString());
15. }
16.
17. }

Example of member inner class that is invoked outside a class


In this example, we are invoking the msg() method of Inner class from outside the outer class i.e. Test
class.

Jai Ma Saraswati

1. <b><i>//Program of member inner class that is invoked outside a class</i></b>


2.
3. class Outer{
4. private int data=30;
5. class Inner{
6. void msg(){System.out.println("data is"+data);}
7. }
8. }
9.
10. class Test{
11. public static void main(String args[]){
12. Outer obj=new Outer();
13. Outer.Inner in=obj.new Inner();
14. in.msg();
15. }
16. }
Output:data is 30

2)Annonymous inner class


A class that have no name is known as annomymous inner class.
Annonymous class can be created by:
1. Class (may be abstract class also).
2. Interface
Program of annonymous inner class by abstract class
1. abstract class Person{
2. abstract void eat();
3. }
4.
5. class Emp{
6. public static void main(String args[]){
7. Person p=new Person(){
8. void eat(){System.out.println("nice fruits");}
9. };
10.
11. p.eat();
12. }
13. }
Output:nice fruits

What happens behind this code?


1. Person p=new Person(){
2. void eat(){System.out.println("nice fruits");}
3. };
4.
5. }

Jai Ma Saraswati

6. }
1. A class is created but its name is decided by the compiler which extends the Person class and
provides the implementation of the eat() method.
2. An object of Annonymous class is created that is reffered by p reference variable of Person type.
As you know well that Parent class reference variable can refer the object of Child class.
The internal code generated by the compiler for annonymous inner class
1. import java.io.PrintStream;
2. static class Emp$1 extends Person
3. {
4. Emp$1(){}
5.
6. void eat()
7. {
8. System.out.println("nice fruits");
9. }
10. }

Program of annonymous inner class by interface


1. interface Eatable{
2. void eat();
3. }
4.
5. class Emp{
6. public static void main(String args[]){
7.
8. Eatable e=new Eatable(){
9. public void eat(){System.out.println("nice fruits");}
10. };
11. e.eat();
12. }
13. }
Output:nice fruits
What does the compiler for annonymous inner class created by interface
It performs two main tasks behind this code:
1. Eatable p=new Eatable(){
2. void eat(){System.out.println("nice fruits");}
3. };
4.
5. }
6. }
1. A class is created but its name is decided by the compiler which implements the Eatable interface
and provides the implementation of the eat() method.
2. An object of Annonymous class is created that is reffered by p reference variable of Eatable type.
As you know well that Parent class reference variable can refer the object of Child class.
The internal code generated by the compiler for annonymous inner class created by interface
1. import java.io.PrintStream;

Jai Ma Saraswati

2. static class Emp$1 implements Eatable


3. {
4. Emp$1(){}
5.
6. void eat(){System.out.println("nice fruits");}
7. }

3)Local inner class


A class that is created inside a method is known as local inner class. If you want to invoke the methods
of local inner class, you must instantiate this class inside the method.
Program of local inner class
1. class Simple{
2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
11. Simple obj=new Simple();
12. obj.display();
13. }
14. }
Output:30

Internal code generated by the compiler for local inner class


In such case, compiler creates a class named Simple$1Local that have the reference of the outer class.
1. import java.io.PrintStream;
2. class Simple$1Local
3. {
4. final Simple this$0;
5.
6. Simple$1Local()
7. {
8. super();
9. this$0 = Simple.this;
10. }
11. void msg()
12. {
13. System.out.println(Simple.access$000(Simple.this));
14. }
15.
16. }

Jai Ma Saraswati

Rule: Local variable can't be private, public or protected.

Rules for Local Inner class


1) Local inner class cannot be invoked from outside the method.
2) Local inner class cannot access non-final local variable.
Program of accessing non-final local variable in local inner class
1. class Simple{
2. private int data=30;//instance variable
3. void display(){
4. int value=50;//local variable must be final
5. class Local{
6. void msg(){System.out.println(value);}//C.T.Error
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. Simple obj=new Simple();
13. obj.display();
14. }
15. }
Output:Compile Time Error
Program of accessing final local variable in local inner class
1. class Simple{
2. private int data=30;//instance variable
3. void display(){
4. final int value=50;//local variable must be final
5. class Local{
6. void msg(){System.out.println(data+" "+value);}//ok
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. Simple obj=new Simple();
13. obj.display();
14. }
15. }
Output:30 50

4)static nested class


A static class that is created inside a class is known as static nested class. It cannot access the non-
static members.
 It can access static data members of outer class including private.

Jai Ma Saraswati

 static nested class cannot access non-static (instance) data member or method.
Program of static nested class that have instance method
1. class Outer{
2. static int data=30;
3.
4. static class Inner{
5. void msg(){System.out.println("data is "+data);}
6. }
7.
8. public static void main(String args[]){
9. Outer.Inner obj=new Outer.Inner();
10. obj.msg();
11. }
12. }
Output:data is 30

In this example, you need to create the instance of static nested class because it has instance method
msg(). But you don't need to create the object of Outer class because nested class is static and static
properties, methods or classes can be accessed without object.

Internal code generated by the compiler for static nested class


1. import java.io.PrintStream;
2.
3. static class Outer$Inner
4. {
5. Outer$Inner(){}
6.
7. void msg(){
8. System.out.println((new StringBuilder()).append("data is ")
9. .append(Outer.data).toString());
10. }
11.
12. }

Program of static nested class that have static method


1. class Outer{
2. static int data=30;
3.
4. static class Inner{
5. static void msg(){System.out.println("data is "+data);}
6. }
7.
8. public static void main(String args[]){
9. Outer.Inner.msg();//no need to create the instance of static nested class
10. }

Jai Ma Saraswati

11. }
Output:data is 30

Nested Interface
An interface which is declared within another interface or class is known as nested interface. The nested
interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface
must be referred by the outer interface or class. It can't be accessed directly.
Points to remember for nested interfaces
There are given some points that should be remembered by the java programmer.
 Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
 Nested interfaces are declared static implicitely.
Syntax of nested interface which is declared within the interface
1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
7.
Syntax of nested interface which is declared within the class
1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
7.

Example of nested interface which is declared within the interface


In this example, we are going to learn how to declare the nested interface and how we can access it.
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7.
8. class Test implements Showable.Message{
9. public void msg(){System.out.println("Hello nested interface");}
10.
11. public static void main(String args[]){
12. Showable.Message message=new Test();//upcasting here
13. message.msg();

Jai Ma Saraswati

14. }
15. }
download the example of nested interface
Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer interface
Showable because it cannot be accessed directly. It is just like almirah inside the room, we cannot
access the almirah directly because we must enter the room first. In collection frameword, sun
microsystem has provided a nested interface Entry. Entry is the subinterface of Map i.e. accessed by
Map.Entry.

Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
1. public static interface Showable$Message
2. {
3. public abstract void msg();
4. }

Example of nested interface which is declared within the class


Let's see how can we define an interface inside the class and how can we access it.
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
6.
7. class Test implements A.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. A.Message message=new Test();//upcasting here
12. message.msg();
13. }
14. }
Output:hello nested interface

Can we define a class inside the interface ?


Yes, Ofcourse! If we define a class inside the interface, java compiler creates a static nested class. Let's
see how can we define a class within the interface:
1. interface M{
2. class A{}
3. }

Jai Ma Saraswati

Multithreading in Java
Multithreading is a process of executing multiple threads simultaneously.
Thread is basically a lightweight subprocess, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
Advantage of multithreading over multiprocessing:-
We use multithreading insteed of multiprocessing because threads share a common memory area.They
don't allocate separate memory area so save memory, and context-switching between the threads takes
less time than processes.
Multithreading is mostly used in games, animation etc.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved by two ways:
 Process-based Multitasking(Multiprocessing)
 Thread-based Multitasking(Multithreading)
1)Process-based Multitasking (Multiprocessing)
 Each process have its own address in memory i.e. each process allocates separate memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for saving and loading registers,
memory maps, updating lists etc.
2)Thread-based Multitasking (Multithreading)
 Threads share the same address space.
 Thread is lightweight.
 Cost of communication between the thread is low.
 Note:At least one process is required for each thread.

What is Thread?
A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path of execution. It
shares the memory area of process.

Jai Ma Saraswati

As shown in the above figure, thread is executed inside the process. There is context-switching between
the threads. There can be multiple processes inside the OS and one process can have multiple threads.
Note:At a time only one thread is executed.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states in the thread. According to sun, there is only 4 states new,
runnable, non-runnable and terminated. There is no running state. But for better understanding the
threads, we are explaining it in the 5 states. The life cycle of the thread is controlled by JVM. The thread
states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

Jai Ma Saraswati

1)New
The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.
2)Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3)Running
The thread is in running state if the thread scheduler has selected it.
4)Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5)Terminated
A thread is in terminated or dead state when its run() method exits.
How to create thread:
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread
class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).

Jai Ma Saraswati

16. public void resume(): is used to resume the suspended thread(depricated).


17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
 A new thread starts(with new callstack).
 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

1)By extending Thread class:


1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output:thread is running...

Who makes your class object as thread object?


Thread class constructor allocates a new thread object.When you create object of Multi class,your
class constructor is invoked(provided by Compiler) fromwhere Thread class constructor is invoked(by
super() as first statement).So your Multi class object is thread object now.

2)By implementing the Runnable interface:


1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.

Jai Ma Saraswati

6. public static void main(String args[]){


7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread object.So
you need to explicitely create Thread class object.We are passing the object of your class that
implements Runnable so that your class run() method may execute.
The Thread Schedular:
 The thread scheduler is the part of the JVM that decides which thread should run.
 There is no guarantee that which runnable thread will be chosen to run by the thread schedular.
 Only one thread at a time can run in a single process.
 The thread schedular mainly uses preemptive or time slicing scheduling to schedule the threads.
What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states
or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of
time and then reenters the pool of ready tasks. The scheduler then determines which task should
execute next, based on priority and other factors.
Sleeping a thread (sleep() method):
The sleep() method of Thread class is used to sleep a thread for the specified time.
Syntax of sleep() method:
The Thread class provides two methods for sleeping a thread:
 public static void sleep(long miliseconds)throws InterruptedException
 public static void sleep(long miliseconds, int nanos)throws InterruptedException
Program of sleep() method
1.
2. class Multi extends Thread{
3. public void run(){
4. for(int i=1;i<5;i++){
5. try{Thread.sleep(500);}
6. catch(InterruptedException e)
7. {System.out.println(e);}
8. System.out.println(i);
9. }
10. }
11. public static void main(String args[]){
12. Multi t1=new Multi();
13. Multi t2=new Multi();
14.
15. t1.start();
16. t2.start();
17. }

Jai Ma Saraswati

18. }
Output:1
1
2
2
3
3
4
4
5
5
As you know well that at a time only one thread is executed. If you sleep a thread for the specified
time,the thread shedular picks up another thread and so on.
Can we start a thread twice?
No. After staring a thread, it can never be started again. If you does so, an IllegalThreadStateException
is thrown. For Example:
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. t1.start();
9. }
10. }
Output:running
Exception in thread "main" java.lang.IllegalThreadStateException

What if we call run() method directly instead start() method?


 Each thread starts in a separate call stack.
 Invoking the run() method from main thread, the run() method goes onto the current call stack
rather than at the beginning of a new call stack.
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.run();//fine, but does not start a separate call stack
8. }
9. }
Output:running...

Jai Ma Saraswati

Problem if you direct call run() method


1.
2. class Multi extends Thread{
3. public void run(){
4. for(int i=1;i<5;i++){
5. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
6. System.out.println(i);
7. }
8. }
9. public static void main(String args[]){
10. Multi t1=new Multi();
11. Multi t2=new Multi();
12.
13. t1.run();
14. t2.run();
15. }
16. }
Output:1
2
3
4
5
1
2
3
4
5

As you can see in the above program that there is no context-switching because here t1 and t2 will be
treated as normal object not thread object.

Jai Ma Saraswati

The join() method:


The join() method waits for a thread to die.In other words, it causes the currently running threads to stop
executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long miliseconds)throws InterruptedException
Example of join() method
1.
2. class Multi extends Thread{
3. public void run(){
4. for(int i=1;i<=5;i++){
5. try{
6. Thread.sleep(500);
7. }catch(Exception e){System.out.println(e);}
8. System.out.println(i);
9. }
10. }
11. public static void main(String args[]){
12. Multi t1=new Multi();
13. Multi t2=new Multi();
14. Multi t3=new Multi();
15. t1.start();
16. try{
17. t1.join();
18. }catch(Exception e){System.out.println(e);}
19.
20. t2.start();
21. t3.start();
22. }
23. }
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5

Jai Ma Saraswati

As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.
Example of join(long miliseconds) method
1.
2. class Multi extends Thread{
3. public void run(){
4. for(int i=1;i<=5;i++){
5. try{
6. Thread.sleep(500);
7. }catch(Exception e){System.out.println(e);}
8. System.out.println(i);
9. }
10. }
11. public static void main(String args[]){
12. Multi t1=new Multi();
13. Multi t2=new Multi();
14. Multi t3=new Multi();
15. t1.start();
16. try{
17. t1.join(1500);
18. }catch(Exception e){System.out.println(e);}
19.
20. t2.start();
21. t3.start();
22. }
23. }
Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5

Jai Ma Saraswati

In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts
executing.

getName(),setName(String) and getId() method:


public String getName()
public void setName(String name)
public long getId()
1. class Multi6 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi6 t1=new Multi6();
7. Multi6 t2=new Multi6();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10. System.out.println("id of t1:"+t1.getId());
11.
12. t1.start();
13. t2.start();
14.
15. t1.setName("Ank");
16. System.out.println("After changing name of t1:"+t1.getName());
17. }
18. }
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Ank
running...

The currentThread() method:


The currentThread() method returns a reference to the currently executing thread object.
Syntax:
public static Thread currentThread()
Example of currentThread() method
1.
2. class Multi6 extends Thread{
3. public void run(){

Jai Ma Saraswati

4. System.out.println(Thread.currentThread().getName());
5. }
6. }
7. public static void main(String args[]){
8. Multi6 t1=new Multi6();
9. Multi6 t2=new Multi6();
10.
11. t1.start();
12. t2.start();
13. }
14. }
Output:Thread-0
Thread-1

Naming a thread:
The Thread class provides methods to change and get the name of a thread.
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
Example of naming a thread:
1. class Multi6 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi6 t1=new Multi6();
7. Multi6 t2=new Multi6();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10.
11. t1.start();
12. t2.start();
13.
14. t1.setName("Ank");
15. System.out.println("After changing name of t1:"+t1.getName());
16. }
17. }
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Ank
running...

Jai Ma Saraswati

The currentThread() method:


The currentThread() method returns a reference to the currently executing thread object.
Syntax of currentThread() method:
 public static Thread currentThread(): returns the reference of currently running thread.

Example of currentThread() method:
1. class Multi6 extends Thread{
2. public void run(){
3. System.out.println(Thread.currentThread().getName());
4. }
5. }
6. public static void main(String args[]){
7. Multi6 t1=new Multi6();
8. Multi6 t2=new Multi6();
9.
10. t1.start();
11. t2.start();
12. }
13. }
Output:Thread-0
Thread-1

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority (known as preemptive scheduling). But
it is not guaranteed because it depends on JVM specifification that which sheduling it chooses.
3 constants defiend in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
Example of priority of a Thread:
1. class Multi10 extends Thread{
2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
5.
6. }
7. public static void main(String args[]){
8. Multi10 m1=new Multi10();
9. Multi10 m2=new Multi10();

Jai Ma Saraswati

10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Daemon Thread
There are two types of threads user thread and daemon thread. The daemon thread is a service provider
thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user
threads dies, JVM termintates this thread automatically.
Points to remember for Daemon Thread:
 It provides services to user threads for background supporting tasks. It has no role in life than to
serve user threads.
 Its life depends on user threads.
 It is a low priority thread.
Why JVM termintates the daemon thread if there is no user thread remaining?
The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM
terminates the daemon thread if there is no user thread.
Methods for Daemon thread:
The java.lang.Thread class provides two methods related to daemon thread
 public void setDaemon(boolean status): is used to mark the current thread as daemon thread
or user thread.
 public boolean isDaemon(): is used to check that current is daemon.
Simple example of Daemon thread
1. class MyThread extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. MyThread t1=new MyThread();
9. MyThread t2=new MyThread();
10. t1.setDaemon(true);
11.

Jai Ma Saraswati

12. t1.start();
13. t2.start();
14. }
15. }
Output:Name: thread-0
Daemon: true
Name: thread-1
Daemon: false

Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw
IllegalThreadStateException.
1. class MyThread extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. MyThread t1=new MyThread();
9. MyThread t2=new MyThread();
10. t1.start();
11. t1.setDaemon(true);//will throw exception here
12. t2.start();
13. }
14. }
Output:exception in thread main: java.lang.IllegalThreadStateException

Thread Pooling in Java


Thread pool represents a group of worker threads that are waiting for the job. Here, threads are executed
whenever they get the job.
In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled
out and assigned a job by the service provider. After completion of the job, thread is contained in the
thread pool again.
Advantage of Thread Pool
Better performance It saves time because there is no need to create new thread.
Where is it used?
It is used in Servlet and JSP where container creates a thread pool to process the request.
Example of Java Thread Pool
Let's see a simple example of java thread pool using executors and ThreadPoolExecutor.
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. class WorkerThread implements Runnable {
4. private String message;
5. public WorkerThread(String s){

Jai Ma Saraswati

6. this.message=s;
7. }
8.
9. public void run() {
10. System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
11. processmessage();
12. System.out.println(Thread.currentThread().getName()+" (End)");
13. }
14.
15. private void processmessage() {
16. try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
17. }
18. }
19.
20. public class SimpleThreadPool {
21. public static void main(String[] args) {
22. ExecutorService executor = Executors.newFixedThreadPool(5);
23. for (int i = 0; i < 10; i++) {
24. Runnable worker = new WorkerThread(" " + i);
25. executor.execute(worker);
26. }
27. executor.shutdown();
28. while (!executor.isTerminated()) { }
29.
30. System.out.println("Finished all threads");
31. }
32.
33. }
--------------------------
Output:
pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9

Jai Ma Saraswati

pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
Shutdown Hook
The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down
normally or abruptly. Performing clean resource means closing log file, sending some alerts or something
else. So if you want to execute some code before JVM shuts down, use shutdown hook.
When does the JVM shut down?
The JVM shuts down when:
 user presses ctrl+c on the command prompt
 System.exit(int) method is invoked
 user logoff
 user shutdown etc.

The addShutdownHook(Runnable r) method


The addShutdownHook() method of Runtime class is used to register the thread with the Virtual
Machine. Syntax:
1. public void addShutdownHook(Runnable r){}

The object of Runtime class can be obtained by calling the static factory method getRuntime(). For
example:
Runtime r = Runtime.getRuntime();
Factory method
The method that returns the instance of a class is known as factory method.

Simple example of Shutdown Hook


1. class MyThread extends Thread{
2. public void run(){
3. System.out.println("shut down hook task completed..");
4. }
5. }
6.
7. public class Shutdown {
8. public static void main(String[] args)throws Exception {
9.
10. Runtime r=Runtime.getRuntime();
11. r.addShutdownHook(new MyThread());
12.
13. System.out.println("Now main sleeping... press ctrl+c to exit");
14. try{Thread.sleep(3000);}catch (Exception e) {}

Jai Ma Saraswati

15. }
16. }
Output:Now main sleeping... press ctrl+c to exit
shut down hook task completed..

Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime class.

Same example of Shutdown Hook by annonymous class:


1. public class Shutdown {
2. public static void main(String[] args)throws Exception {
3.
4. Runtime r=Runtime.getRuntime();
5.
6. r.addShutdownHook(new Runnable(){
7. public void run(){
8. System.out.println("shut down hook task completed..");
9. }
10. }
11. );
12.
13. System.out.println("Now main sleeping... press ctrl+c to exit");
14. try{Thread.sleep(3000);}catch (Exception e) {}
15. }
16. }
Output:Now main sleeping... press ctrl+c to exit
shut down hook task completed..

How to perform single task by multiple threads?


If you have to perform single task by many threads, have only one run() method.For example:
1. //<b><i>Program of performing single task by multiple threads</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. System.out.println("task one");
6. }
7. public static void main(String args[]){
8. Multi t1=new Multi();
9. Multi t2=new Multi();
10. Multi t3=new Multi();
11.
12. t1.start();
13. t2.start();

Jai Ma Saraswati

14. t3.start();
15. }
16. }
Output:task one
task one
task one
Program of performing single task by multiple threads:-
1.
2. class Multi3 implements Runnable{
3. public void run(){
4. System.out.println("task one");
5. }
6.
7. public static void main(String args[]){
8. Thread t1 =new Thread(new Multi3());//passing annonymous object of Multi3 class
9. Thread t2 =new Thread(new Multi3());
10.
11. t1.start();
12. t2.start();
13.
14. }
15. }
Output:task one
task one

Note: Each thread run in a separate callstack.



Jai Ma Saraswati

How to perform multiple tasks by multiple threads (multtasking in multithreading)?


If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example:
1. //<b><i>Program of performing two tasks by two threads</i></b>
2.
3. class Simple1 extends Thread{
4. public void run(){
5. System.out.println("task one");
6. }
7. }
8.
9. class Simple2 extends Thread{
10. public void run(){
11. System.out.println("task two");
12. }
13. }
14.
15. class Test{
16. public static void main(String args[]){
17. Simple1 t1=new Simple1();
18. Simple2 t2=new Simple2();
19.
20. t1.start();
21. t2.start();
22. }
23. }
Output:task one
task two
Same example as above by annonymous class that extends Thread class:
Program of performing two tasks by two threads:-
1.
2. class Test{
3. public static void main(String args[]){
4. Thread t1=new Thread(){
5. public void run(){
6. System.out.println("task one");
7. }
8. };
9. Thread t2=new Thread(){
10. public void run(){
11. System.out.println("task two");
12. }
13. };
14.
15.
16. t1.start();
17. t2.start();

Jai Ma Saraswati

18. }
19. }
Output:task one
task two
Same example as above by annonymous class that implements Runnable interface:
Program of performing two tasks by two threads
1.
2. class Test{
3. public static void main(String args[]){
4. Runnable r1=new Runnable(){
5. public void run(){
6. System.out.println("task one");
7. }
8. };
9.
10. Runnable r2=new Runnable(){
11. public void run(){
12. System.out.println("task two");
13. }
14. };
15.
16. Thread t1=new Thread(r1);
17. Thread t2=new Thread(r1);
18.
19. t1.start();
20. t2.start();
21. }
22. }
Output:task one
task two

Garbage Collection:
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically.
Advantage of Garbage Collection:
 It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
 It is automatically done by the garbage collector so we don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
 By nulling the reference
 By assigning a reference to another
 By annonymous object etc.

Jai Ma Saraswati

1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
2) By assigning a reference to another:
1. Employee e1=new Employee();
2. Employee e2=new Employee();
3.
4. e1=e2;//now the first object refered by e1 is available for garbage collection
3) By annonymous object:
1. new Employee();

finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This method can be
used to perform cleanup processing. This method is defined in System class as:
1. protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new keyword.
So if you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).

gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found
in System and Runtime classes.
1. public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection:


1. class Simple{
2.
3. public void finalize(){System.out.println("object is garbage collected");}
4.
5. public static void main(String args[]){
6. Simple s1=new Simple();
7. Simple s2=new Simple();
8. s1=null;
9. s2=null;
10. System.gc();
11. }
12. }
Output: object is garbage collected
object is garbage collected
Note: Neither finalization nor garbage collection is guaranteed.
`

Jai Ma Saraswati

Synchronization
Synchronization is the capabilility of control the access of multiple threads to any shared resource.
Synchronization is better in case we want only one thread can access the shared resource at a time.
Why use Synchronization?
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
 Process Synchronization
 Thread Synchronization
Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
 Mutual Exclusive
 Synchronized method.
 Synchronized block.
 static synchronization.
 Cooperation (Inter-thread communication)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be
done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization

Understanding the concept of Lock


Synchronization is built around an internal entity known as the lock or monitor.Every object has an lock
associated with it. By convention, a thread that needs consistent access to an object's fields has to
acquire the object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.
Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
1. Class Table{
2.
3. void printTable(int n){//method not synchronized
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);

Jai Ma Saraswati

8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. class Use{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }
Output: 5
100
10
200
15
300
20
400
25
500

Jai Ma Saraswati

Solution by synchronized method


 If you declare any method as synchronized, it is known as synchronized method.
 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the method returns.
Program of synchronized method
1. Class Table{
2.
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. class Use{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();

Jai Ma Saraswati

40. t2.start();
41. }
42. }
Output: 5
10
15
20
25
100
200
300
400
500

Same Example of synchronized method by using annonymous class


In this program, we have created the two threads by annonymous class, so less coding is required.
Program of synchronized method by using annonymous class
1.
2. Class Table{
3.
4. synchronized void printTable(int n){//synchronized method
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11.
12. }
13. }
14.
15. class Use{
16. public static void main(String args[]){
17. final Table obj = new Table();//only one object
18.
19. MyThread1 t1=new MyThread1(){
20. public void run(){
21. obj.printTable(5);
22. }
23. };
24. MyThread1 t2=new MyThread1(){
25. public void run(){
26. obj.printTable(100);
27. }

Jai Ma Saraswati

28. };
29.
30. t1.start();
31. t2.start();
32. }
33. }
Output: 5
10
15
20
25
100
200
300
400
500

Synchronized block
Synchronized block can be used to perform synchronization on any specific resouce of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can
use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the synchronized
method.
Points to remember for Synchronized block
 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
1. synchronized (object reference expression) {
2. //code block
3. }
Example of synchronized block
Program of synchronized block

1. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method

Jai Ma Saraswati

13. }
14.
15. class MyThread1 extends Thread{
16. Table t;
17. MyThread1(Table t){
18. this.t=t;
19. }
20. public void run(){
21. t.printTable(5);
22. }
23.
24. }
25. class MyThread2 extends Thread{
26. Table t;
27. MyThread2(Table t){
28. this.t=t;
29. }
30. public void run(){
31. t.printTable(100);
32. }
33. }
34.
35. class Use{
36. public static void main(String args[]){
37. Table obj = new Table();//only one object
38. MyThread1 t1=new MyThread1(obj);
39. MyThread2 t2=new MyThread2(obj);
40. t1.start();
41. t2.start();
42. }
43. }
Output:5
10
15
20
25
100
200
300
400
500

Jai Ma Saraswati

Same Example of synchronized block by using annonymous class:


Program of synchronized block by using annonymous class
1.
2. class Table{
3.
4. void printTable(int n){
5. synchronized(this){//synchronized block
6. for(int i=1;i<=5;i++){
7. System.out.println(n*i);
8. try{
9. Thread.sleep(400);
10. }catch(Exception e){System.out.println(e);}
11. }
12. }
13. }//end of the method
14. }
15.
16. class Use{
17. public static void main(String args[]){
18. final Table obj = new Table();//only one object
19.
20. Thread t1=new Thread(){
21. public void run(){
22. obj.printTable(5);
23. }
24. };
25. Thread t2=new Thread(){
26. public void run(){
27. obj.printTable(100);
28. }
29. };
30.
31. t1.start();
32. t2.start();
33. }
34. }
Output:5
10
15
20
25
100
200
300

Jai Ma Saraswati

400
500

Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.

Problem without static synchronization


Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of
synchonized method and synchronized block there cannot be inteference between t1 and t2 or t3 and t4
because t1 and t2 both refers to a common object that have a single lock.But there can be interference
between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want no
interference between t1 and t3 or t2 and t4.Static synchronization solves this problem.
Example of static synchronization
In this example we are applying synchronized keyword on the static method to perform statis
synchrnization.
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. class MyThread1 extends Thread{

Jai Ma Saraswati

14. public void run(){


15. Table.printTable(1);
16. }
17. }
18.
19. class MyThread2 extends Thread{
20. public void run(){
21. Table.printTable(10);
22. }
23. }
24.
25. class MyThread3 extends Thread{
26. public void run(){
27. Table.printTable(100);
28. }
29. }
30.
31.
32.
33.
34. class MyThread4 extends Thread{
35. public void run(){
36. Table.printTable(1000);
37. }
38. }
39.
40. class Use{
41. public static void main(String t[]){
42. MyThread1 t1=new MyThread1();
43. MyThread2 t2=new MyThread2();
44. MyThread3 t3=new MyThread3();
45. MyThread4 t4=new MyThread4();
46. t1.start();
47. t2.start();
48. t3.start();
49. t4.start();
50. }
51. }
Output: 1
2
3
4
5
6
7
8

Jai Ma Saraswati

9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

Same example of static synchronization by annonymous class


In this example, we are using annonymous class to create the threads.
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}

Jai Ma Saraswati

9. }
10. }
11. }
12.
13. public class Test {
14. public static void main(String[] args) {
15.
16. Thread t1=new Thread(){
17. public void run(){
18. Table.printTable(1);
19. }
20. };
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
27.
28. Thread t3=new Thread(){
29. public void run(){
30. Table.printTable(100);
31. }
32. };
33.
34. Thread t4=new Thread(){
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
39. t1.start();
40. t2.start();
41. t3.start();
42. t4.start();
43.
44. }
45. }
Output: 1
2
3
4
5
6
7
8
9

Jai Ma Saraswati

10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

Synchronized block on a class lock:


The block synchronizes on the lock of the object denoted by the reference .class name .class. A static
synchronized method printTable(int n) in class Table is equivalent to the following declaration:
1. static void printTable(int n) {
2. synchronized (Table.class) { // Synchronized block on class A
3. // ...
4. }
5. }

Jai Ma Saraswati

Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another
thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads
are waiting for each other to release the lock, the condition is called daedlock.

Example of Deadlock in java:


1. public class DeadlockExample {
2. public static void main(String[] args) {
3. final String resource1 = "ratan jaiswal";
4. final String resource2 = "vimal jaiswal";
5. // t1 tries to lock resource1 then resource2
6. Thread t1 = new Thread() {
7. public void run() {
8. synchronized (resource1) {
9. System.out.println("Thread 1: locked resource 1");
10.
11. try { Thread.sleep(100);} catch (Exception e) {}
12.
13. synchronized (resource2) {
14. System.out.println("Thread 1: locked resource 2");
15. }
16. }
17. }
18. };
19.
20. // t2 tries to lock resource2 then resource1
21. Thread t2 = new Thread() {
22. public void run() {
23. synchronized (resource2) {
24. System.out.println("Thread 2: locked resource 2");
25.
26. try { Thread.sleep(100);} catch (Exception e) {}
27.
28. synchronized (resource1) {
29. System.out.println("Thread 2: locked resource 1");
30. }
31. }

Jai Ma Saraswati

32. }
33. };
34.
35.
36. t1.start();
37. t2.start();
38. }
39. }
40.
Output: Thread 1: locked resource 1
Thread 2: locked resource 2
Another example of creating deadlock:
public class Deadlock {

String str1 = "Java";


String str2 = "UNIX";

Thread trd1 = new Thread("My Thread 1"){


public void run(){
while(true){
synchronized(str1){
synchronized(str2){
System.out.println(str1 + str2);
}
}
}
}
};

Thread trd2 = new Thread("My Thread 2"){


public void run(){
while(true){
synchronized(str2){
synchronized(str1){
System.out.println(str2 + str1);
}
}
}
}
};

public static void main(String a[]){



Jai Ma Saraswati

Deadlock mdl = new Deadlock();


mdl.trd1.start();
mdl.trd2.start();
}
}
Inter-thread communication in Java
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()

1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify() method
or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.
Method Description
public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws waits for the specified amount of
InterruptedException time.

2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object,
one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the
implementation.
Syntax:
public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()

Jai Ma Saraswati

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:


1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the
lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
It is because they are related to lock and object has a lock.

Difference between wait and sleep?


wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.

Jai Ma Saraswati

Example of inter thread communication in java


Let's see the simple example of inter thread communication.
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Jai Ma Saraswati

Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method
on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not
in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't
interrupt the thread but sets the interrupt flag to true. Let's first see the methods provided by the Thread
class for thread interruption.

The 3 methods provided by the Thread class for interrupting a thread


 public void interrupt()
 public static boolean interrupted()
 public boolean isInterrupted()

Example of interrupting a thread that stops working


In this example, after interrupting the thread, we are propagating it, so it will stop working. If we don't
want to stop the thread, we can handle it where sleep() or wait() method is invoked. Let's first see the
example where we are propagating the exception.
1. class A extends Thread{
2. public void run(){
3. try{
4. Thread.sleep(1000);
5. System.out.println("task");
6. }catch(InterruptedException e){
7. throw new RuntimeException("Thread interrupted..."+e);
8. }
9.
10. }
11.
12. public static void main(String args[]){
13. A t1=new A();
14. t1.start();
15. try{
16. t1.interrupt();
17. }catch(Exception e){System.out.println("Exception handled "+e);}
18.
19. }
20. }
Output:Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)

Example of interrupting a thread that doesn't stop working


In this example, after interrupting the thread, we handle the exception, so it will break out the sleeping
but will not stop working.
1. class A extends Thread{

Jai Ma Saraswati

2. public void run(){


3. try{
4. Thread.sleep(1000);
5. System.out.println("task");
6. }catch(InterruptedException e){
7. System.out.println("Exception handled "+e);
8. }
9. System.out.println("thread is running...");
10. }
11.
12. public static void main(String args[]){
13. A t1=new A();
14. t1.start();
15.
16. t1.interrupt();
17.
18. }
19. }
--------------------------
Output:Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running...

Example of interrupting thread that behaves normally


If thread is not in sleeping or waiting state, calling the interrupt() method sets the interrupted flag to true
that can be used to stop the thread by the java programmer later.
1. class A extends Thread{
2.
3. public void run(){
4. for(int i=1;i<=5;i++)
5. System.out.println(i);
6. }
7.
8. public static void main(String args[]){
9. A t1=new A();
10. t1.start();
11.
12. t1.interrupt();
13.
14. }
15. }
Output:1
2
3
4
5

Jai Ma Saraswati

What about isInterrupted and interrupted method?


The isInterrupted() method returns the interrupted flag either true or false. The static interrupted() method
returns the interrupted flag after that it sets the flag to false if it is true.
1. class InterruptedDemo extends Thread{
2.
3. public void run(){
4. for(int i=1;i<=2;i++){
5. if(Thread.interrupted()){
6. System.out.println("code for interrupted thread");
7. }
8. else{
9. System.out.println("code for normal thread");
10. }
11.
12. }//end of for loop
13. }
14.
15. public static void main(String args[]){
16.
17. InterruptedDemo t1=new InterruptedDemo();
18. InterruptedDemo t2=new InterruptedDemo();
19.
20. t1.start();
21. t1.interrupt();
22.
23. t2.start();
24.
25. }
26. }
Output:Code for interrupted thread
code for normal thread
code for normal thread
code for normal thread

Reentrant Monitor in Java


According to Sun Microsystems, Java monitors are reentrant means java thread can reuse the same
monitor for different synchronized methods if method is called from the method.

Advantage of Reentrant Monitor


It eliminates the possibility of single thread deadlocking

Let's understand the java reentrant monitor by the example given below:
1. class Reentrant {
2. public synchronized void m() {
3. n();

Jai Ma Saraswati

4. System.out.println("this is m() method");


5. }
6. public synchronized void n() {
7. System.out.println("this is n() method");
8. }
9. }
In this class, m and n are the synchronized methods. The m() method internally calls the n() method.
Now let's call the m() method on a thread. In the class given below, we are creating thread using
annonymous class.
1. class ReentrantExample{
2. public static void main(String args[]){
3. final Reentrant re=new Reentrant();
4.
5. Thread t1=new Thread(){
6. public void run(){
7. re.m();//calling method of Reentrant class
8. }
9. };
10. t1.start();
11. }}
Output: this is n() method
this is m() method

Input and Output in Java


Input and Output (I/O) is used to process the input and produce the output based on the input. Java
uses the concept of stream to make I/O operations fast. java.io package contains all the classes required
for input and output operations.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it's
like a stream of water that continues to flow.
Three streams are created for us automatically:
 1) System.out: standard output stream
 2) System.in: standard input stream
 3) System.err: standard error

Do You Know ?
 How to write a common data to multiple files using single stream only ?
 How can we access multiple files by single stream ?
 How can we improve the performance of Input and Output operation ?
 How many ways can we read data from the keyboard?
 What is console class ?

Jai Ma Saraswati

 How to compress and uncompress the data of a file?

OutputStream
Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral
device or socket.

InputStream
Java application uses an input stream to read data from a source, it may be a file,an array,peripheral
device or socket.

Jai Ma Saraswati

OutputStream class
OutputStream class ia an abstract class.It is the superclass of all classes representing an output stream
of bytes. An output stream accepts output bytes and sends them to some sink.
Commonly used methods of OutputStream class
Method Description

1) public void write(int)throws is used to write a byte to the current output stream.
IOException:

2) public void write(byte[])throws is used to write an array of byte to the current output
IOException: stream.

3) public void flush()throws IOException: flushes the current output stream.

4) public void close()throws IOException: is used to close the current output stream.

InputStream class
InputStream class ia an abstract class.It is the superclass of all classes representing an input stream of
bytes.
Commonly used methods of InputStream class
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream.It returns
IOException: -1 at the end of file.

2) public int available()throws returns an estimate of the number of bytes that can be
IOException: read from the current input stream.

Jai Ma Saraswati

3) public void close()throws is used to close the current input stream.


IOException:

FileInputStream and FileOutputStream (File Handling):


FileInputStream and FileOutputStream classes are used to read and write data in file. In another words,
they are used for file handling in java.

FileOutputStream class:
A FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data,
prefer FileWriter.But you can write byte-oriented as well as character-oriented data.
Example of FileOutputStream class:
Simple program of writing data into the file</i></b>
1.
2.
3. import java.io.*;
4. class Test{
5. public static void main(String args[]){
6. try{
7. FileOutputstream fout=new FileOutputStream("abc.txt");
8. String s="Sachin Tendulkar is my favourite player";
9.
10. byte b[]=s.getBytes();
11. fout.write(b);
12.

Jai Ma Saraswati

13. fout.close();
14.
15. System.out.println("success...");
16. }catch(Exception e){system.out.println(e);}
17. }
18. }
Output:success...

FileInputStream class:
A FileInputStream obtains input bytes from a file.It is used for reading streams of raw bytes such as
image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data.For example, to read image etc.
Example of FileInputStream class:
1. //<b><i>Simple program of reading data from the file</i></b>
2.
3. import java.io.*;
4. class SimpleRead{
5. public static void main(String args[]){
6. try{
7. FileInputStream fin=new FileInputStream("abc.txt");
8. int i;
9. while((i=fr.read())!=-1)
10. System.out.println((char)i);
11.
12. fin.close();
13. }catch(Exception e){system.out.println(e);}
14. }
15. }
Output:Sachin is my favourite player.

Jai Ma Saraswati

Example of Reading the data of current java file and writing it into another file
We can read the data of any file using the FileInputStream class whether it is java file, image file, video
file etc. In this example, we are reading the data of C.java file and writing it into another file M.java.
1. import java.io.*;
2.
3. class C{
4. public static void main(String args[])throws Exception{
5.
6. FileInputStream fin=new FileInputStream("C.java");
7. FileOutputStream fout=new FileOutputStream("M.java");
8.
9. int i=0;
10. while((i=fin.read())!=-1){
11. fout.write((byte)i);
12. }
13.
14. fin.close();
15. }
16. }

ByteArrayOutputStream class:
In this stream, the data is written into a byte array. The buffer automatically grows as data is written to it.
Closing a ByteArrayOutputStream has no effect.
Commonly used Constructors of ByteArrayOutputStream class:
1) ByteArrayOutputStream():creates a new byte array output stream with the initial capacity of 32
bytes, though its size increases if necessary.
2) ByteArrayOutputStream(int size):creates a new byte array output stream, with a buffer capacity of
the specified size, in bytes.
Commonly used Methods of ByteArrayOutputStream class:
1) public synchronized void writeTo(OutputStream out) throws IOException: writes the complete

Jai Ma Saraswati

contents of this byte array output stream to the specified output stream.

Example of ByteArrayOutputStream class:


1. //<b><i>Simple program of writing data by ByteArrayOutputStream class</i></b>
2.
3.
4. import java.io.*;
5. class S{
6. public static void main(String args[])throws Exception{
7.
8. FileOutputStream fout1=new FileOutputStream("f1.txt");
9. FileOutputStream fout2=new FileOutputStream("f2.txt");
10.
11. ByteArrayOutputStream bout=new ByteArrayOutputStream();
12. bout.write(239);
13.
14. bout.writeTo(fout1);
15. bout.writeTo(fout2);
16.
17. bout.flush();
18.
19. bout.close();//has no effect
20. System.out.println("success...");
21. }
22. }
Output:success...

SequenceInputStream class:

Jai Ma Saraswati

SequenceInputStream class is used to read data from multipule streams.


Constructors of SequenceInputStream class:
1) SequenceInputStream(InputStream s1, InputStream s2):creates a new input stream by reading the
data of two input stream in order, first s1 and then s2.
2) SequenceInputStream(Enumeration e):creates a new input stream by reading the data of an
enumeration whose type is InputStream.

Simple example of SequenceInputStream class


In this example, we are printing the data of two files f1.txt and f2.txt.
1. //Program of SequenceInputStream that reads data of 2 files
2.
3. import java.io.*;
4. class Simple{
5. public static void main(String args[])throws Exception{
6.
7. FileinputStream fin1=new FileinputStream("f1.txt");
8. FileinputStream fin2=new FileinputStream("f2.txt");
9.
10. SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
11. int i;
12. while((i=sis.read())!=-1)
13. {
14. System.out.println((char)i);
15. }
16. }
17. }

Example of SequenceInputStream class that reads the data from two files and write it into another
In this example, we are writing the data of two files f1.txt and f2.txt into another file named f3.txt.
1. //reading data of 2 files and writing it into one file
2.
3. import java.io.*;
4. class Simple{
5. public static void main(String args[])throws Exception{
6.
7. FileinputStream fin1=new FileinputStream("f1.txt");
8. FileinputStream fin2=new FileinputStream("f2.txt");
9.
10. FileOutputStream fout=new FileOutputStream("f3.txt");
11.
12. SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
13. int i;
14. while((i.sisread())!=-1)

Jai Ma Saraswati

15. {
16. fout.write(i);
17. }
18. sis.close();
19. fout.close();
20. fin.close();
21. fin.close();
22.
23. }
24. }

Example of SequenceInputStream class that reads the data from multiple files using enumeration
If we need to read the data from more than two files, we need to have these information in the
Enumeration object. Enumeration object can be get by calling elements method of the Vector class. Let's
see the simple example where we are reading the data from the 4 files.
1. import java.io.*;
2. import java.util.*;
3.
4. class B{
5. public static void main(String args[])throws IOException{
6.
7. //creating the FileInputStream objects for all the files
8. FileInputStream fin=new FileInputStream("A.java");
9. FileInputStream fin2=new FileInputStream("abc2.txt");
10. FileInputStream fin3=new FileInputStream("abc.txt");
11. FileInputStream fin4=new FileInputStream("B.java");
12.
13. //creating Vector object to all the stream
14. Vector v=new Vector();
15. v.add(fin);
16. v.add(fin2);
17. v.add(fin3);
18. v.add(fin4);
19.
20. //creating enumeration object by calling the elements method
21. Enumeration e=v.elements();
22.
23. //passing the enumeration object in the constructor
24. SequenceInputStream bin=new SequenceInputStream(e);
25. int i=0;
26.
27. while((i=bin.read())!=-1){
28. System.out.print((char)i);
29. }
30.

Jai Ma Saraswati

31. bin.close();
32. fin.close();
33. fin2.close();
34. }
35. }

BufferedOutputStream class:
BufferedOutputStream used an internal buffer. It adds more efficiency than to write data directly into a
stream. So, it makes the performance fast.

Example of BufferedOutputStream class:


In this example, we are writing the textual information in the BufferedOutputStream object which is
connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into
another. It is required if you have connected the one stream with another.
1. import java.io.*;
2. class Test{
3. public static void main(String args[])throws Exception{
4.
5. FileOutputStream fout=new FileOutputStream("f1.txt");
6. BufferedOutputStream bout=new BufferedOutputStream(fout);
7.
8. String s="Sachin is my favourite player";
9. byte b[]=s.getBytes();
10. bout.write(b);
11.
12. bout.flush();
13. bout.close();
14. System.out.println("success");
15. }
16. }
Output:success...

Example of BufferedInputStream class:


1. //<b><i>Simple program of reading data from the file using buffer</i></b>
2.
3. import java.io.*;
4. class SimpleRead{
5. public static void main(String args[]){
6. try{
7.
8. FileInputStream fin=new FileInputStream("f1.txt");
9. BufferedInputStream bin=new BufferedInputStream(fin);
10. int i;
11. while((i=bin.read())!=-1)
12. System.out.println((char)i);

Jai Ma Saraswati

13.
14. fin.close();
15. }catch(Exception e){system.out.println(e);}
16. }
17. }
Output:Sachin is my favourite player

FileWriter class:
FileWriter class is used to write character-oriented data to the file. Sun Microsystem has suggested not
to use the FileInputStream and FileOutputStream classes if you have to read and write the textual
information.
Example of FileWriter class:
In this example, we are writing the data in the file abc.txt.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[]){
4. try{
5. FileWriter fw=new FileWriter("abc.txt");
6. fw.write("my name is sachin");
7. fw.flush();
8.
9. fw.close();
10. }catch(Exception e){System.out.println(e);}
11. System.out.println("success");
12. }
13. }
Output:success...

FileReader class:
FileReader class is used to read data from the file.
Example of FileReader class:
In this example, we are reading the data from the file abc.txt file.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. FileReader fr=new FileReader("abc.txt");
6. int i;
7. while((i=fr.read())!=-1)
8. System.out.println((char)i);
9.
10. fr.close();
11. }
12. }
Output:my name is sachin

Jai Ma Saraswati

CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class implements the
Appendable interface. Its buffer automatically grows when data is written in this stream. Calling the
close() method on this object has no effect.
Example of CharArrayWriter class:
In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and d.txt.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. CharArrayWriter out=new CharArrayWriter();
6. out.write("my name is");
7.
8. FileWriter f1=new FileWriter("a.txt");
9. FileWriter f2=new FileWriter("b.txt");
10. FileWriter f3=new FileWriter("c.txt");
11. FileWriter f4=new FileWriter("d.txt");
12.
13. out.writeTo(f1);
14. out.writeTo(f2);
15. out.writeTo(f3);
16. out.writeTo(f4);
17.
18.
19. f1.close();
20. f2.close();
21. f3.close();
22. f4.close();
23. }
24. }

Reading data from keyboard:


There are many ways to read data from the keyboard. For example:
 InputStreamReader
 Console
 Scanner
 DataInputStream etc.
InputStreamReader class:
InputStreamReader class can be used to read data from keyboard.It performs two tasks:
 connects to input stream of keyboard
 converts the byte-oriented stream into character-oriented stream
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.

Jai Ma Saraswati

Example of reading data from keyboard by InputStreamReader and BufferdReader class:


In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for
reading the line by line data from the keyboard.
1. //<b><i>Program of reading data</i></b>
2.
3. import java.io.*;
4. class G5{
5. public static void main(String args[])throws Exception{
6.
7. InputStreamReader r=new InputStreamReader(System.in);
8. BufferedReader br=new BufferedReader(r);
9.
10. System.out.println("Enter ur name");
11. String name=br.readLine();
12. System.out.println("Welcome "+name);
13. }
14. }
Output:Enter ur name
Amit
Welcome Amit

Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until
the user writes stop
In this example, we are reading and printing the data until the user prints stop.
1. import java.io.*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7.

Jai Ma Saraswati

8. String name="";
9.
10. while(name.equals("stop")){
11. System.out.println("Enter data: ");
12. name=br.readLine();
13. System.out.println("data is: "+name);
14. }
15.
16. br.close();
17. r.close();
18. }
19. }
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop

Console class (I/O)


The Console class can be used to get input from the keyboard.

How to get the object of Console class?


System class provides a static method named console() that returns the unique instance of Console
class.
Syntax:
1. public static Console console(){}

Commonly used methods of Console class:


1) public String readLine(): is used to read a single line of text from the console.
2) public String readLine(String fmt,Object... args): it provides a formatted prompt then reads the
single line of text from the console.
3) public char[] readPassword(): is used to read password that is not being displayed on the console.
4) public char[] readPassword(String fmt,Object... args): it provides a formatted prompt then reads
the password that is not being displayed on the console.
Example of Console class that reads name of user:
1. import java.io.*;
2. class A{
3. public static void main(String args[]){
4.
5. Console c=System.console();
6.

Jai Ma Saraswati

7. System.out.println("Enter ur name");
8. String n=c.readLine();
9. System.out.println("Welcome "+n);
10.
11. }
12. }

Example of Console class that reads password:


1. import java.io.*;
2. class A{
3. public static void main(String args[]){
4.
5. Console c=System.console();
6.
7. System.out.println("Enter password");
8. char[] ch=c.readPassword();
9.
10. System.out.println("Password is");
11. for(char ch2:ch)
12. System.out.print(ch2);
13.
14. }
15. }

java.util.Scanner class:
There are various ways to read input from the keyboad, the java.util.Scanner class is one of them. The
Scanner class breaks the input into tokens using a delimiter which is whitespace bydefault. It provides
many methods to read and parse various primitive values.
Commonly used methods of Scanner class:
There is a list of commonly used Scanner class methods:
 public String next(): it returns the next token from the scanner.
 public String nextLine(): it moves the scanner position to the next line and returns the value as a
string.
 public byte nextByte(): it scans the next token as a byte.
 public short nextShort(): it scans the next token as a short value.
 public int nextInt(): it scans the next token as an int value.
 public long nextLong(): it scans the next token as a long value.
 public float nextFloat(): it scans the next token as a float value.
 public double nextDouble(): it scans the next token as a double value.
Example of java.util.Scanner class:
Let's see the simple example of the Scanner class which reads the int, string and double value as an
input:
1. import java.util.Scanner;
2. class ScannerTest{
3. public static void main(String args[]){

Jai Ma Saraswati

4.
5. Scanner sc=new Scanner(System.in);
6.
7. System.out.println("Enter your rollno");
8. int rollno=sc.nextInt();
9. System.out.println("Enter your name");
10. String name=sc.next();
11. System.out.println("Enter your fee");
12. double fee=sc.nextDouble();
13.
14. System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
15.
16. }
17. }
download this scanner example
Output:Enter your rollno
111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The PrintStream class
automatically flushes the data so there is no need to call flush() method. Moreover, its methods don't
throw IOException.
Commonly used methods of PrintStream class:
There are many methods in PrintStream class. Let's see commonly used methods of PrintStream class:
 public void print(boolean b): it prints the specified boolean value.
 public void print(char c): it prints the specified char value.
 public void print(char[] c): it prints the specified character array values.
 public void print(int i): it prints the specified int value.
 public void print(long l): it prints the specified long value.
 public void print(float f): it prints the specified float value.
 public void print(double d): it prints the specified double value.
 public void print(String s): it prints the specified string value.
 public void print(Object obj): it prints the specified object value.
 public void println(boolean b): it prints the specified boolean value and terminates the line.
 public void println(char c): it prints the specified char value and terminates the line.
 public void println(char[] c): it prints the specified character array values and terminates the
line.
 public void println(int i): it prints the specified int value and terminates the line.
 public void println(long l): it prints the specified long value and terminates the line.
 public void println(float f): it prints the specified float value and terminates the line.

Jai Ma Saraswati

 public void println(double d): it prints the specified double value and terminates the line.
 public void println(String s): it prints the specified string value and terminates the line./li>
 public void println(Object obj): it prints the specified object value and terminates the line.
 public void println(): it terminates the line only.
 public void printf(Object format, Object... args): it writes the formatted string to the current
stream.
 public void printf(Locale l, Object format, Object... args): it writes the formatted string to the
current stream.
 public void format(Object format, Object... args): it writes the formatted string to the current
stream using specified format.
 public void format(Locale l, Object format, Object... args): it writes the formatted string to the
current stream using specified format.

Example of java.io.PrintStream class:


In this example, we are simply printing integer and string values.
1. import java.io.*;
2. class PrintStreamTest{
3. public static void main(String args[])throws Exception{
4.
5. FileOutputStream fout=new FileOutputStream("mfile.txt");
6. PrintStream pout=new PrintStream(fout);
7. pout.println(1900);
8. pout.println("Hello Java");
9. pout.println("Welcome to Java");
10. pout.close();
11. fout.close();
12.
13. }
14. }

Example of printf() method of java.io.PrintStream class:


Let's see the simple example of printing integer value by format specifier.
1. class PrintStreamTest{
2. public static void main(String args[]){
3. int a=10;
4. System.out.printf("%d",a);//Note, out is the object of PrintStream class
5.
6. }
7. }
Output:10

PipedInputStream and PipedOutputStream classes


The PipedInputStream and PipedOutputStream classes can be used to read and write data
simultaneously. Both streams are connected with each other using the connect() method of the
PipedOutputStream class.

Example of PipedInputStream and PipedOutputStream classes using threads


Here, we have created two threads t1 and t2. The t1 thread writes the data using the PipedOutputStream

Jai Ma Saraswati
object and the t2 thread reads the data from that pipe using the PipedInputStream object. Both the piped
stream object are connected with each other.
1. import java.io.*;
2.
3. class PipedWR{
4. public static void main(String args[])throws Exception{
5.
6. final PipedOutputStream pout=new PipedOutputStream();
7. final PipedInputStream pin=new PipedInputStream();
8.
9. pout.connect(pin);//connecting the streams
10.
11. //creating one thread t1 which writes the data
12. Thread t1=new Thread(){
13. public void run(){
14. for(int i=65;i<=90;i++){
15. try{
16.
17. pout.write(i);

Jai Ma Saraswati

18. Thread.sleep(1000);
19.
20. }catch(Exception e){}
21. }
22. }
23. };
24.
25. //creating another thread t2 which reads the data
26. Thread t2=new Thread(){
27. public void run(){
28. try{
29. for(int i=65;i<=90;i++)
30. System.out.println(pin.read());
31. }catch(Exception e){}
32. }
33. };
34.
35. //starting both threads
36. t1.start();
37. t2.start();
38.
39. }}

Serialization

Serialization is a machanism of writing the state of an object into a byte stream. It is mainly used in
Hibernate, JPA, EJB etc. The reverse operation of the serialization is called deserialization. The String
class and all the wrapper classes implements Serializable interface bydefault.
Advantage of Serialization
It is mainly used to travel object's state on the network.

Jai Ma Saraswati

About Serializable interface


Serializable is a marker interface(have no body). It is just used to "mark" Java classes which support a
certain capability. It must be implemented by the class whose object you want to persist. Let's see the
example given below:
1. import java.io.Serializable;
2.
3. public class Student implements Serializable{
4. int id;
5. String name;
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }

ObjectOutputStream class:
An ObjectOutputStream is used to write primitive data types and Java objects to an OutputStream.Only
objects that support the java.io.Serializable interface can be written to streams.
Commonly used Constructors:
1) public ObjectOutputStream(OutputStream out) throws IOException {}creates an
ObjectOutputStream that writes to the specified OutputStream.
Commonly used Methods:
1) public final void writeObject(Object obj) throws IOException {}write the specified object to the
ObjectOutputStream.
2) public void flush() throws IOException {}flushes the current output stream.

Example of Serialization
In this example, we are going to serialize the object of Student class. The writeObject() method of
ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the
object in the file named f.txt.

Jai Ma Saraswati

1. import java.io.*;
2. class Persist{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi");
5.
6. FileOutputStream fout=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(fout);
8.
9. out.writeObject(s1);
10. out.flush();
11.
12. System.out.println("success");
13. }
14. }
Output:success

Deserilization:
Deserialization is the process of reconstructing the object from the serialized state.It is the reverse
operation of serialization.
ObjectInputStream class:
An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.
Commonly used Constructors:
1) public ObjectInputStream(InputStream in) throws IOException {}creates an ObjectInputStream
that reads from the specified InputStream.

Jai Ma Saraswati

Commonly used Methods:


1) public final Object readObject() throws IOException, ClassNotFoundException{}reads an object
from the input stream.

Example of Deserialization:
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[])throws Exception{
4.
5. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
6. Student s=(Student)in.readObject();
7. System.out.println(s.id+" "+s.name);
8.
9. in.close();
10. }
11. }
Output:211 ravi
-------------------------- of deserialization

Serialization with Inheritance


If a class implements Serilizable then all its subclasses will also be serilizable. Let's see the
example given below:
1. import java.io.Serializable;
2.
3. class Person implements Serializable{
4. int id;
5. String name;
6. Person(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }
1. class Student extends Person{
2. String course;
3. int fee;
4. public Student(int id, String name, String course, int fee) {
5. super(id,name);
6. this.course=course;
7. this.fee=fee;
8. }
9. }
Now you can serialize the Student class object that extends the Person class which is
Serializable.Parent class properties are inherited to subclasses so if parent class is Serializable,
subclass would also be.

Jai Ma Saraswati

Externalizable interface:
The Externalizable interface provides the facility of writing the state of an object into a byte stream in
compress format. It is not a marker interface.
The Externalizable interface provides two methods:
 public void writeExternal(ObjectOutput out) throws IOException
 public void readExternal(ObjectInput in) throws IOException

Serialization with Static datamember


Note: If there is any static data member in a class, it will not be serialized because static is related
to class not to instance.
1. class Employee implements Serializable{
2. int id;
3. String name;
4. static String companyName="IBM";//it won't be serialized
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

Rule: In case of array or collection, all the objects of array or collection must be serializable,if any
object is not serialiizable then serialization will be failed.
The transient keyword
The transient keyword is used in serialization. If you define any data member as transient, it will not be
serialized. Let's take an example, I have declared a class as Student, it has three data members id,
name and age. If you serialize the object, all the values will be serialized but I don't want to serialize one
value, e.g. age then we can declare the age datamember as transient.
Example of transient keyword
In this example, we have created the two classes Student and Persist. One data member of the Student
class is declared as transient, it value will not be serialized. If you deserialize the object, it will return the
default value for transient variable.
1. import java.io.Serializable;
2.
3. public class Student implements Serializable{
4. int id;
5. String name;
6. transient int age;//Now it will not be serialized
7. public Student(int id, String name,int age) {
8. this.id = id;
9. this.name = name;
10. this.age=age;

Jai Ma Saraswati

11. }
12. }
1. import java.io.*;
2. class Persist{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi",22);
5.
6. FileOutputStream f=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(f);
8.
9. out.writeObject(s1);
10. out.flush();
11.
12. System.out.println("success");
13. }
14. }
Output:succss

Jai Ma Saraswati

Java Collection Framework


Collection Framework provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, deletion etc. can be
performed by Java Collection Framework.
Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Collection- interafce
Collections- class
collection- data type
What is Collection?
Collection represents a single unit of objects i.e. a group.
What is framework?
 It provides readymade architecture.
 It represents set of classes and interface.
 It is optional.
That‟s why it is called framework.

Collection framework
Collection framework represents a unified architecture for storing and manipulating group of object. It
has:
1. Interfaces and its implementations i.e. classes
2. Algorithm

 What are the two ways to iterate the elements of a collection ?


 What is the difference between ArrayList and LinkedList classes in collection framework ?
 What is the difference between ArrayList and Vector classes in collection framework ?
 What is the difference between HashSet and HashMap classes in collection framework ?
 What is the difference between HashMap and Hashtable class ?
 What is the difference between Iterator and Enumeration interface in collection framework
?
 How can we sort the elements of an object. What is the difference between Comparable
and Comparator interfaces ?
 What does the hashcode() method ?
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for Collection framework.

Jai Ma Saraswati

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:
No. Method Description

1 public boolean add(Object is used to insert an element in this collection.


element)

2 public boolean addAll(collection is used to insert the specified collection elements in the
c) invoking collection.

3 public boolean remove(Object is used to delete an element from this collection.


element)

4 public boolean is used to delete all the elements of specified collection



Jai Ma Saraswati

removeAll(Collection c) from the invoking collection.

5 public boolean is used to delete all the elements of invoking collection


retainAll(Collection c) except the specified collection.

6 public int size() return the total number of elements in the collection.

7 public void clear() removes the total no of element from the collection.

8 public boolean contains(object is used to search an element.


element)

9 Public Boolean is used to search the specified collection in this collection.


containsAll(Collection c)

10 public Iterator iterator() returns an iterator.

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

12 public boolean isEmpty() checks if collection is empty.

13 public boolean equals(Object matches two collection.


element)

14 public int hashCode() returns the hashcode number for collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
1. public boolean hasNext() it returns true if iterator has more elements.
2. public object next() it returns the element and moves the cursor pointer to the next element.
3. public void remove() it removes the last elements returned by the iterator. It is rarely used.
ArrayList class:
 uses a dynamic array for storing the elements.It extends AbstractList class and implements List
interface.
 can contain duplicate elements.
 maintains insertion order.
 not synchronized.
 random access because array works at the index basis.
 manipulation slow because a lot of shifting needs to be occured.

Jai Ma Saraswati

Hierarchy of ArrayList class:

Example of ArrayList:
1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:Ravi
Vijay
Ravi
Ajay

Jai Ma Saraswati

Sorting of an ArrayList:
Sorting any ArrayList is pretty simple. Using Collections.sort( ) method we can sort the ArrayList.
Collections class having all the static methods, we can use those methods directly along with the class
name. These methods return the object as type Collection.

Collections.sort(list);
Two ways to iterate the elements of collection:
1. By Iterator interface.
2. By for-each loop.
Iterating the elements of Collection by for-each loop:
1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. for(Object obj:al)
12. System.out.println(obj);
13. }
14. }
Output:Ravi
Vijay
Ravi
Ajay

Storing user-defined class objects:


1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }

1. import java.util.*;

Jai Ma Saraswati

2. class Simple{
3. public static void main(String args[]){
4.
5. Student s1=new Student(101,"Ank",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8.
9. ArrayList al=new ArrayList();
10. al.add(s1);
11. al.add(s2);
12. al.add(s3);
13.
14. Iterator itr=al.iterator();
15. while(itr.hasNext()){
16. Student st=(Student)itr.next();
17. System.out.println(st.rollno+" "+st.name+" "+st.age);
18. }
19. }
20. }
Output:101 Ank 23
102 Ravi 21
103 Hanumat 25

Example of addAll(Collection c) method:


1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList al2=new ArrayList();
11. al2.add("Ank");
12. al2.add("Hanumat");
13.
14. al.addAll(al2);
15.
16. Iterator itr=al.iterator();
17. while(itr.hasNext()){
18. System.out.println(itr.next());
19. }
20. }
21. }
Output:Ravi

Jai Ma Saraswati

Vijay
Ajay Ank
Hanumat

Example of removeAll() method:


1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList al2=new ArrayList();
11. al2.add("Ravi");
12. al2.add("Hanumat");
13.
14. al.removeAll(al2);
15.
16. System.out.println("iterating the elements after removing the elements of al2...");
17. Iterator itr=al.iterator();
18. while(itr.hasNext()){
19. System.out.println(itr.next());
20. }
21.
22. }
23. }
Output:iterating the elements after removing the elements of al2...
Vijay
Ajay

Example of retainAll() method:


1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList al2=new ArrayList();

Jai Ma Saraswati

11. al2.add("Ravi");
12. al2.add("Hanumat");
13.
14. al.retainAll(al2);
15.
16. System.out.println("iterating the elements after retaining the elements of al2...");
17. Iterator itr=al.iterator();
18. while(itr.hasNext()){
19. System.out.println(itr.next());
20. }
21. }
22. }
Output:iterating the elements after retaining the elements of al2...
Ravi

LinkedList class:
 uses doubly linked list to store the elements. It extends the AbstractList class and implements List
and Deque interfaces.
 can contain duplicate elements.
 maintains insertion order.
 not synchronized.
 No random access.
 manipulation fast because no shifting needs to be occured.
 can be used as list, stack or queue.

Example of LinkedList:
1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. LinkedList al=new LinkedList();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }

Jai Ma Saraswati

15. }
16. }
Output:Ravi
Vijay
Ravi
Ajay

Singly LinkedList Implementation:

public class SinglyLinkedList<T> {


private Node<T> head;
private Node<T> tail;
private Node<T> temp;
private int size;

public SinglyLinkedList() {
head = null;
tail = null;
size = 0;
}

public void addLast(T elem) {


if(head == null){
head = new Node<T>();
head.element = elem;
tail = head;
size++;
} else {
temp = new Node<T>();
temp.element = elem;
tail.next = temp;
temp.prev = tail;
tail = temp;
size++;
}

}
void print(){ temp =
head; while(temp
!= null){
System.out.println(temp.element);

Jai Ma Saraswati

temp = temp.next;
}
}
public static void main(String[] args) {
SinglyLinkedList<Integer> list = new SinglyLinkedList<>();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addLast(4);
list.addLast(5);
list.addLast(6);
list.print();

}
}
public class Node<T>{
Node<T> prev;
Node<T> next;
T element;
public Node() {
}
}

List Interface:
List Interface is the subinterface of Collection.It contains methods to insert and delete elements on index
basis.It is a factory of ListIterator interface.
Commonly used mehtods of List Interface:
1. public void add(int index,Object element);
2. public boolean addAll(int index,Collection c);
3. public object get(int Index position);
4. public object set(int index,Object element);
5. public object remove(int index);
6. public ListIterator listIterator();
7. public ListIterator listIterator(int i);

ListIterator Interface:
ListIterator Interface is used to traverse the element in backward and forward direction.
Commonly used mehtods of ListIterator Interface:
1. public boolean hasNext();
2. public Object next();
3. public boolean hasPrevious();
4. public Object previous();
5. public void remove()
6. public int nextIndex()
7. public int previousIndex()

Jai Ma Saraswati

Example of ListIterator Interface:


1. import java.util.*;
2. class Simple5{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add("Amit");
7. al.add("Vijay");
8. al.add("Kumar");
9. al.add(1,"Sachin");
10.
11. System.out.println("element at 2nd position: "+al.get(2));
12.
13. ListIterator itr=al.listIterator();
14.
15. System.out.println("traversing elements in forward direction...");
16. while(itr.hasNext()){
17. System.out.println(itr.next());
18. }
19.
20.
21. System.out.println("traversing elements in backward direction...");
22. while(itr.hasPrevious()){
23. System.out.println(itr.previous());
24. }
25. }
26. }
Output:element at 2nd position: Vijay
traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit
Difference between List and Set:
List can contain duplicate elements whereas Set contains unique elements only.

HashSet class:
 uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
 contains unique elements only.

Jai Ma Saraswati

Hierarchy of HashSet class:

Example of HashSet class:


1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. HashSet al=new HashSet();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:Ajay
Vijay
Ravi

Jai Ma Saraswati

LinkedHashSet class:
 contains unique elements only like HashSet. It extends HashSet class and implements Set
interface.
 maintains insertion order.
Hierarchy of LinkedHashSet class:

Example of LinkedHashSet class:


1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. LinkedHashSet al=new LinkedHashSet();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){

Jai Ma Saraswati

13. System.out.println(itr.next());
14. }
15. }
16. }
Output:>Ravi
Vijay
Ajay

TreeSet class:
 contains unique elements only like HashSet. The TreeSet class implements NavigableSet
interface that extends the SortedSet interface.
 maintains ascending order.
Hierarchy of TreeSet class:

Example of TreeSet class:


1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. TreeSet al=new TreeSet();
6. al.add("Ravi");

Jai Ma Saraswati

7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:Ajay
Ravi
Vijay

Queue Interface:
The Queue interface basically orders the element in FIFO(First In First Out)manner.
Methods of Queue Interface :
1. public boolean add(object);
2. public boolean offer(object);
3. public remove();
4. public poll();
5. public element();
6. public peek();

PriorityQueue class:
The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO
manner.
Example of PriorityQueue:
1. import java.util.*;
2. class Simple8{
3. public static void main(String args[]){
4.
5. PriorityQueue queue=new PriorityQueue();
6. queue.add("Amit");
7. queue.add("Vijay");
8. queue.add("Karan");
9. queue.add("Jai");
10. queue.add("Rahul");
11.
12. System.out.println("head:"+queue.element());
13. System.out.println("head:"+queue.peek());
14.
15. System.out.println("iterating the queue elements:");
16. Iterator itr=queue.iterator();

Jai Ma Saraswati

17. while(itr.hasNext()){
18. System.out.println(itr.next());
19. }
20.
21. queue.remove();
22. queue.poll();
23.
24. System.out.println("after removing two elements:");
25. Iterator itr2=queue.iterator();
26. while(itr2.hasNext()){
27. System.out.println(itr2.next());
28. }
29.
30. }
31. }
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay

Conversion
List to Set (or) ArrayList to HashSet ?
YES;( To eleminate duplicate values and null values in the list.)
We can convert from List to Set.Both are under the same Superclass Collection Interface. So there are
more chances to convert.
Actually ArrayList follows the insertion order of elements. When you tried to convert from
ArrayList to HashSet it won't preserve the previous order, it may change according to the properties of
HashSet. Set won't maintain the order of elements.
Here we are passing the reference of the List to HashSet constructor at the creation of set object.

Set<Object> set = new HashSet<Object>(list);


Set to List ?
Yes.we can convert a Set into List.The List and Set both are interfaces having superclass of
Collection interface.
Here we are passing the reference of the Set to ArrayList constructor at the creation of List object

Jai Ma Saraswati

List<String> list = new ArrayList<String>(set);

How to synchronized List , Set and Map?


synchronizedList(List<T> list)
synchronizedSet(Set<T> s)
synchronizedMap(Map<K,V> m)

Map Interface
A map contains values based on the key i.e. key and value pair.Each pair is known as an entry.Map
contains only unique elements.
Commonly used methods of Map interface:
1. public Object put(object key,Object value): is used to insert an entry in this map.
2. public void putAll(Map map):is used to insert the specifed map in this map.
3. public Object remove(object key):is used to delete an entry for the specified key.
4. public Object get(Object key):is used to return the value for the specified key.
5. public boolean containsKey(Object key):is used to search the specified key from this map.
6. public boolean containsValue(Object value):is used to search the specified value from this
map.
7. public Set keySet():returns the Set view containing all the keys.
8. public Set entrySet():returns the Set view containing all the keys and values.

Entry
Entry is the subinterface of Map.So we will access it by Map.Entry name.It provides methods to get key
and value.
Methods of Entry interface:
1. public Object getKey(): is used to obtain key.
2. public Object getValue():is used to obtain value.

HashMap class:
 A HashMap contains values based on the key. It implements the Map interface and extends
AbstractMap class.
 It contains only unique elements.
 It may have one null key and multiple null values.
 It maintains no order.
Hierarchy of HashMap class:

Jai Ma Saraswati

Example of HashMap class:


1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. HashMap hm=new HashMap();
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. Set set=hm.entrySet();
12. Iterator itr=set.iterator();
13.
14. while(itr.hasNext()){
15. Map.Entry m=(Map.Entry)itr.next();
16. System.out.println(m.getKey()+" "+m.getValue());
17. }
18. }
19. }
Output:102 Rahul
100 Amit
101 Vijay

What is difference between HashSet and HashMap?


HashSet contains only values whereas HashMap contains entry(key and value).

LinkedHashMap class:
 A LinkedHashMap contains values based on the key. It implements the Map interface and extends
HashMap class.
 It contains only unique elements.
 It may have one null key and multiple null values.

Jai Ma Saraswati

 It is same as HashMap instead maintains insertion order.


Hierarchy of LinkedHashMap class:

Example of LinkedHashMap class:


1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. LinkedHashMap hm=new LinkedHashMap();
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. Set set=hm.entrySet();
12. Iterator itr=set.iterator();
13.
14. while(itr.hasNext()){
15. Map.Entry m=(Map.Entry)itr.next();
16. System.out.println(m.getKey()+" "+m.getValue());
17. }
18. }
19. }
Output:100 Amit
101 Vijay
103 Rahul

TreeMap class
 A TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class.
 It contains only unique elements.
 It cannot have null key but can have multiple null values.
 It is same as HashMap instead maintains ascending order.

Jai Ma Saraswati

Hierarchy of TreeMap class:

Example of TreeMap class:


1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. TreeMap hm=new TreeMap();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. Set set=hm.entrySet();
13. Iterator itr=set.iterator();
14.
15. while(itr.hasNext()){
16. Map.Entry m=(Map.Entry)itr.next();
17. System.out.println(m.getKey()+" "+m.getValue());
18. }
19. }
20. }
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul

Jai Ma Saraswati

What is difference between HashMap and TreeMap?


1) HashMap can contain one null key. TreeMap connot contain any null key.
2) HashMap maintains no order. TreeMap maintains ascending order.

Legacy collection framework:


When SUN Micro Systems has developed java, collection framework was known as data structures.
Data structures in java were unable to meet industry requirements at that time. Hence data structures of
java was reengineered and they have added „n‟ number of classes and interfaces and in later stages the
data structures of java is known as new collection framework we have one interface and classes.
Interface:
We have only one interface, namely java.util.Enumeration. This interface is used for extracting the data
from legacy collection framework classes.
Classes:
As a part of legacy collection framework we have the following essential classes: Vector, Stack,
Dictionary, Hashtable and properties. Here, Vector and Stack belongs to one dimensional classes
whereas Dictionary, Hashtable and Properties belongs to two dimensional classes.
What is the difference between normal collection framework and legacy collection framework?
Answer: All the classes in the normal collection framework are by default belongs to nonsynchronized
classes whereas all classes in legacy collection framework are by default belongs to synchronized
classes.
Vector:
Its functionality is exactly similar to ArrayList but Vector class belongs to synchronized
whereas ArrayList belongs to non-synchronized class.
Creating a Vector is nothing but creating an object of java.util.Vector class.
Vector API:
Constructors:
1. Vector (); _1
2. Vector (int size); _2
Instance methods:
1. public int size ();_3
2. public void addItem (Object obj); [old] _4
3. public void addElement (Object obj); [new] _5
4. public void addItem (int pos, Object obj); _6
5. public void addElement (int pos, Object obj); _7
6. public Object getItem (int pos); _8
7. public Object remove (int pos); _9
8. public void remove (Object obj ); _10
9. public void removeAll ();_11
10. public Enumeration elements ();_12
The methods 4,5,6 and 7 are used for adding an object to the vector either at end or at specified position.
Method-12 is used for extracting the data from vector object.
Enumeration en=v.elements ();
While (en.hasMoreElements ())
{
Object obj=en.nextElement ();

Jai Ma Saraswati

System.out.println (obj);
}
Example:
1. import java.util.*;
2. class vector
3. {
4. public static void main (String [] args)
5. {
6. Vector v=new Vector ();
7. v.addElement (new Integer (10));
8. v.addElement (new Float (100.37f));
9. v.addElement (new Boolean (true));
10. v.addElement ("K.V.R");
11. System.out.println ("SIZE = "+v.size ());
12. System.out.println ("CONTENTS = "+v);
13. Enumeration e
14. while (en.hasMoreElements ())
15. {
16. Object val=en.nextElement ();
17. System.out.println (val);
18. }
19. }
20. }

Stack:
Stack is the sub-class of Vector class. The basic working principal of Stack is Last In First Out.
Stack API:
Constructors:
Stack ();
Stack (int size);
Instance methods:
1. public boolean empty (); _1
2. public void push (Object);_2
3. public Object pop (); _3
4. public Object peek (); _4
5. public int search (Object); _5
Method-1 returns true when the Stack does not contain any elements otherwise false.
Method-2 is used for inserting an object into the Stack.
Method-3 is used to remove top most elements permanently.
Method-4 is used to retrieve top most elements without removing.
Method-5 returns relative position of the element, if it found otherwise returns -1.

Example:
1. import java.util.*;
2. class stack
3. {

Jai Ma Saraswati

4. public static void main (String [] args)


5. {
6. Stack st=new Stack ();
7. System.out.println ("IS STACK EMPTY ? "+st.empty ());
8. System.out.println (st);
9. st.push (new Integer (10));
10. st.push (new Integer (20));
11. st.push (new Integer (30));
12. st.push (new Integer (40));
13. System.out.println (st);
14. System.out.println ("TOP MOST ELEMENT = "+st.peek ());
15. System.out.println (st);
16. System.out.println ("DELETED ELEMENT = "+st.pop ());
17. System.out.println ("MODIFIED STACK = "+st.peek ());
18. System.out.println ("IS 10 FOUND ? "+st.search (new Integer (10)));
19. Enumeration en=st.elements ();
20. while (en.hasMoreElements ())
21. {
22. Object obj=en.nextElement ();
23. System.out.println (obj);
24. }
25. }
26. };

Dictionary:
Dictionary is an abstract class, whose object allows to retrieve to store the data in the form of (key, value)
pair. An object of Dictionary never allows duplicate values as key objects and null values.
Or
Dictionary is an abstract class which behaves as Map. Dictionary is legacy class. It implements
Enumeration. Dictionary has two methods Dictionary.keys() and Dictionary.elements() that can be
iterated by Enumeration. Dictionary is legacy class. We should use Map instead of Dictionary. Find
example how to use Dictionary.
Example of Dictionary:
1. package com.util;
2. import java.util.Dictionary;
3. import java.util.Enumeration;
4. import java.util.Hashtable;
5. public class DictionaryDemo {
6. public static void main(String[] args) {
7. Dictionary<Integer, String> d = new Hashtable<Integer, String>();
8. d.put(1,"Passion");
9. d.put(2,"Motion");
10. d.put(3,"Caution");

Jai Ma Saraswati

11. Enumeration<Integer> key = d.keys();


12. while(key.hasMoreElements()){
13. System.out.println(key.nextElement());
14. }
15. Enumeration<String> element = d.elements();
16. while(element.hasMoreElements()){
17. System.out.println(element.nextElement());
18. }
19. }
20. }

Hashtable:
A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling
the hashcode() method.A Hashtable contains values based on the key. It implements the Map interface
and extends Dictionary class.
 It contains only unique elements.
 It may have not have any null key or value.
 It is synchronized.
Example of Hashtable:
1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. Hashtable hm=new Hashtable();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. Set set=hm.entrySet();
13. Iterator itr=set.iterator();
14.
15. while(itr.hasNext()){
16. Map.Entry m=(Map.Entry)itr.next();
17. System.out.println(m.getKey()+" "+m.getValue());
18. }
19. }
20. }
Output:103 Rahul
102 Ravi
101 Vijay
100 Amit

Jai Ma Saraswati

Properties class in Java


The properties object contains key and value pair both as a string. It is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties class provides methods to
get data from properties file and store data into properties file. Moreover, it can be used to get properties
of system.
Advantage of properties file
Easy Maintenance: If any information is changed from the properties file, you don't need to recompile
the java class. It is mainly used to contain variable information i.e. to be changed.
Methods of Properties class
The commonly used methods of Properties class are given below.
Method Description

public void load(Reader r) loads data from the Reader object.

public void load(InputStream is) loads data from the InputStream object

public String getProperty(String key) returns value based on the key.

public void setProperty(String key,String sets the property in the properties object.
value)

public void store(Writer w, String comment) writers the properties in the writer object.

public void store(OutputStream os, String writes the properties in the OutputStream object.
comment)

storeToXML(OutputStream os, String writers the properties in the writer object for
comment) generating xml document.

public void storeToXML(Writer w, String writers the properties in the writer object for
comment, String encoding) generating xml document with specified encoding.

Example of Properties class to get information from properties file


To get information from the properties file, create the properties file first.
db.properties
1. user=system
2. password=oracle
Now, lets create the java class to read the data from the properties file.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{

Jai Ma Saraswati

5. FileReader reader=new FileReader("db.properties");


6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }
Output:system
oracle
Now if you change the value of the properties file, you don't need to compile the java class again. That
means no maintenance problem.

Example of Properties class to get all the system properties


By System.getProperties() method we can get all the properties of system. Let's create the class that
gets information from the system properties.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=System.getProperties();
7. Set set=p.entrySet();
8.
9. Iterator itr=set.iterator();
10. while(itr.hasNext()){
11. Map.Entry entry=(Map.Entry)itr.next();
12. System.out.println(entry.getKey()+" = "+entry.getValue());
13. }
14.
15. }
16. }
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =

Jai Ma Saraswati

sun.java.launcher = SUN_STANDARD
...........

Example of Properties class to create properties file


Now lets write the code to create the properties file.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=new Properties();
7. p.setProperty("name","Ank Jaiswal");
8. p.setProperty("email","ankjaiswal@hftech.com");
9.
10. p.store(new FileWriter("info.properties"),"Hftech Properties Example");
11.
12. }
13. }
Let's see the generated properties file.
info.properties
1. #Hftech Properties Example
2. #Thu Oct 03 22:35:53 IST 2013
3. email=ankjaiswal@hftech.com
4. name=Ank Jaiswal

What is difference between HashMap and Hashtable?


1) HashMap is not synchronized. Hashtable is synchronized.
2) HashMap can contain one null key and multiple Hashtable cannot contain any null key nor
null values. value.

How to Iterate Map using Generics?


Map is an interface.We can iterate the implemented classes from map
likeTreeMap,HashMap,LinkedHashMap.

Maps do not provide an iterator() method as do Lists and Sets. A Set of either keys (keySet()) or key-
value 'Map.Entry' elements (entrySet()) can be obtained from the Map, and one can iterate over that.

Jai Ma Saraswati

Create an object for HashMap and insert the objects in that.

1 Map<Integer, String> map = new HashMap();


2 map.put(100, "Murali");
3 map.put(200, "khaleel");
4 map.put(300, "Bhaskar");

With that object if you want to retrieve only keys from HashMap then we should convert it into Set and
while iteration by using getKey() method.

?
1 Set<integer> set = map.keySet();
2 Iterator<integer> it = set.iterator();
3 while(it.hasNext()){
4 System.out.println(it.next());
5 }

To retreive the values from the HashMap we can't use the Set why because by using map.values()
method returns Collection of objects, so we should convert it into Collection. So take the Collection object
in String object.

?
1 Collection<string> col = map.values();
2 Iterator<string> it1 = col.iterator();
3 while(it1.hasNext()){
4 System.out.println(it1.next());
5 }

Here we are using Generics to mention their type of keys and values in HashMap.Here we are iterating

Jai Ma Saraswati

keys and values in HashMap.For that better to take map.entrySet() to iterate the Map keys and values.

In that we can retrieve the keys in Iteration block with getKey() and values as getValue().

1 Iterator<Map.Entry<Integer, String>> entries = map.entrySet().iterator();


2
3 while(entries.hasNext()){
4 Map.Entry<Integer, String> entry = entries.next();
5 System.out.print(entry.getKey()+" , ");
6 System.out.print(entry.getValue()+"n");
}

Sorting Of Collection
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of collection.If collection elements are
of Set type, we can use TreeSet.But We cannot sort the elements of List.Collections class provides
methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List.List elements must be of Comparable
type.
Note: String class and Wrapper classes implements the Comparable interface.So if you store the
objects of string or wrapper classes, it will be Comparable.
Example of Sorting the elements of List that contains string objects
1. import java.util.*;
2. class Simple12{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add("Viru");
7. al.add("Saurav");
8. al.add("Mukesh");
9. al.add("Tahir");
10.
11. Collections.sort(al);
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){

Jai Ma Saraswati

14. System.out.println(itr.next());
15. }
16. }
17. }
Output:Mukesh
Saurav
Tahir
Viru

Example of Sorting the elements of List that contains Wrapper class objects
1. import java.util.*;
2. class Simple12{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add(Integer.valueOf(201));
7. al.add(Integer.valueOf(101));
8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)
9.
10. Collections.sort(al);
11.
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Output:101
201
230

Comparable interface
Comparable interface is used to order the objects of user-defined class.This interface is found in
java.lang package and contains only one method named compareTo(Object).It provide only single
sorting sequence i.e. you can sort the elements on based on single data member only.For instance it
may be either rollno,name,age or anything else.
Syntax:
public int compareTo(Object obj): is used to compare the current object with the specified object.

We can sort the elements of:


1. String objects
2. Wrapper class objects
3. User-defined class objects

Jai Ma Saraswati

Collections class provides static methods for sorting the elements of collection.If collection elements are
of Set type, we can use TreeSet.But We cannot sort the elements of List.Collections class provides
methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List.List elements must be of Comparable
type.
Note: String class and Wrapper classes implements the Comparable interface.So if you store the
objects of string or wrapper classes, it will be Comparable.

Example of Sorting the elements of List that contains user-defined class objects on age basis
Student.java
1. class Student implements Comparable{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10.
11. public int compareTo(Object obj){
12. Student st=(Student)obj;
13. if(age==st.age)
14. return 0;
15. else if(age>st.age)
16. return 1;
17. else
18. return -1;
19. }
20.
21. }
Simple.java
1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.

Jai Ma Saraswati

12. Collections.sort(al);
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. Student st=(Student)itr.next();
16. System.out.println(st.rollno+""+st.name+""+st.age);
17. }
18. }
19. }
Output:105 Jai 21
101 Vijay 23
106 Ajay 27

Comparator interface
Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2)
and equals(Object element).
It provides multiple sorting sequence i.e. you can sort the elements based on any data member. For
instance it may be on rollno, name, age or anything else.
Syntax of compare method
public int compare(Object obj1,Object obj2): compares the first object with second object.

Collections class provides static methods for sorting the elements of collection. If collection elements
are of Set type, we can use TreeSet. But We cannot sort the elements of List. Collections class provides
methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list,Comparator c): is used to sort the elements of List by the given comparator.

Example of sorting the elements of List that contains user-defined class objects on the basis of age and
name
In this example, we have created 4 java classes:
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java
This class contains three fields rollno, name and age and a parameterized constructor.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;

Jai Ma Saraswati

9. }
10. }
AgeComparator.java
This class defines comparison logic based on the age. If age of first object is greater than the second, we
are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first object is less than the
second object, we are returning negative value, it can be any negative value and if age of both objects
are equal, we are returning 0.
1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the compareTo()
method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }
Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.
1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.

Jai Ma Saraswati

12. System.out.println("Sorting by Name...");


13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("sorting by age...");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
27. System.out.println(st.rollno+" "+st.name+" "+st.age);
28. }
29.
30.
31. }
32. }
Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27

Jai Ma Saraswati

JDBC Tutorial
JDBC is a Java API that is used to connect and execute query to the database. JDBC API uses jdbc
drivers to connects to the database.

Why use JDBC?


Before JDBC, ODBC API was used to connect and execute query to the database. But ODBC API uses
ODBC driver that is written in C language which is plateform dependent and unsecured. That is why Sun
Microsystem has defined its own API (JDBC API) that uses JDBC driver written in Java language.

Do You Know ?
 How to connect Java application with Oracle and Mysql database using JDBC?
 What is the difference between Statement and PreparedStatement interface?
 How to print total numbers of tables and views of a database using JDBC ?
 How to store and retrieve images from Oracle database using JDBC?
 How to store and retrieve files from Oracle database using JDBC?
What is API?
API (Application programming interface) is a document that contains description of all the features of a
product or software. It represents classes and interfaces that software programs can follow to
communicate with each other. An API can be created for applications, libraries, operating systems, etc
JDBC Driver
1. JDBC Drivers
1. JDBC-ODBC bridge driver
2. Native-API driver
3. Network Protocol driver
4. Thin driver
JDBC Driver is a software component that enables java application to interact with the database.There

Jai Ma Saraswati

are 4 types of JDBC drivers:


1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin
driver.

Advantages:
 easy to use.
 can be easily connected to any database.
Disadvantages:
 Performance degraded because JDBC method call is converted into the ODBC funcion calls.
 The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.

Jai Ma Saraswati

Advantage:
 performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
 The Native driver needs to be installed on the each client machine.
 The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.

Jai Ma Saraswati

Advantage:
 No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.

Jai Ma Saraswati

Advantage:
 Better performance than all other drivers.
 No software is required at client side or server side.
Disadvantage:
 Drivers depends on the Database.
5 Steps to connect to the database in java
1. 5 Steps to connect to the database in java
1. Register the driver class
2. Create the connection object
3. Create the Statement object
4. Execute the query
5. Close the connection object
There are 5 steps to connect any java application with the database in java using JDBC. They are as
follows:
 Register the driver class
 Creating connection
 Creating statement
 Executing queries
 Closing connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to

Jai Ma Saraswati

dynamically load the driver class.


Syntax of forName() method
1. public static void forName(String className)throws ClassNotFoundException
2.
3. </pre></div>
4.
5. <h3 class="h3ex">Example to register the OracleDriver class</h3>
6. <div class="codeblock"><pre name="code" class="java" >
7.
8. Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException
Example to establish connection with the Oracle database
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
Syntax of createStatement() method
1. public Statement createStatement()throws SQLException
Example to create the statement object
1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. This
method returns the object of ResultSet that can be used to get all the rocords of a table.
Syntax of executeQuery() method
1. public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
1. ResultSet rs=stmt.executeQuery("select * from emp");
2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

Jai Ma Saraswati

5) Close the connection object


By closing connection object statment and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.
Syntax of close() method
1. public void close()throws SQLException
Example to close connection
1. con.close();
Example to connect to the Oracle database
For connecting java application with the oracle database, you need to follow 5 steps to perform database
connectivity. In this example we are using Oracle10g as the database. So we need to know following
informations for the oracle database:
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
isjdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver,
localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port
number and XE is the Oracle service name. You may get all these informations from the tnsnames.ora
file.
3. Username: The default username for the oracle database is system.
4. Password: Password is given by the user at the time of installing the oracle database.

Let's first create a table in oracle database.


1. create table emp(id number(10),name varchar2(40),age number(3));

Example to Connect Java Application with Oracle database


In this example, system is the username and oracle is the password of the Oracle database.
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.

Jai Ma Saraswati

20. //step5 close the connection object


21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
--------------------------
The above example will fetch all the records of emp table.

To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
download the jar file ojdbc14.jar
Two ways to load the jar file:
1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
 temporary
 permament
How to set the temporary classpath:
Firstly, search the ojdbc14.jar file then open comman prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
How to set the permanent classpath:
Go to environment variable then click on new tab. In variable name write classpath and in variable value
paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;
Example to connect to the mysql database
For connecting java application with the mysql database, you need to follow 5 steps to perform database
connectivity.
In this example we are using MySql as the database. So we need to know following informations for the
mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
isjdbc:mysql://localhost:3306/ank where jdbc is the API, mysql is the database, localhost is the
server name on which mysql is running, we may also use IP address, 3306 is the port number and ank is
the database name. We may use any database, in such case, you need to replace the ank with your
database name.
3. Username: The default username for the mysql database is root.
4. Password: Password is given by the user at the time of installing the mysql database. In this
example, we are going to use root as the password.

Jai Ma Saraswati

Let's first create a table in the mysql database, but before creating table, we need to create database
first.
1. create database ank;
2. use ank;
3. create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database


In this example, ank is the database name, root is the username and password.
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:mysql://localhost:3306/ank","root","root");
9.
10. //here ank is database name, root is username and password
11.
12. Statement stmt=con.createStatement();
13.
14. ResultSet rs=stmt.executeQuery("select * from emp");
15.
16. while(rs.next())
17. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
18.
19. con.close();
20.
21. }catch(Exception e){ System.out.println(e);}
22.
23. }
24. }
--------------------------
The above example will fetch all the records of emp table.

To connect java application with the mysql database mysqlconnector.jar file is required to be loaded.
download the jar file mysql-connector.jar
Two ways to load the jar file:
1. paste the mysqlconnector.jar file in jre/lib/ext folder
2. set classpath
1) paste the mysqlconnector.jar file in JRE/lib/ext folder:
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:

Jai Ma Saraswati

 temporary
 permament
How to set the temporary classpath
open comman prompt and write:
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
How to set the permanent classpath
Go to environment variable then click on new tab. In variable name write classpath and in variable value
paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as C:\folder\mysql-
connector-java-5.0.8-bin.jar;.;
DriverManager class:
The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that
are available and handles establishing a connection between a database and the appropriate driver. The
DriverManager class maintains a list of Driver classes that have registered themselves by calling the
method DriverManager.registerDriver().
Commonly used methods of DriverManager class:
is used to register the given driver with
1) public static void registerDriver(Driver driver):
DriverManager.
is used to deregister the given driver (drop the
2) public static void deregisterDriver(Driver driver):
driver from the list) with DriverManager.
is used to establish the connection with the
3) public static Connection getConnection(String url):
specified url.
4) public static Connection getConnection(String is used to establish the connection with the
url,String userName,String password): specified url, username and password.
Connection interface:
A Connection is the session between java application and database. The Connection interface is a
factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used
to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods
for transaction management like commit(),rollback() etc.
By default, connection commits the changes after executing queries.
Commonly used methods of Connection interface:
1) public Statement createStatement(): creates a statement object that can be used to execute SQL
queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a
Statement object that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true.
4) public void commit(): saves the changes made since the previous commit/rollback permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface

Jai Ma Saraswati

The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object
of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop,
insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
Example of Statement interface
Let‟s see the simple example of Statement interface to insert, update and delete the record.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","or
acle");
7. Statement stmt=con.createStatement();
8.
9. //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
10. //int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where id=33");
11. int result=stmt.executeUpdate("delete from emp765 where id=33");
12.
13. System.out.println(result+" records affected");
14. con.close();
15. }}
ResultSet interface
The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to
before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as
well as we can make this object as updatable by:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface
1) public boolean next(): is used to move the cursor to the one row next from the current
position.

Jai Ma Saraswati

2) public boolean previous(): is used to move the cursor to the one row previous from the
current position.

3) public boolean first(): is used to move the cursor to the first row in result set object.

4) public boolean last(): is used to move the cursor to the last row in result set object.

5) public boolean absolute(int is used to move the cursor to the specified row number in the
row): ResultSet object.

6) public boolean relative(int is used to move the cursor to the relative row number in the
row): ResultSet object, it may be positive or negative.

7) public int getInt(int is used to return the data of specified column index of the
columnIndex): current row as int.

8) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.

9) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.

10) public String getString(String is used to return the data of specified column name of the
columnName): current row as String.
Example of Scrollable ResultSet
Let‟s see the simple example of ResultSet interface to retrieve the data of 3rd row.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","or
acle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCU
R_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14. con.close();
15. }}

Jai Ma Saraswati

PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to exeucte parameterized
query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter
methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use PreparedStatement
interface because query is compiled only once.

How to get the instance of PreparedStatement?


The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
1. public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface


The important methods of PreparedStatement interface are given below:
Method Description

public void setInt(int paramIndex, int sets the integer value to the given parameter index.
value)

public void setString(int paramIndex, sets the String value to the given parameter index.
String value)

public void setFloat(int paramIndex, float sets the float value to the given parameter index.
value)

public void setDouble(int paramIndex, sets the double value to the given parameter index.
double value)

public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
1. create table emp(id number(10),name varchar2(50));
Now insert records in this table by the code given below:
1. import java.sql.*;
2. class InsertPrepared{

Jai Ma Saraswati

3. public static void main(String args[]){


4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","or
acle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
--------------------------

Example of PreparedStatement interface that updates the record


1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");
2. stmt.setString(1,"Ank");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
--------------------------

Example of PreparedStatement interface that deletes the record


1. PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
2. stmt.setInt(1,101);
3.
4. int i=stmt.executeUpdate();
5. System.out.println(i+" records deleted");
--------------------------

Example of PreparedStatement interface that retrieve the records of a table


1. PreparedStatement stmt=con.prepareStatement("select * from emp");
2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
--------------------------

Jai Ma Saraswati

Example of PreparedStatement to insert records until user press n


1. import java.sql.*;
2. import java.io.*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","or
acle");
7.
8. PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
9.
10. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
11.
12. do{
13. System.out.println("enter id:");
14. int id=Integer.parseInt(br.readLine());
15. System.out.println("enter name:");
16. String name=br.readLine();
17. System.out.println("enter salary:");
18. float salary=Float.parseFloat(br.readLine());
19.
20. ps.setInt(1,id);
21. ps.setString(2,name);
22. ps.setFloat(3,salary);
23. int i=ps.executeUpdate();
24. System.out.println(i+" records affected");
25.
26. System.out.println("Do you want to continue: y/n");
27. String s=br.readLine();
28. if(s.startsWith("n")){
29. break;
30. }
31. }while(true);
32.
33. con.close();
34. }}
CallableStatement Interface
To call the stored procedures and functions, CallableStatement interface is used.
We can have business logic on the database by the use of stored procedures and functions that will
make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create a function
that receives date as the input and returns age of the employee as the output.

What is the difference between stored procedures and functions.


The differences between stored procedures and functions are given below:

Jai Ma Saraswati

Stored Procedure Function


is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

We can call functions from the procedure. Procedure cannot be called from function.

Procedure supports input and output parameters. Function supports only input parameter.

Exception handling using try/catch block can be Exception handling using try/catch can't be used
used in stored procedures. in user defined functions.

How to get the instance of CallableStatement?


The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is
given below:
1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
The example to get the instance of CallableStatement is given below:
1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
It calls the procedure myprocedure that receives 2 arguments.

Full example to call the stored procedure using JDBC


To call the stored procedure, you need to create it in the database. Here, we are assuming that stored
procedure looks like this.
1. create or replace procedure "INSERTR"
2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user420 values(id,name);
7. end;
8. /
The table structure is given below:
1. create table user420(id number(10), name varchar2(200));
In this example, we are going to call the stored procedure INSERTR that receives id and name as the
parameter and inserts it into the table user420. Note that you need to create the user420 table as well to
run this application.
1. import java.sql.*;
2. public class Proc {
3. public static void main(String[] args) throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");

Jai Ma Saraswati

6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
10. stmt.setInt(1,1011);
11. stmt.setString(2,"Amit");
12. stmt.execute();
13.
14. System.out.println("success");
15. }
16. }
Now check the table in the database, value is inserted in the user420 table.

Example to call the function using JDBC


In this example, we are calling the sum4 function that receives two input and returns the sum of the given
number. Here, we have used the registerOutParameter method of CallableStatement interface, that
registers the output parameter with its corresponding type. It provides information to the
CallableStatement about the type of result being displayed.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE, BLOB,
CLOB etc.
Let's create the simple function in the database first.
1. create or replace function sum4
2. (n1 in number,n2 in number)
3. return number
4. is
5. temp number(8);
6. begin
7. temp :=n1+n2;
8. return temp;
9. end;
10. /
Now, let's write the simple program to call the function.
1. import java.sql.*;
2.
3. public class FuncSum {
4. public static void main(String[] args) throws Exception{
5.
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}");
11. stmt.setInt(2,10);
12. stmt.setInt(3,43);
13. stmt.registerOutParameter(1,Types.INTEGER);
14. stmt.execute();

Jai Ma Saraswati

15.
16. System.out.println(stmt.getInt(1));
17.
18. }
19. }
Output: 53
Transaction Management in JDBC
Transaction represents a single unit of work.
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the event of errors,
power loss etc.

Advantage of Transaction Mangaement


fast performance It makes the performance fast because database is hit at the time of commit.

In JDBC, Connection interface provides methods to manage transaction.


Method Description

void setAutoCommit(boolean It is true bydefault means each transaction is committed


status) bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.



Jai Ma Saraswati

Simple example of transaction management in jdbc using Statement


Let's see the simple example of transaction mangement using Statement.
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","or
acle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
10. stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
11.
12. con.commit();
13. con.close();
14. }}
If you see the table emp400, you will see that 2 records has been added.
Example of transaction management in jdbc using PreparedStatement
Let's see the simple example of transaction mangement using PreparedStatement.
1. import java.sql.*;
2. import java.io.*;
3. class TM{
4. public static void main(String args[]){
5. try{
6.
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","or
acle");
9. con.setAutoCommit(false);
10.
11. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
12.
13. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
14. while(true){
15.
16. System.out.println("enter id");
17. String s1=br.readLine();
18. int id=Integer.parseInt(s1);
19.
20. System.out.println("enter name");
21. String name=br.readLine();
22.
23. System.out.println("enter salary");
24. String s3=br.readLine();
25. int salary=Integer.parseInt(s3);

Jai Ma Saraswati

26.
27. ps.setInt(1,id);
28. ps.setString(2,name);
29. ps.setInt(3,salary);
30. ps.executeUpdate();
31.
32. System.out.println("commit/rollback");
33. String answer=br.readLine();
34. if(answer.equals("commit")){
35. con.commit();
36. }
37. if(answer.equals("rollback")){
38. con.rollback();
39. }
40.
41.
42. System.out.println("Want to add more records y/n");
43. String ans=br.readLine();
44. if(ans.equals("n")){
45. break;
46. }
47.
48. }
49. con.commit();
50. System.out.println("record successfully saved");
51.
52. con.close();//before closing connection commit() is called
53. }catch(Exception e){System.out.println(e);}
54.
55. }}

New Features in Java


There are many new features that have been added in java. There are major enhancement made in
Java5, Java6 and Java7 like auto-boxing, generics, var-args, java annotations, enum, premain
method etc.
Most of the interviewers ask questions from this chapter.

Do You Know ?
1. How to create generic class and generic method in java ?
2. What is annotation and how to create custom annotation ?
3. What is the advantage of assertion and where we should not use it ?
4. What is variable argument and what rules are defined for variable argument ?
5. What is the difference between import and static import ?
6. How autoboxing is applied in method overloading. Which concept beats autoboxing ?

Jai Ma Saraswati

7. What is enum type and how to specify specific value to the enum constants ?
J2SE 4 Features
The important feature of J2SE 4 is assertions. It is used for testing.
 Assertion (Java 4)

J2SE 5 Features
The important features of J2SE 5 are generics and assertions. Others are auto-boxing, enum, var-args,
static import, for-each loop (enhanced for loop etc.
 For-each loop (Java 5)
 Varargs (Java 5)
 Static Import (Java 5)
 Autoboxing and Unboxing (Java 5)
 Enum (Java 5)
 Covariant Return Type (Java 5)
 Annotation (Java 5)
 Generics (Java 5)

JavaSE 6 Features
The important feature of JavaSE 6 is premain method (also known as instrumentation).
 Instrumentation (premain method) (Java 6)

JavaSE 7 Features
The important features of JavaSE 7 are try with resource, catching multiple exceptions etc.
 String in switch statement (Java 7)
 Binary Literals (Java 7)
 The try-with-resources (Java 7)
 Caching Multiple Exceptions by single catch (Java 7)
 Underscores in Numeric Literals (Java 7)
Assertion:
Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Advantage of Assertion:
It provides an effective way to detect and correct programming errors.

Syntax of using Assertion:


There are two ways to use assertion. First way is:
1. assert expression;
and second way is:
1. assert expression1 : expression2;

Simple Example of Assertion in java:


1. import java.util.Scanner;
2.
3. class AssertionExample{

Jai Ma Saraswati

4. public static void main( String args[] ){


5.
6. Scanner scanner = new Scanner( System.in );
7. System.out.print("Enter ur age ");
8.
9. int value = scanner.nextInt();
10. assert value>=18:" Not valid";
11.
12. System.out.println("value is "+value);
13. }
14. }
15.
16.

If you use assertion, It will not run simply because assertion is disabled by default. To enable the
assertion, -ea or -enableassertions switch of java must be used.
Compile it by: javac AssertionExample.java
Run it by: java -ea AssertionExample
Output: Enter ur age 11
Exception in thread "main" java.lang.AssertionError: Not valid

Where not to use Assertion:


There are some situations where assertion should be avoid to use. They are:
1. According to Sun Specification, assertion should not be used to check arguments in the public
methods because it should result in appropriate runtime exception e.g. IllegalArgumentException,
NullPointerException etc.
2. Do not use assertion, if you don't want any error in any situation.
For-each loop (Advanced or Enhanced For loop):
The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The
advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more
readable.
Advantage of for-each loop:
 It makes the code more readable.
 It elimnates the possibility of programming errors.

Syntax of for-each loop:


1. for(data_type variable : array | collection){}

Simple Example of for-each loop for traversing the array elements:


1.
2. class ForEachExample1{
3. public static void main(String args[]){
4. int arr[]={12,13,14,44};

Jai Ma Saraswati

5.
6. for(int i:arr){
7. System.out.println(i);
8. }
9.
10. }
11. }
12.
Output:12
13
14
44

Simple Example of for-each loop for traversing the collection elements:


1. import java.util.*;
2. class ForEachExample2{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("vimal");
6. list.add("ank");
7. list.add("ratan");
8.
9. for(String s:list){
10. System.out.println(s);
11. }
12.
13. }
14. }
15.
Output:vimal
ank
ratan
Variable Argument (Varargs):
The varrags allows the method to accept zero or muliple arguments. Before varargs either we use
overloaded method or take an array as the method parameter but it was not considered good because it
leads to the maintenance problem. If we don't know how many argument we will have to pass in the
method, varargs is the better approach.
Advantage of Varargs:
We don't have to provide overloaded methods so less code.

Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
1. return_type method_name(data_type... variableName){}

Jai Ma Saraswati

Simple Example of Varargs in java:


1.
2. class VarargsExample1{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. }
7.
8. public static void main(String args[]){
9.
10. display();//zero argument
11. display("my","name","is","varargs");//four arguments
12. }
13. }
14.
Output:display method invoked
display method invoked

Another Program of Varargs in java:


1.
2. class VarargsExample{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display();//zero argument
14. display("hello");//one argument
15. display("my","name","is","varargs");//four arguments
16. }
17. }
18.
Output:display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs

Jai Ma Saraswati

Rules for varargs:


While using the varargs, you must follow some rules otherwise program code won't compile. The rules
are as follows:
 There can be only one variable argument in the method.
 Variable argument (varargs) must be the last argument.
Examples of varargs that fails to compile:
1.
2. void method(String... a, int... b){}//Compile time error
3.
4. void method(int... a, String b){}//Compile time error
5.
Example of Varargs that is the last argument in the method:
1.
2. class VarargsExample3{
3.
4. static void display(int num, String... values){
5. System.out.println("number is "+num);
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display(500,"hello");//one argument
14. display(1000,"my","name","is","varargs");//four arguments
15. }
16. }
17.
Output:number is 500
hello
number is 1000
my
name
is
varargs
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static member of a class
directly. There is no need to qualify it by the class name.
Advantage of static import:
 Less coding is required if you have access any static member of a class oftenly.
Disadvantage of static import:

Jai Ma Saraswati

 If you overuse the static import feature, it makes the program unreadable and unmaintainable.

Simple Example of static import


1. import static java.lang.System.*;
2. class StaticImportExample{
3. public static void main(String args[]){
4.
5. out.println("Hello");//Now no need of System.out
6. out.println("Java");
7.
8. }
9. }
10.
Output:Hello
Java

What is the difference between import and static import?


The import allows the java programmer to access classes of a package without package qualification
whereas the static import feature allows to access the static members of a class without the class
qualification. The import provides accessibility to classes and interface whereas static import provides
accessibility to static members of the class.
Autoboxing and Unboxing:
The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and
opposite operation is known as unboxing. This is the new feature of Java5. So java programmer doesn't
need to write the conversion code.
Advantage of Autoboxing and Unboxing:
No need of conversion between primitives and Wrappers manually so less coding is required.

Simple Example of Autoboxing in java:


1.
2. class BoxingExample1{
3. public static void main(String args[]){
4. int a=50;
5. Integer a2=new Integer(a);//Boxing
6.
7. Integer a3=5;//Boxing
8.
9. System.out.println(a2+" "+a3);
10. }
11. }
12.
Output:50 5
--------------------------

Jai Ma Saraswati

Simple Example of Unboxing in java:


The automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing.
Let's see the example of unboxing:
1.
2. class UnboxingExample1{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5. int a=i;
6.
7. System.out.println(a);
8. }
9. }
10.
Output:50

Autoboxing and Unboxing with comparison operators


Autoboxing can be performed with comparison operators. Let's see the example of boxing with
comparison operator:
1.
2. class UnboxingExample1{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5.
6. if(i<100){ //unboxing internally
7. System.out.println(i);
8. }
9. }
10. }
11.
Output:50

Autoboxing and Unboxing with method overloading


In method overloading, boxing and unboxing can be performed. There are some rules for method
overloading with boxing:
 Widening beats boxing
 Widening beats varargs
 Boxing beats varargs
1) Example of Autoboxing where widening beats boxing
If there is possibility of widening and boxing, widening beats boxing.
1.
2. class Boxing1{
3. static void m(int i){System.out.println("int");}
4. static void m(Integer i){System.out.println("Integer");}
5.

Jai Ma Saraswati

6. public static void main(String args[]){


7. short s=30;
8. m(s);
9. }
10. }
11.
Output:int

2) Example of Autoboxing where widening beats varargs


If there is possibility of widening and varargs, widening beats var-args.
1.
2. class Boxing2{
3. static void m(int i, int i2){System.out.println("int int");}
4. static void m(Integer... i){System.out.println("Integer...");}
5.
6. public static void main(String args[]){
7. short s1=30,s2=40;
8. m(s1,s2);
9. }
10. }
11.
Output:int int

3) Example of Autoboxing where boxing beats varargs


Let's see the program where boxing beats variable argument:
1.
2. class Boxing3{
3. static void m(Integer i){System.out.println("Integer");}
4. static void m(Integer... i){System.out.println("Integer...");}
5.
6. public static void main(String args[]){
7. int a=30;
8. m(a);
9. }
10. }
11.
Output:Integer

Method overloading with Widening and Boxing


Widening and Boxing can't be performed as given below:
1.
2. class Boxing3{
3. static void m(Long l){System.out.println("Long");}
4.

Jai Ma Saraswati

5. public static void main(String args[]){


6. int a=30;
7. m(a);
8. }
9. }
10.
Output:Compile Time Error
Enum
An enum is a data type which contains fixed set of constants. It can be used for days of the week
(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions
(NORTH, SOUTH, EAST and WEST) etc. The enum constants are static and final implicitely. It is
available from Java 5. Enums can be thought of as classes that have fixed set of constants.
Points to remember for Enum:
1. enum improves type safety
2. enum can be easily used in switch
3. enum can be traversed
4. enum can have fields, constructors and methods
5. enum may implement many interfaces but cannot extend any class because it internally extends
Enum class

Simple Example of enum in java:


1.
2. class EnumExample1{
3.
4. public enum Season { WINTER, SPRING, SUMMER, FALL }
5.
6. public static void main(String[] args) {
7. for (Season s : Season.values())
8. System.out.println(s);
9.
10. }}
11.
Output:WINTER
SPRING
SUMMER
FALL
What is the purpose of values() method in enum?
The java compiler internally adds the values() method when it creates an enum. The values() method
returns an array containing all the values of the enum.

Internal code generated by the compiler for the above example of enum type
The java compiler internally creates a static and final class that extends the Enum class as shown in the
below example:
1. public static final class EnumExample1$Season extends Enum

Jai Ma Saraswati

2. {
3. private EnumExample1$Season(String s, int i)
4. {
5. super(s, i);
6. }
7.
8. public static EnumExample1$Season[] values()
9. {
10. return (EnumExample1$Season[])$VALUES.clone();
11. }
12.
13. public static EnumExample1$Season valueOf(String s)
14. {
15. return (EnumExample1$Season)Enum.valueOf(EnumExample1$Season, s);
16. }
17.
18. public static final EnumExample1$Season WINTER;
19. public static final EnumExample1$Season SPRING;
20. public static final EnumExample1$Season SUMMER;
21. public static final EnumExample1$Season FALL;
22. private static final EnumExample1$Season $VALUES[];
23.
24. static
25. {
26. WINTER = new EnumExample1$Season("WINTER", 0);
27. SPRING = new EnumExample1$Season("SPRING", 1);
28. SUMMER = new EnumExample1$Season("SUMMER", 2);
29. FALL = new EnumExample1$Season("FALL", 3);
30. $VALUES = (new EnumExample1$Season[] {
31. WINTER, SPRING, SUMMER, FALL
32. });
33. }
34.
35. }

Defining enum:
The enum can be defined within or outside the class because it is similar to a class.
Example of enum that is defined outside the class:
1.
2. enum Season { WINTER, SPRING, SUMMER, FALL }
3.
4. class EnumExample2{
5. public static void main(String[] args) {
6.
7. Season s=Season.WINTER;
8. System.out.println(s);

Jai Ma Saraswati

9.
10. }}
11.
Output:WINTER
Example of enum that is defined within the class:
1. class EnumExample2{
2. enum Season { WINTER, SPRING, SUMMER, FALL; }//semicolon(;) is optional here
3.
4. public static void main(String[] args) {
5. Season s=Season.WINTER;//enum type is required to access WINTER
6. System.out.println(s);
7.
8. }}
9.
Output:WINTER

Initializing specific value to the enum constants:


The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize the
specific value to the enum constants by defining fields and constructors. As specified earlier, Enum can
have fields, constructors and methods.
Example of specifying initial value to the enum constants
1. class EnumExample4{
2. enum Season{
3. WINTER(5), SPRING(10), SUMMER(15), FALL(20);
4.
5. private int value;
6. private Season(int value){
7. this.value=value;
8. }
9. }
10. public static void main(String args[]){
11. for (Season s : Season.values())
12. System.out.println(s+" "+s.value);
13.
14. }}
15.
download this enum example
Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20

Constructor of enum type is private if you don't declare private compiler internally have private
constructor
1. enum Season{

Jai Ma Saraswati

2. WINTER(10),SUMMER(20);
3. private int value;
4. Season(int value){
5. this.value=value;
6. }
7. }
8.
Internal code generated by the compiler for the above example of enum type
1. final class Season extends Enum
2. {
3.
4. public static Season[] values()
5. {
6. return (Season[])$VALUES.clone();
7. }
8.
9. public static Season valueOf(String s)
10. {
11. return (Season)Enum.valueOf(Season, s);
12. }
13.
14. private Season(String s, int i, int j)
15. {
16. super(s, i);
17. value = j;
18. }
19.
20. public static final Season WINTER;
21. public static final Season SUMMER;
22. private int value;
23. private static final Season $VALUES[];
24.
25. static
26. {
27. WINTER = new Season("WINTER", 0, 10);
28. SUMMER = new Season("SUMMER", 1, 20);
29. $VALUES = (new Season[] {
30. WINTER, SUMMER
31. });
32. }
33. }

Can we create the instance of enum by new keyword?


No, because it contains private constructors only.

Jai Ma Saraswati

Can we have abstract method in enum?


Yes, ofcourse! we can have abstract methods and can provide the implementation of these methods.

Applying enum on switch statement


We can apply enum on switch statement as in the given example:
Example of applying enum on switch statement
1. class EnumExample5{
2. enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}

3.
4. public static void main(String args[]){
5.
6. Day day=Day.MONDAY;
7.
8. switch(day){
9. case SUNDAY:
10. System.out.println("sunday");
11. break;
12. case MONDAY:
13. System.out.println("monday");
14. break;
15. default:
16. System.out.println("other day");
17. }
18.
19. }}
20.
Java Annotation
Annotation is a tag that represents the metadata. It is attached with class, interface, methods or fields to
indicate some additional information that can be used by java compiler and JVM.

Built-In Annotations
There are several built-in annoations. Some annotations are applied to java code and some to other
annotations.
Built-In Annotations that are applied to java code
 @Override
 @SuppressWarnings
 @Deprecated
Built-In Annotations that are applied to other annotations
 @Target
 @Retention
 @Inherited
 @Documented

Understanding Built-In Annotations that are applied to java code



Jai Ma Saraswati

Let's understand the built-in annotations first.


@Override
@Override annotation assures that the subclass method is overriding the parent class method. If it is not
so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark @Override
annotation that provides assurity that method is overridden.
1. class Animal{
2. void eatSomething(){System.out.println("eating something");}
3. }
4.
5. class Dog extends Animal{
6. @Override
7. void eatsomething(){System.out.println("eating foods");}//should be eatSomething
8. }
9.
10. class Test{
11. public static void main(String args[]){
12. Animal a=new Dog();
13. a.eatSomething();
14. }}
Output:Comple Time Error

@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.
1. import java.util.*;
2. class Test{
3. @SuppressWarnings("unchecked")
4. public static void main(String args[]){
5.
6. ArrayList list=new ArrayList();
7. list.add("ank");
8. list.add("vimal");
9. list.add("ratan");
10.
11. for(Object obj:list)
12. System.out.println(obj);
13.
14. }}
Now no warning at compile time.
If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at compile time
because we are using non-generic collection.

@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It informs user
that it may be removed in the future versions. So, it is better not to use such methods.
1. class A{

Jai Ma Saraswati

2. void m(){System.out.println("hello m");}


3.
4. @Deprecated
5. void n(){System.out.println("hello n");}
6. }
7.
8. class Test{
9. public static void main(String args[]){
10.
11. A a=new A();
12. a.n();
13. }}
At Compile Time:
Note: Test.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.


At Runtime:
hello n
Custom Annotation
We can create the user-defined annotations also. The @interface element is used to declare an
annotation. For example:
1. @interface MyAnnotation{}
Points to remember for annotation signature
There are few points that should be remembered by the programmer.
1. Method should not have any throws clauses
2. Method should return one of the following: primitive data types, String, Class, enum or array of
these data types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to define annotation.
5. It may assign a default value to the method.

Types of Annotation
There are three types of annotations.
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:
1. @interface MyAnnotation{}
The @Override and @Deprecated are marker annotations.

2) Single-Value Annotation
An annotation that has one method, is called Single-Value annotation. For example:
1. @interface MyAnnotation{
2. int value();
3. }

Jai Ma Saraswati

We can provide the default value also. For example:


1. @interface MyAnnotation{
2. int value() default 0;
3. }
How to apply Single-Value Annotation
Let's see the code to apply the single value annotation.
1. @MyAnnotation(value=10)
The value can be anything.

3) Mulit-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:
1. @interface MyAnnotation{
2. int value1();
3. String value2();
4. String value3();
5. }
6. }
We can provide the default value also. For example:
1. @interface MyAnnotation{
2. int value1() default 1;
3. String value2() default "";
4. String value3() default "xyz";
5. }
How to apply Multi-Value Annotation
Let's see the code to apply the multi-value annotation.
1. @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

Built-in Annotations applied to other annotations (custom annotations)


 @Target
 @Retention
 @Inherited
 @Documented

@Target
@Target tag is used to specify at which type, the annotation is used.
The java.lang.annotation.ElementType enum declares many constants to specify the type of element
where annotation is to be applied such as TYPE, METHOD, FIELD etc. Let's see the constants of
ElementType enum:
Element Types Where the annotation can be applied
TYPE class, interface or enumeration
FIELD fields
METHOD methods
CONSTRUCTOR constructors
LOCAL_VARIABLE local variables

Jai Ma Saraswati

ANNOTATION_TYPE annotation type


PARAMETER parameter
Example to specify annoation for a class
1. @Target(ElementType.TYPE)
2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }
Example to specify annoation for a class, methods or fields
1. @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }

@Retention
@Retention annotation is used to specify to what level annotation will be available.
RetentionPolicy Availability
refers to the source code, discarded during compilation. It will not be available
RetentionPolicy.SOURCE
in the compiled class.
refers to the .class file, available to java compiler but not to JVM . It is
RetentionPolicy.CLASS
included in the class file.
RetentionPolicy.RUNTIME refers to the runtime, available to java compiler and JVM .
Example to specify the RetentionPolicy
1. @Retention(RetentionPolicy.RUNTIME)
2. @Target(ElementType.TYPE)
3. @interface MyAnnotation{
4. int value1();
5. String value2();
6. }

Example of custom annotation: creating, applying and accessing annotation


Let's see the simple example of creating, applying and accessing annotation.
1. //Creating annotation
2. import java.lang.annotation.*;
3. import java.lang.reflect.*;
4.
5. @Retention(RetentionPolicy.RUNTIME)
6. @Target(ElementType.METHOD)
7. @interface MyAnnotation{
8. int value();
9. }
10.
11. //Applying annotation
12. class Hello{

Jai Ma Saraswati

13. @MyAnnotation(value=10)
14. public void sayHello(){System.out.println("hello annotation");}
15. }
16.
17. //Accessing annotation
18. class Test{
19. public static void main(String args[])throws Exception{
20.
21. Hello h=new Hello();
22. Method m=h.getClass().getMethod("sayHello");
23.
24. MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
25. System.out.println("value is: "+manno.value());
26. }}
Output:value is: 10

--------------------------

How built-in annotaions are used in real scenario?


In real scenario, java programmer only need to apply annotation. He/She doesn't need to create and
access annotation. Creating and Accessing annotation is performed by the implementation provider. On
behalf of the annotation, java compiler or JVM performs some additional operations.

@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation marks the annotation
to be inherited to subclasses.
1. @Inherited
2. @interface ForEveryone { }//Now it will be available to subclass also
3.
4. @interface ForEveryone { }
5. class Superclass{}
6.
7. class Subclass extends Superclass{}

@Documented
The @Documented Marks the annotation for inclusion in the documentation.
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the
java programmer to store specific type of objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety : We can hold only a single type of objects in generics. It doesn‟t allow to store other
objects.
2) Type casting is not required: There is no need to typecast the object.

Jai Ma Saraswati

Before Generics, we need to type cast.


1. List list = new ArrayList();
2. list.add("hello");
3. String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
1. List<String> list = new ArrayList<String>();
2. list.add("hello");
3. String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The
good programming strategy says it is far better to handle the problem at compile time than runtime.
1. List<String> list = new ArrayList<String>();
2. list.add("hello");
3. list.add(32);//Compile Time Error

Syntax to use generic collection


1. ClassOrInterface<Type>
Simple example to use Generics
1. ArrayList<String>

Full Example of Java Generics


Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.
1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Output:element is: jai
rahul
jai

Jai Ma Saraswati

Example of Java Generics using Map


Now we are going to use map elements using generics. Here, we need to pass key and value. Let us
understand it by a simple example:
1. import java.util.*;
2. class Test{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(1,"vijay");
6. map.put(4,"umesh");
7. map.put(2,"ankit");
8.
9. //Now use Map.Entry for Set and Iterator
10. Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12. Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13. while(itr.hasNext()){
14. Map.Entry e=itr.next();//no need to typecast
15. System.out.println(e.getKey()+" "+e.getValue());
16. }
17.
18. }}
Output:1 vijay
2 ankit
4 umesh

Generic class
A class that can refer to any type is known as generic class. Here, we are using T type parameter to
create the generic class of specific type.
Let‟s see the simple example to create and use the generic class.
Creating generic class:
1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }
The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type you
specify for the class, will be used to store and retrieve the data.
Using generic class:
Let‟s see the code to use the generic class.
1. class UseGen{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());

Jai Ma Saraswati

7. }}
Output:2

Understanding Type Parameters


The type parameters naming conventions are important to learn generics thoroughly. The commonly type
parameters are as follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value
6. S,U,V etc. - 2nd, 3rd, 4th types

Generic Method
Like generic class, we can create generic method that can accept any type of argument.
Let‟s see a simple example of java generic method to print array elements. We are using here E to
denote the element.
1. public class GenericMethodDemo{
2.
3. public static < E > void printArray(E[] elements) {
4. for ( E element : elements){
5. System.out.println(element );
6. }
7. System.out.println();
8. }
9. public static void main( String args[] ) {
10. Integer[] intArray = { 10, 20, 30, 40, 50 };
11. Character[] charArray = { 'H', 'F', 'T', 'E', 'C','H'};
12.
13. System.out.println( "Printing Integer Array" );
14. printArray( intArray );
15.
16. System.out.println( "Printing Character Array" );
17. printArray( charArray );
18. }
19. }
Output:Printing Integer Array
10
20
30
40
50
Printing Character Array

H
F
T
E
C
H

You might also like