Vous êtes sur la page 1sur 265

Java Introduction:

Java is a high-level programming language originally developed by Sun Microsystems in 1995.


Java is a platform independent language. Yes, it runs on a multiple platforms such as UNIX,
Windows, Mac OS. The Java language’s programming is based on the concept of OOP.

JDK, JRE and JVM:

We need to understand three terminologies for sure in Java such as JDK, JRE and JVM. Here I
give basic idea about these terms.

What is JDK?

JDK stands for Java Development Kit.


Using JDK, we can develop, compile and execute (run) new applications and also we can modify
existing applications. We need to install JDK in developers machine where we want to develop
new applications or modify existing applications.
JDK includes JRE and development tools (environment to develop, debug and monitor Java
programs).

What is JRE?

JRE stands for Java Runtime Environment.


Using JRE, we can only execute already developed applications. We cannot develop new
applications or modify existing applications.
As the name suggests, JRE only provides Runtime Environment.

What is JVM?

JVM stands for Java Virtual Machine. JVM drives the java code. Using JVM, we can run java
byte code by converting them into current OS machine language.

Java Syntax:

1. Java is a case sensitive language


Ex: NAME and name are not same as per Java Language
2. Java file name should be same as its Class name
3. Class name should start with upper case letter
4. Method name should start with lower case letter
5. Every statement should end with semi colon
6. Java program execution starts from main method which is mandatory in every program
Public static void main(String args[])

Introduction to Java
Java is one of the world's most important and widely used computer languages, and it has held
this distinction for many years. Unlike some other computer languages whose influence has
weared with passage of time, while Java's has grown.
As of 2015, Java is one of the most popular programming languages in use, particularly for
client-server web applications, with a reported 9 million developers using and working on it.

Creation of Java
Java was developed by James Ghosling, Patrick Naughton, Mike Sheridan at Sun Microsystems
Inc. in 1991. It took 18 months to develop the first working version.
The initial name was Oak but it was renamed to Java in 1995 as OAK was a registered
trademark of another Tech company.

Evolution of Java
Java was initially launched as Java 1.0 but soon after its initial release, Java 1.1 was launched.
Java 1.1 redefined event handling, new library elements were added.
In Java 1.2 Swing and Collection framework was added
and suspend(), resume() and stop()methods were deprecated from Thread class.
No major changes were made into Java 1.3 but the next release that was Java 1.4 contained
several important changes. Keyword assert, chained exceptions and channel based I/O System
was introduced.
Java 1.5 was called J2SE 5, it added following major new features :

Setting Classpath for Java


Java is freely available on Oracle's Website. Download the latest version of JDK (Java
Development Kit) on your machine. Do check whether your machine is 32 bit or 64 bit and
download that particular Java version. Install JDK on your machine. Once you have installed
Java on your machine you would need to set environment variable to point to correct installation
directory.
An Environment variable is a dynamic "object" on a computer that stores a value(like a key-
value pair), which can be referenced by one or more software programs in Windows. Like for
Java, we will set an environment variable with name "java" and its value will be the path of
the /bin directory present in Java directory. So whenever a program will require Java
environment, it will look for the java environment variable which will give it the path to the
execution directory.

Setting up path for windows ( 2000/XP/vista/Window 7,8 )


Assuming that you have installed Java in C:\ Program files/ Java / JDK directory
Step 1: Right click on my computer and select properties.

Step 2: Go to the Advance System Settings tab.


Step 3: Click on Environment Variables button.

Step 4: Now alter the path variable so that it also contains the path to JDK installed directory.
For e.g:- Change C:\windows/ system 32. to C:\windows/system 32; C:\program files / Java/
JDK.

Setting up path for window 95/98/ME


Assuming that you have installed Java in C:\program files\ java\ JDK directory, do the
following:
Step 1: Edit the C:\autoexec.bat file and add the following line at the end.
SET PATH =% PATH% C:\ PROGRAM FILE/JAVA/JDK/bin

Setting up path for Linux , Unix , Solaris, free BSD


Assuming that you have installed Java in C:\program files\ java\ JDK directory, do the
following:
Step 1: Environment variable path should be set to point where java binaries have been installed.
Refer to your shell if you have trouble doing this.
For Example: If you use bash as your shell, then you would add following line to the end
bash mc: export PATH=/ Path/to/java

 Generics
 Annotations
 Autoboxing and autounboxing
 Enumerations
 For-each Loop
 Varargs
 Static Import
 Formatted I/O
 Concurrency utilities

Next major release was Java SE 7 which included many new changes, like :

 Now String can be used to control Switch statement.


 Multi Catch Exception
 try-with-resource statement
 Binary Integer Literals
 Underscore in numeric literals, etc.

And the latest addition to the lot is, Java SE 8, it was released on March 18, 2014. Some of the
major new features introduced in JAVA 8 are,

 Lambda Expressions
 New Collection Package java.util.stream to provide Stream API.
 Enhanced Security
 Nashorn Javascript Engine included
 Parallel Array Sorting
 The JDBC-ODBC Bridge has been removed etc.

Application of Java
Java is widely used in every corner of world and of human life. Java is not only used in softwares
but is also widely used in designing hardware controlling software components. There are more
than 930 million JRE downloads each year and 3 billion mobile phones run java.
Following are some other usage of Java :

1. Developing Desktop Applications


2. Web Applications like Linkedin.com, Snapdeal.com etc
3. Mobile Operating System like Android
4. Embedded Systems
5. Robotics and games etc.
Features of Java
The prime reason behind creation of Java was to bring portability and security feature into a
computer language. Beside these two major features, there were many other features that played
an important role in moulding out the final form of this outstanding language. Those features are
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand. The confusing
and ambiguous concepts of C++ are either left out in Java or they have been re-implemented in a
cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C++.

2) Object Oriented

In java everything is Object which has some data and behaviour. Java can be easily extended as
it is based on Object Model.
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time
error checking and runtime checking. But the main areas which Java improved were Memory
Management and mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.

4) Platform Independent

Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent
and can be run on any machine, plus this bytecode format also provide security. Any machine
with Java Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable us
to develop virus free, temper free system. Java program always runs in Java runtime environment
with almost null interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer architecture,
hence a Java program is easy to intrepret on any machine.

8) Portable

Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types

9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
But, Java enables high performance with the use of just-in-time compiler.

New Features of JAVA 8


Below mentioned are some of the core upgrades done as a part of Java 8 release. Just go through
them quickly, we will explore them in details later.

 Enhanced Productivity by providing Optional Classes feature, Lamda Expressions, Streams


etc.
 Ease of Use
 Improved Polyglot programming. A Polyglot is a program or script, written in a form which
is valid in multiple programming languages and it performs the same operations in multiple
programming languages. So Java now supports such type of programming technique.
 Improved Security and performance.
What is JVM?
Java virtual Machine(JVM) is a virtual Machine that provides runtime environment to execute
java byte code. The JVM doesn't understand Java typo, that's why you compile your *.java files
to obtain *.class files that contain the bytecodes understandable by the JVM.
JVM control execution of every Java program. It enables features such as automated exception
handling, Garbage-collected heap.

JVM Architecture

Class Loader : Class loader loads the Class for execution.


Method area : Stores pre-class structure as constant pool.
Heap : Heap is in which objects are allocated.
Stack : Local variables and partial results are store here. Each thread has a private JVM stack
created when the thread is created.
Program register : Program register holds the address of JVM instruction currently being
executed.
Native method stack : It contains all native used in application.
Executive Engine : Execution engine controls the execute of instructions contained in the
methods of the classes.
Native Method Interface : Native method interface gives an interface between java code and
native code during execution.
Native Method Libraries : Native Libraries consist of files required for the execution of native
code.
Difference between JDK and JRE
JRE : The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine,
and other components to run applets and applications written in the Java programming language.
JRE does not contain tools and utilities such as compilers or debuggers for developing applets
and applications.

JDK : The JDK also called Java Development Kit is a superset of the JRE, and contains everything that is in
the JRE, plus tools such as the compilers and debuggers necessary for developing applets and
applications.
First Java Program
Let us look at a simple java program.
class Hello
{
public static void main(String[] args)
{
System.out.println ("Hello World program");
}
}
class : class keyword is used to declare classes in Java
public : It is an access specifier. Public means this function is visible to all.
static : static is again a keyword used to make a function static. To execute a static function you
do not have to create an Object of the class. The main() method here is called by JVM, without
creating any object for class.
void : It is the return type, meaning this function will not return anything.
main : main() method is the most important method in a Java program. This is the method which
is executed, hence all the logic must be inside the main() method. If a java class is not having a
main() method, it causes compilation error.
String[] args : This represents an array whose type is String and name is args. We will discuss
more about array in Java Array section.
System.out.println : This is used to print anything on the console like printf in C language.

Steps to Compile and Run your first Java program


Step 1: Open a text editor and write the code as above.
Step 2: Save the file as Hello.java
Step 3: Open command prompt and go to the directory where you saved your first java program
assuming it is saved in C:\
Step 4: Type javac Hello.java and press Return(Enter KEY) to compile your code. This
command will call the Java Compiler asking it to compile the specified file. If there are no errors
in the code the command prompt will take you to the next line.
Step 5: Now type java Hello on command prompt to run your program.
Step 6: You will be able to see Hello world program printed on your command prompt.
Now let us see What happens at Runtime
After writing your Java program, when you will try to compile it. Compiler will perform some
compilation operation on your program.
Once it is compiled successfully byte code(.class file) is generated by the compiler.

After compiling when you will try to run the byte code(.class file), the following steps are
performed at runtime:-

1. Class loader loads the java class. It is subsystem of JVM Java Virtual machine.
2. Byte Code verifier checks the code fragments for illegal codes that can violate access right to
the object.
3. Interpreter reads the byte code stream and then executes the instructions, step by step.
Data Types in Java
Java language has a rich implementation of data types. Data types specify size and the type of
values that can be stored in an identifier.
In java, data types are classified into two catagories :

1. Primitive Data type


2. Non-Primitive Data type

1) Primitive Data type


A primitive data type can be of eight types :

Primitive Data types

char boolean byte short int long float double

Once a primitive data type has been declared its type can never change, although in most cases
its value can change. These eight primitive type can be put into four groups
Integer

This group includes byte, short, int, long


byte : It is 1 byte(8-bits) integer data type. Value range from -128 to 127. Default value zero.
example: byte b=10;
short : It is 2 bytes(16-bits) integer data type. Value range from -32768 to 32767. Default value
zero. example: short s=11;
int : It is 4 bytes(32-bits) integer data type. Value range from -2147483648 to 2147483647.
Default value zero. example: int i=10;
long : It is 8 bytes(64-bits) integer data type. Value range from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. Default value zero. example: long l=100012;
Floating-Point Number
This group includes float, double
float : It is 4 bytes(32-bits) float data type. Default value 0.0f. example: float ff=10.3f;
double : It is 8 bytes(64-bits) float data type. Default value 0.0d. example: double db=11.123;
Characters
This group represent char, which represent symbols in a character set, like letters and numbers.
char : It is 2 bytes(16-bits) unsigned unicode character. Range 0 to 65,535. example: char c='a';
Boolean
This group represent boolean, which is a special type for representing true/false values. They are
defined constant of the language. example: boolean b=true;
2) Non-Primitive(Reference) Data type
A reference data type is used to refer to an object. A reference variable is declare to be of
specific and that type can never be change. We will talk a lot more about reference data type
later in Classes and Object lesson.

Identifiers in Java
All Java components require names. Name used for classes, methods, interfaces and variables are
called Identifier. Identifier must follow some rules. Here are the rules:

 All identifiers must start with either a letter( a to z or A to Z ) or currency character($) or an


underscore.
 After the first character, an identifier can have any combination of characters.
 A Java keyword cannot be used as an identifier.
 Identifiers in Java are case sensitive, foo and Foo are two different identifiers.

Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,

 Widening Casting(Implicit)

 Narrowing Casting(Explicitly done)

Widening or Automatic type converion


Automatic Type casting take place when,

 the two types are compatible


 the target type is larger than the source type

Example :
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit type conversion
When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);
}

Double value 100.04


Long value 100
Int value 100

Variable

What is a variable?
When we want to store any information, we store it in an address of the computer. Instead of
remembering the complex address where we have stored our information, we name that address.
The naming of an address is known as variable. Variable is the name of memory location.
Java Programming language defines mainly three kind of variables.

1. Instance variables
2. Static Variables
3. Local Variables

1) Instance variables
Instance variables are variables that are declare inside a class but outside any method,
constructor or block. Instance variable are also variable of object commonly known as field or
property. They are referred as object variable. Each object has its own copy of each variable and
thus, it doesn't effect the instance variable if one object changes the value of the variable.
class Student
{
String name;
int age;
}
Here name and age are instance variable of Student class.

2) Static variables
Static are class variables declared with static keyword. Static variables are initialized only once.
Static variables are also used in declaring constant along with final keyword.
class Student
{
String name;
int age;
static int instituteCode=1101;
}
Here instituteCode is a static variable. Each object of Student class will share instituteCode
property.
Additional points on static variable:

 static variable are also known as class variable.


 static means to remain constant.
 In Java, it means that it will be constant for all the instances created for that class.
 static variable need not be called from object.
 It is called by classname.static variable name

Note: A static variable can never be defined inside a method i.e it can never be a local variable.
Example:

Suppose you make 2 objects of class Student and you change the value of static variable from
one object. Now when you print it from other object, it will display the changed value. This is
because it was declared static i.e it is constant for every object created.
package studytonight;

class Student{
int a;
static int id = 35;

void change(){

System.out.println(id);
}
}

public class StudyTonight {


public static void main(String[] args) {

Student o1 = new Student();


Student o2 = new Student();

o1.change();
Student.id = 1;
o2.change();
}
}

35
1

3) Local variables
Local variables are declared in method, constructor or block. Local variables are initialized when
method, constructor or block start and will be destroyed once its end. Local variable reside in
stack. Access modifiers are not used for local variable.
float getDiscount(int price)
{
float discount;
discount=price*(20/100);
return discount;
}
Here discount is a local variable.

Concept of Array in Java


An array is a collection of similar data types. Array is a container object that hold values of
homogenous type. It is also known as static data structure because size of an array must be
specified at the time of its declaration.
An array can be either primitive or reference type. It gets memory in heap area. Index of array
starts from zero to size-1.

Features of Array

 It is always indexed. Index begins from 0.


 It is a collection of similar data types.
 It occupies a contiguous memory location.

Array Declaration
Syntax :
datatype[] identifier;
or
datatype identifier[];
Both are valid syntax for array declaration. But the former is more readable.
Example :
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr; // two dimensional array.

Initialization of Array
new operator is used to initialize an array.
Example :
int[] arr = new int[10]; //this creates an empty array named arr of integer type whose size is 10.
or
int[] arr = {10,20,30,40,50}; //this creates an array named arr whose elements are given.

Accessing array element


As mention ealier array index starts from 0. To access nth element of an array. Syntax
arrayname[n-1];
Example : To access 4th element of a given array
int[ ] arr = {10,20,30,40};
System.out.println("Element at 4th place" + arr[3]);
The above code will print the 4th element of array arr on console.

Note: To find the length of an array, we can use the following syntax: array_name.length. There
are no braces infront of length. Its not length().

foreach or enhanced for loop


J2SE 5 introduces special type of for loop called foreach loop to access elements of array. Using
foreach loop you can access complete array sequentially without using index of array. Let us see
an example of foreach loop.
class Test
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40};
for(int x : arr)
{
System.out.println(x);
}
}
}

10
20
30
40

Multi-Dimensional Array
A multi-dimensional array is very much similar to a single dimensional array. It can have
multiple rows and multiple columns unlike single dimensional array, which can have only one
full row or one full column.
Array Declaration
Syntax:

datatype[ ][ ] identifier;
or
datatype identifier[ ][ ];

Initialization of Array
new operator is used to initialize an array.
Example:

int[ ][ ] arr = new int[10][10]; //10 by 10 is the size of array.


or
int[ ][ ] arr = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
// 3 by 5 is the size of the array.

Accessing array element


For both, row and column, the index begins from 0.
Syntax:

array_name[m-1][n-1]
Example:

int arr[ ][ ] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};


System.out.println("Element at (2,3) place" + arr[1][2]);

Jagged Array
Jagged means to have an uneven edge or surface. In java, a jagged array means to have a multi-
dimensional array with uneven size of rows in it.
Initialization of Jagged Array
new operator is used to initialize an array.
Example:

int[ ][ ] arr = new int[3][ ]; //there will be 10 arrays whose size is variable
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[5];

Java Operators
Java provides a rich set of operators environment. Java operators can be divided into following
categories:
 Arithmetic operators
 Relation operators
 Logical operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Misc operators

Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used in
algebra.

Operator Description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denumerator

% remainder of division

++ Increment operator increases integer value by one

-- Decrement operator decreases integer value by one


Relation operators
The following table shows all relation operators supported by Java.

Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false


Bitwise operators
Java defines several bitwise operators that can be applied to the integer types long, int, short,
char and byte

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

>> left shift

<< right shift

Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted
and the right operand specifies the number of positions that the bits in the value are to be shifted.
Both operands have the same precedence.
Example:

a = 0001000
b=2
a << b = 0100000
a >> b = 0000010

Assignment Operators
Assignment operator supported by Java are as follows:

Operator Description Example

= assigns values from right side operands to left side operand a=b

+= adds right operand to the left operand and assign the result to left a+=b is same
as a=a+b

-= subtracts right operand from the left operand and assign the result a-=b is same as a=a-
to left operand b

*= mutiply left operand with the right operand and assign the result a*=b is same
to left operand as a=a*b

/= divides left operand with the right operand and assign the result a/=b is same
to left operand as a=a/b

%= calculate modulus using two operands and assign the result to left a%=b is same
operand as a=a%b
Misc operator
There are few other operator supported by java language.
Conditional operator
It is also known as ternary operator and used to evaluate Boolean expression,
epr1 ? expr2 : expr3
If epr1Condition is true? Then value expr2 : Otherwise value expr3

instanceOf operator

This operator is used for object reference variables. The operator checks whether the object is of
particular type (class type or interface type)

Object and Classes


Since Java is an object oriented language, complete java language is build on classes and object.
Java is also known as a strong Object oriented programming language(OOPS).
OOPS is a programming approach which provides solution to problems with the help of
algorithms based on real world. It uses real world approach to solve a problem. So object
oriented technique offers better and easy way to write program then procedural programming
model such as C, ALGOL, PASCAL.

Main Features of OOPS

 Inheritence
 Polymorphism
 Encapsulation
 Abstraction

As an object oriented language Java supports all the features given above. We will discuss all
these features in detail later.
Class
In Java everything is encapsulated under classes. Class is the core of Java language. Class can be
defined as a template/ blueprint that describe the behaviors /states of a particular entity. A class
defines new data type. Once defined this new type can be used to create object of that type.
Object is an instance of class. You may also call it as physical existence of a logical template
class.
A class is declared using class keyword. A class contain both data and code that operate on that
data. The data or variables defined within a class are called instance variables and the code that
operates on this data is known as methods. Thus, the instance variables and methods are known
as class members. class is also known as a user defined datatype.
A class and an object can be related as follows: Consider an ice tray(like of cube shape) as a
class. Then ice cubes can be considered as the objects which is a blueprint of its class i.e of ice
tray.

Rules for Java Class

 A class can have only public or default(no modifier) access specifier.


 It can be either abstract, final or concrete (normal class).
 It must have the class keyword, and class must be followed by a legal identifier.
 It may optionally extend one parent class. By default, it will extend java.lang.Object.
 It may optionally implement any number of comma-separated interfaces.
 The class's variables and methods are declared within a set of curly braces {}.
 Each .java source file may contain only one public class. A source file may contain any
number of default visible classes.
 Finally, the source file name must match the public class name and it must have a .java
suffix.
A simple class example
Suppose, Student is a class and student's name, roll number, age will be its property. Lets see this
in Java syntax
class Student.
{
String name;
int rollno;
int age;
}
When a reference is made to a particular student with its property then it becomes an object,
physical existence of Student class.
Student std=new Student();
After the above statement std is instance/object of Student class. Here the new keyword creates
an actual physical copy of the object and assign it to the std variable. It will have physical
existence and get memory in heap area. The new operator dynamically allocates memory for
an object
Q. How a class is initialized in java?
A Class is initialized in Java when an instance of class is created using either new operator or
using reflection using class.forName(). A class is also said to be initialized when a static method
of Classis invoked or a static field of Class is assigned.

Q. How would you make a copy of an entire Java object with its state?
Make that class implement Cloneable interface and call clone() method on its
object. clone() method is defined in Object class which is parent of all java class by default.

Methods in Java
Method describe behavior of an object. A method is a collection of statements that are group
together to perform an operation.
Syntax :
return-type methodName(parameter-list)
{
//body of method
}

Example of a Method
public String getName(String st)
{
String name="StudyTonight";
name=name+st;
return name;
}

Modifier : Modifier are access type of method. We will discuss it in detail later.
Return Type : A method may return value. Data type of value return by a method is declare in
method heading.
Method name : Actual name of the method.
Parameter : Value passed to a method.
Method body : collection of statement that defines what method does.
Parameter Vs. Argument
While talking about method, it is important to know the difference between two
terms parameter and argument.
Parameter is variable defined by a method that receives value when the method is called.
Parameter are always local to the method they dont have scope outside the method.
While argument is a value that is passed to a method when it is called.

call-by-value and call-by-reference


There are two ways to pass an argument to a method

1. call-by-value : In this approach copy of an argument value is pass to a method. Changes


made to the argument value inside the method will have no effect on the arguments.
2. call-by-reference : In this reference of an argument is pass to a method. Any changes made
inside the method will affect the agrument value.

NOTE :There is only call by value in java, not call by reference.


Example of call-by-value
public class Test
{
public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}

50

Method overloading
If two or more method in a class have same name but different parameters, it is known as method
overloading. Overloading always occur in the same class(unlike method overriding).
Method overloading is one of the ways through which java supports polymorphism. Method
overloading can be done by changing number of arguments or by changing the data type of
arguments. If two or more method have same name and same parameter list but differs in
return type are not said to be overloaded method
Note: Overloaded method can have different access modifiers.
Different ways of Method overloading
There are two different ways of method overloading
Method overloading by changing data type of Arguments
Example :
class Calculate
{
void sum (int a, int b)
{
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}

Sum is 13
Sum is 8.4
You can see that sum() method is overloaded two times. The first takes two integer arguments,
the second takes two float arguments.
Method overloading by changing no. of argument.
Example :
class Area
{
void find(int l, int b)
{
System.out.println("Area is"+(l*b)) ;
}
void find(int l, int b,int h)
{
System.out.println("Area is"+(l*b*h));
}
public static void main (String[] args)
{
Area ar = new Area();
ar.find(8,5); //find(int l, int b) is method is called.
ar.find(4,6,2); //find(int l, int b,int h) is called.
}
}

Area is 40
Area is 48
In this example the find() method is overloaded twice. The first takes two arguments to calculate
area, and the second takes three arguments to calculate area.
When an overloaded method is called java look for match between the arguments to call the
method and the method's parameters. This match need not always be exact, sometime when
exact match is not found, Java automatic type conversion plays a vital role.
Example of Method overloading with type promotion.
class Area
{
void find(long l,long b)
{
System.out.println("Area is"+(l*b)) ;
}
void find(int l, int b,int h)
{
System.out.println("Area is"+(l*b*h));
}
public static void main (String[] args)
{
Area ar = new Area();
ar.find(8,5); //automatic type conversion from find(int,int) to find(long,long) .
ar.find(2,4,6) //find(int l, int b,int h) is called.
}
}

Area is 40
Area is 48

Constructors in Java
A constructor is a special method that is used to initialize an object.Every class has a
constructor,if we don't explicitly declare a constructor for any java class the compiler builds a
default constructor for that class. A constructor does not have any return type.
A constructor has same name as the class in which it resides. Constructor in Java can not be
abstract, static, final or synchronized. These modifiers are not allowed for constructor.
class Car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
}

There are two types of Constructor

 Default Constructor
 Parameterized constructor

Each time a new object is created at least one constructor will be invoked.
Car c = new Car() //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked

Constructor Overloading
Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated
on the basis of their type of parameters or number of parameters. Constructor overloading is not
much different than method overloading. In case of method overloading you have multiple
methods with same name but different signature, whereas in Constructor overloading you have
multiple constructor with different signature but only difference is that Constructor doesn't have
return type in Java.

Q. Why do we Overload constructors ?


Constuctor overloading is done to construct object in different ways.
Example of constructor overloading
class Cricketer
{
String name;
String team;
int age;
Cricketer () //default constructor.
{
name ="";
team ="";
age = 0;
}
Cricketer(String n, String t, int a) //constructor overloaded
{
name = n;
team = t;
age = a;
}
Cricketer (Cricketer ckt) //constructor similar to copy constructor of c++
{
name = ckt.name;
team = ckt.team;
age = ckt.age;
}
public String toString()
{
return "this is " + name + " of "+team;
}
}
Class test:
{
public static void main (String[] args)
{
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("sachin", "India", 32);
Cricketer c3 = new Cricketer(c2 );
System.out.println(c2);
System.out.println(c3);
c1.name = "Virat";
c1.team= "India";
c1.age = 32;
System .out. print in (c1);
}
}

this is sachin of india


this is sachin of india
this is virat of india

Q What's the difference between constructors and normal methods?


Constructors must have the same name as the class and can not return a value. They are only
called once for a single object while regular methods could be called many times and it can
return a value or can be void.

Q. What is constructor chaining in Java?


Constructor chaining is a phenomena of calling one constructor from another constructor of same
class. Since constructor can only be called from another constructor in Java, constructor chaining
is used for this purpose.
class Test
{
Test()
{
this(10);
}
Test(int x)
{
System.out.println("x="+x);
}
public static void main(String arg[])
{
Test object = new Test();
}
}

x=10

Q. Does constructors return any value?


Yes, constructors return current instant of a class. But yet constructor signature cannot have any
return type.

this keyword

 this keyword is used to refer to current object.


 this is always a reference to the object on which method was invoked.
 this can be used to invoke current class constructor.
 this can be passed as an argument to another method.
Example :
class Box
{
Double width, height, depth;
Box (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
}
Here the this is used to initialize member of current object. Such as, this.width refers to the
variable width of the current object that has invoked the constructor. width only refers to the
parameter received in the constructor i.e the argument passed while calling the constructor.

The this is used to call overloaded constructor in java


class Car
{
private String name;
public Car()
{
this("BMW"); //oveloaded constructor is called.
}
public Car(String n)
{
this.name=n; //member is initialized using this.
}
}
The this is also used to call Method of that class.
public void getName()
{
System.out.println("Studytonight");
}

public void display()


{
this.getName();
System.out.println();
}

this is used to return current Object


public Car getCar()
{
return this;
}

Garbage Collection
In Java destruction of object from memory is done automatically by the JVM. When there is no
reference to an object, then that object is assumed to be no longer needed and the memory
occupied by the object are released. This technique is called Garbage Collection. This is
accomplished by the JVM.
Unlike C++ there is no explicit need to destroy object.
Can the Garbage Collection be forced explicitly ?
No, the Garbage Collection can not be forced explicitly. We may request JVM for garbage
collection by calling System.gc() method. But This does not guarantee that JVM will perform
the garbage collection.

Advantages of Garbage Collection

1. Programmer doesn't need to worry about dereferencing an object.


2. It is done automatically by JVM.
3. Increases memory efficiency and decreases the chances for memory leak.

finalize() method
Sometime an object will need to perform some specific task before it is destroyed such as closing
an open connection or releasing any resources held. To handle such situation finalize() method is
used. finalize() method is called by garbage collection thread before collecting object. Its the last
chance for any object to perform cleanup utility.
Signature of finalize() method
protected void finalize()
{
//finalize-code
}

Some Important Points to Remember

1. finalize() method is defined in java.lang.Object class, therefore it is available to all the


classes.
2. finalize() method is declare as proctected inside Object class.
3. finalize() method gets called only once by a Daemon thread named GC (Garbage
Collector)thread.

gc() Method
gc() method is used to call garbage collector explicitly. However gc() method does not guarantee
that JVM will perform the garbage collection. It only request the JVM for garbage collection.
This method is present in System and Runtime class.
Example for gc() method
public class Test
{
public static void main(String[] args)
{
Test t = new Test();
t=null;
System.gc();
}
public void finalize()
{
System.out.println("Garbage Collected");
}
}
Garbage Collected

Modifiers in Java
Modifiers are keywords that are added to change meaning of a definition. In Java, modifiers are
catagorized into two types,

1. Access control modifier


2. Non Access Modifier

1) Access control modifier


Java language has four access modifier to control access levels for classes, variable methods and
constructor.

 Default : Default has scope only inside the same package


 Public : Public has scope that is visible everywhere
 Protected : Protected has scope within the package and all sub classes
 Private : Private has scope only within the classes

2) Non-access Modifier
Non-access modifiers do not change the accessibility of variables and methods, but they do
provide them special properties. Non-access modifiers are of 5 types,

1. Final
2. Static
3. Transient
4. Synchronized
5. Volatile

Final
Final modifier is used to declare a field as final i.e. it prevents its content from being modified.
Final field must be initialized when it is declared. Final keyword can be used with a variable, a
method or a class.

1. Final Variable

When a variable is declared as final, then its value cannot be changed. The variable acts like
a constant.
Syntax:
final int a = 5;

2. Final Method

When a method is declared as final, then that method cannot be overridden.


Example:
class StudyTonight
{
final void learn()
{
System.out.println("learning something new");
}
}

class Student extends StudyTonight


{
void learn()
{
System.out.println("learning something interesting");
}
public static void main(String args[]){
Student object= new Student();
object.learn();
}
}
This will give a compile time error because the method is declared as final and thus, it cannot be
overridden.
Note: A final method can be inherited/used in the subclass, but it cannot be overriden.
Example :
class Cloth
{
final int MAX_PRICE = 999; //final variable
final int MIN_PRICE = 699;
final void display() //final method
{
System.out.println("Maxprice is" + MAX_PRICE );
System.out.println("Minprice is" + MIN_PRICE);
}
}
A class can also be declared as final. A class declared as final cannot be inherited. String class in
java.lang package is a example of final class. Method declared as final can be inherited but you
cannot override(redefine) it.
Static Modifier
Static Modifiers are used to create class variable and class methods which can be accessed
without instance of a class. Lets study how it works with variables and member functions.
Static with Variables
Static variables are defined as a class member that can be accessed without any object of that
class. Static variable has only one single storage. All the object of the class having static variable
will have the same instance of static variable. Static variables are initialized only once.
Static variable are used to represent common property of a class. It saves memory. Suppose there
are 100 employee in a company. All employee have its unique name and employee id but
company name will be same all 100 employee. Here company name is the common property. So
if you create a class to store employee detail, company_name field will be mark as static.
Example
class Employee
{
int e_id;
String name;
static String company_name = "StudyTonight";
}

Example of static variable


class ST_Employee
{
int eid;
String name;
static String company_name ="StudyTonight";
public void show()
{
System.out.println(eid+" "+name+" "+company_name);
}
public static void main( String[] args )
{
ST_Employee se1 = new ST_Employee();
se1.eid = 104;
se1.name = "Abhijit";
se1.show();
ST_Employee se2 = new ST_Employee();
se2.eid = 108;
se2.name = "ankit";
se2.show();
}

}
104 Abhijit StudyTonight
108 ankit StudyTonight

Static variable vs Instance Variable

Static variable Instance Variable

Represent common property Represent unique property

Accessed using class name Accessed using object

get memory only once get new memory each time a new object is created
Example
public class Test
{
static int x = 100;
int y = 100;
public void increment()
{
x++; y++;
}
public static void main( String[] args )
{
Test t1 = new Test();
Test t2 = new Test();
t1.increment();
t2.increment();
System.out.println(t2.y);
System.out.println(Test.x); //accessed without any instance of class.
}
}
/pre>

101
102
See the difference in value of two variable. Static variable x shows the changes made to it by
increment() method on the different object. While instance variable y show only the change
made to it by increment() method on that particular instance.

Static Method
A method can also be declared as static. Static methods do not need instance of its class for being
accessed. main() method is the most common example of static method. main() method is
declared as static because it is called before any object of the class is created.
Example :
class Test
{

public static void square(int x)


{
System.out.println(x*x);
}

public static void main (String[] arg)


{

square(8) //static method square () is called without any instance of class.


}
}

64

Static block
Static block is used to initialize static data member. Static block executes before main() method.
Example
class ST_Employee
{
int eid;
String name;
static String company_name;

static {
company_name ="StudyTonight"; //static block invoked before main() method
}

public void show()


{
System.out.println(eid+" "+name+" "+company_name);
}
public static void main( String[] args )
{
ST_Employee se1 = new ST_Employee();
se1.eid = 104;
se1.name = "Abhijit";
se1.show();

104 Abhijit StudyTonight

Q. Why a non-static variable cannot be referenced from a static context ?


When you try to access a non-static variable from a static context like main method, java
compiler throws a message like "a non-static variable cannot be referenced from a static
context". This is because non-static variables are related with instance of class(object) and they
get created when instance of a class is created by using new operator. So if you try to access a
non-static variable without any instance compiler will complain because those variables are not
yet created and they don't have any existence until an instance is created and associated with it.
Example of accessing non-static variable from a static context
class Test
{
int x;
public static void main(String[] args)
{
x=10;
}
}
compiler error: non-static variable count cannot be referenced from a static context
Same example using instance of class
class Test
{
int x;
public static void main(String[] args)
{
Test tt=new Test();
tt.x=10; //works fine with instance of class
}
}

Q. Why main() method is static in java ?


Because static methods can be called without any instance of a class and main() is called before
any instance of a class is created.

Transient modifier
When an instance variable is declared as transient, then its value doesn't persist when an object is
serialized

Synchronized modifier
When a method is synchronized it can be accessed by only one thread at a time. We will discuss
it in detail in Thread.

Volatile modifier
Volatile modifier tells the compiler that the volatile variable can be changed unexpectedly by
other parts of your program. Volatile variables are used in case of multithreading
program. volatile keyword cannot be used with a method or a class. It can be only used with a
variable.
Inheritance (IS-A)
Inheritance is one of the key features of Object Oriented Programming. Inheritance provided
mechanism that allowed a class to inherit property of another class. When a Class extends
another class it inherits all non-private members including fields and methods. Inheritance in
Java can be best understood in terms of Parent and Child relationship, also known as Super
class(Parent) and Sub class(child) in Java language.
Inheritance defines is-a relationship between a Super class and its Sub
class. extends and implements keywords are used to describe inheritance in Java.

Let us see how extends keyword is used to achieve Inheritance.


class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}
Now based on above example. In OOPs term we can say that,

 Vehicle is super class of Car.


 Car is sub class of Vehicle.
 Car IS-A Vehicle.
Purpose of Inheritance

1. It promotes the code reusabilty i.e the same methods and variables which are defined in a
parent/super/base class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.

Disadvantages of Inheritance
Main disadvantage of using inheritance is that the two classes (parent and child class)
gets tightly coupled.
This means that if we change code of parent class, it will affect to all the child classes which is
inheriting/deriving the parent class, and hence, it cannot be independent of each other.

Simple example of Inheritance


class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1()
{
System.out.println("Child method");
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}

Child method
Parent method

Another example of Inheritance


class Vehicle
{
String vehicleType;
}
public class Car extends Vehicle {

String modelType;
public void showDetail()
{
vehicleType = "Car"; //accessing Vehicle class member
modelType = "sports";
System.out.println(modelType+" "+vehicleType);
}
public static void main(String[] args)
{
Car car =new Car();
car.showDetail();
}
}

sports Car
Types of Inheritance

1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance

NOTE :Multiple inheritance is not supported in java

Why multiple inheritance is not supported in Java

 To remove ambiguity.
 To provide more maintainable and clear design.
super keyword
In Java, super keyword is used to refer to immediate parent class of a child class. In other
words super keyword is used by a subclass whenever it need to refer to its immediate super
class.
Example of Child class refering Parent class property using super keyword
class Parent
{
String name;

}
public class Child extends Parent {
String name;
public void details()
{
super.name = "Parent"; //refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}

Parent and Child

Example of Child class refering Parent class methods using super keyword
class Parent
{
String name;
public void details()
{
name = "Parent";
System.out.println(name);
}
}
public class Child extends Parent {
String name;
public void details()
{
super.details(); //calling Parent class details() method
name = "Child";
System.out.println(name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Parent
Child

Example of Child class calling Parent class constructor using super keyword
class Parent
{
String name;

public Parent(String n)
{
name = n;
}

}
public class Child extends Parent {
String name;

public Child(String n1, String n2)


{

super(n1); //passing argument to parent class constructor


this.name = n2;
}
public void details()
{
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child("Parent","Child");
cobj.details();
}
}

Parent and Child


Note: When calling the parent class constructor from the child class using super keyword, super
keyword should always be the first line in the method/constructor of the child class.

Super class reference pointing to Sub class object.


In context to above example where Class B extends class A.
A a=new B();
is legal syntax because of IS-A relationship is there between class A and Class B.

Q. Can you use both this() and super() in a Constructor?


NO, because both super() and this() must be first statement inside a constructor. Hence we
cannot use them together.

Aggregation (HAS-A)
HAS-A relationship is based on usage, rather than inheritance. In other words, class A has-
arelationship with class B, if code in class A has a reference to an instance of class B.

Example
class Student
{
String name;
Address ad;
}
Here you can say that Student has-a Address.
Student class has an instance variable of type Address. Student code can use Address reference
to invoke methods on the Address, and get Address behavior.
Aggregation allow you to design classes that follow good Object Oriented practices. It also
provide code reusability.

Example of Aggregation
class Author
{
String authorName;
int age;
String place;
Author(String name,int age,String place)
{
this.authorName=name;
this.age=age;
this.place=place;
}
public String getAuthorName()
{
return authorName;
}
public int getAge()
{
return age;
}
public String getPlace()
{
return place;
}
}

class Book
{
String name;
int price;
Author auth;
Book(String n,int p,Author at)
{
this.name=n;
this.price=p;
this.auth=at;
}
public void showDetail()
{
System.out.println("Book is"+name);
System.out.println("price "+price);
System.out.println("Author is "+auth.getAuthorName());
}
}

class Test
{
public static void main(String args[])
{
Author ath=new Author("Me",22,"India");
Book b=new Book("Java",550,ath);
b.showDetail();
}
}

Book is Java.
price is 550.
Author is me.

Q. What is Composition in java?


Composition is restricted form of Aggregation. Composition can be described as when one class
which owns the other class, is destroyed then the other class cannot exist meaningfully without
it. For example a class Car cannot exist without Engine.
class Car
{
private Engine engine;
Car(Engine en)
{
engine = en;
}
}

Q. When to use Inheritance and Aggregation?


When you need to use property and behaviour of a class without modifying it inside your class.
In such case Aggregation is a better option. Whereas when you need to use and modify property
and behaviour of a class inside your class, its best to use Inheritance.

Method Overriding
When a method in a sub class has same name, same number of arguments and same type
signature as a method in its super class, then the method is known as overridden method. Method
overriding is also referred to as runtime polymorphism. The key benefit of overriding is the
abitility to define method that's specific to a particular subclass type.
Example of Method Overriding
class Animal
{
public void eat()
{
System.out.println("Generic Animal eating");
}
}

class Dog extends Animal


{
public void eat() //eat() method overriden by Dog class.
{
System.out.println("Dog eat meat");
}
}
As you can see here Dog class gives it own implementation of eat() method. Method must have
same name and same type signature.
NOTE : Static methods cannot be overridden because, a static method is bounded with class
where as instance method is bounded with object.

Covariant return type


Since Java 5, it is possible to override a method by changing its return type. If subclass override
any method by changing the return type of super class method, then the return type of overriden
method must be subtype of return type declared in original method inside the super class. This
is the only way by which method can be overriden by changing its return type.
Example :
class Animal
{
Animal myType()
{
return new Animal();
}
}

class Dog extends Animal


{
Dog myType() //Legal override after Java5 onward
{
return new Dog();
}
}

Difference between Overloading and Overriding

Method Overloading Method Overriding

Parameter must be different and name Both name and parameter must be same.
must be same.

Compile time polymorphism. Runtime polymorphism.

Increase readability of code. Increase reusability of code.

Access specifier can be changed. Access specifier cannot be more restrictive than original
method(can be less restrictive).
Q. Can we Override static method? Explain with reasons ?
No, we cannot override static method. Because static method is bound to class whereas method
overriding is associated with object i.e at runtime.

Runtime Polymorphism or Dynamic method dispatch


Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at
runtime. This is how java implements runtime polymorphism. When an overridden method is
called by a reference, java determines which version of that method to execute based on the type
of object it refer to. In simple words the type of object which it referred determines which
version of overridden method will be called.
Upcasting
When Parent class reference variable refers to Child class object, it is known as Upcasting

Example
class Game
{
public void type()
{ System.out.println("Indoor & outdoor"); }
}

Class Cricket extends Game


{
public void type()
{ System.out.println("outdoor game"); }

public static void main(String[] args)


{
Game gm = new Game();
Cricket ck = new Cricket();
gm.type();
ck.type();
gm=ck; //gm refers to Cricket object
gm.type(); //calls Cricket's version of type
}
}

Indoor & outdoor


Outdoor game
Outdoor game
Notice the last output. This is because of gm = ck; Now gm.type() will call Cricket version of
type method. Because here gm refers to cricket object.

Q. Difference between Static binding and Dynamic binding in java ?


Static binding in Java occurs during compile time while dynamic binding occurs during runtime.
Static binding uses type(Class) information for binding while dynamic binding uses instance of
class(Object) to resolve calling of method at run-time. Overloaded methods are bonded using
static binding while overridden methods are bonded using dynamic binding at runtime.
In simpler terms, Static binding means when the type of object which is invoking the method is
determined at compile time by the compiler. While Dynamic binding means when the type of
object which is invoking the method is determined at run time by the compiler.

instanceof operator
In Java, instanceof operator is used to check the type of an object at runtime. It is the means by
which your program can obtain run-time type information about an object. instanceof operator is
also important in case of casting object at runtime. instanceof operator return boolean value, if an
object reference is of specified type then it return true otherwise false.

Example of instanceOf
public class Test
{
public static void main(String[] args)
{
Test t= new Test();
System.out.println(t instanceof Test);
}
}

true

Downcasting

Example of downcasting with instanceof operator


class Parent{ }

public class Child extends Parent


{
public void check()
{
System.out.println("Sucessfull Casting");
}

public static void show(Parent p)


{
if(p instanceof Child)
{
Child b1=(Child)p;
b1.check();
}
}

public static void main(String[] args)


{

Parent p=new Child();

Child.show(p);

}
}

Sucessfull Casting

More example of instanceof operator


class Parent{}

class Child1 extends Parent{}

class Child2 extends Parent{}


class Test
{
public static void main(String[] args)
{
Parent p =new Parent();
Child1 c1 = new Child1();
Child2 c2 = new Child2();

System.out.println(c1 instanceof Parent); //true


System.out.println(c2 instanceof Parent); //true
System.out.println(p instanceof Child1); //false
System.out.println(p instanceof Child2); //false

p = c1;
System.out.println(p instanceof Child1); //true
System.out.println(p instanceof Child2); //false

p = c2;
System.out.println(p instanceof Child1); //false
System.out.println(p instanceof Child2); //true

true
true
false
false
true
false
false
true

Command line argument in Java


The command line argument is the argument passed to a program at the time when you run it. To
access the command-line argument inside a java program is quite easy, they are stored as string
in String array passed to the args parameter of main() method.
Example
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}
Execute this program as java cmd 10 20 30

10
20
30
Java Package
Package are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of classes,
interface, enumeration or sub-package. Using package it becomes easier to locate the related
classes and it also provides a good structure for projects with hundreds of classes and other files.

Types of Packages: Built-in and User defined

 Built-in Package: Existing Java package for example java.lang, java.util etc.
 User-defined-package: Java package created by user to categorize their project's classes and
interface.
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by name
of the package as the first statement in java source file.
package mypack;
public class employee
{
statement;
}
The above statement will create a package woth name mypack in the project directory.
Java uses file system directories to store packages. For example the .java file for any class you
define to be part of mypack package must be stored in a directory called mypack.
Additional points about package:

 A package is always defined as a separate folder having the same name as the package name.
 Store all the classes in that package folder.
 All classes of the package which we wish to access outside the package must be declared
public.
 All classes within the package must have the package statement as its first line.
 All classes of the package must be compiled before use (So that they are error free)

Example of Java packages


//save as FirstProgram.java
package learnjava;
public class FirstProgram{
public static void main(String args[]) {
System.out.println("Welcome to package");
}
}

How to compile Java programs inside packages?


This is just like compiling a normal java program. If you are not using any IDE, you need to
follow the steps given below to successfully compile your packages:
javac -d directory javafilename
Example:
javac -d . FirstProgram.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like 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 Java package program?


You need to use fully qualified name e.g. learnjava.FirstProgram etc to run the class.
To Compile:
javac -d . FirstProgram.java
To Run:
java learnjava.FirstProgram
Output: Welcome to package
import keyword
import keyword is used to import built-in and user-defined packages into your java source file so
that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to any class that is present in a different package:

1. Using fully qualified name (But this is not a good practice.)

If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, other classes in the same
package will not be accessible. For this approach, there is no need to use
the import statement. But you will have to use the fully qualified name every time you are
accessing the class or the interface, which can look a little untidy if the package name is
long.

This is generally used when two packages have classes with same names. For
example: java.util and java.sql packages contain Date class.

Example :
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}

//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}

Output:

Hello

2. To import only the class/classes you want to use

If you import packagename.classname then only the class with name classname in the
package with name packagename will be available for use.

Example :
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.A;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}

Output:

Hello

3. To import all the classes from a particular package


If you use packagename.*, then all the classes and interfaces of this package will be
accessible but the classes and interface inside the subpackages will not be available for use.

The import keyword is used to make the classes and interface of another package accessible
to the current package.

Example :
//save by First.java
package learnjava;
public class First{
public void msg() {
System.out.println("Hello");
}
}

//save by Second.java
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}

Output:

Hello
Points to remember

 When a package name is not specified, the classes are defined into the default package (the
current working directory) and the package itself is given no name. That is why, you were
able to execute assignments earlier.
 While creating a package, care should be taken that the statement for creating package must
be written before any other import statements.

// not allowed
import package p1.*;
package p3;
Below code is correct, while the code mentioned above is incorrect.
//correct syntax
package p3;
import package p1.*;

Abstract class
If a class contain any abstract method then the class is declared as abstract class. An abstract
class is never instantiated. It is used to provide abstraction. Although it does not provide 100%
abstraction because it can also have concrete method.
Syntax :
abstract class class_name { }

Abstract method
Method that are declared without any body within an abstract class are called abstract method.
The method body will be defined by its subclass. Abstract method can never be final and static.
Any class that extends an abstract class must implement all the abstract methods declared by the
super class.
Syntax :
abstract return_type function_name (); //No definition
Example of Abstract class
abstract class A
{
abstract void callme();
}
class B extends A
{
void callme()
{
System.out.println("this is callme.");
}
public static void main(String[] args)
{
B b = new B();
b.callme();
}
}

this is callme.

Abstract class with concrete(normal) method.


Abstract classes can also have normal methods with definitions, along with abstract methods.
abstract class A
{
abstract void callme();
public void normal()
{
System.out.println("this is concrete method");
}
}
class B extends A
{
void callme()
{
System.out.println("this is callme.");
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.normal();
}
}

this is callme.
this is concrete method.

Points to Remember

1. Abstract classes are not Interfaces. They are different, we will study this when we will study
Interfaces.
2. An abstract class may or may not have an abstract method. But if any class has even a single
abstract method, then it must be declared abstract.
3. Abstract classes can have Constructors, Member variables and Normal methods.
4. Abstract classes are never instantiated.
5. When you extend Abstract class with abstract method, you must define the abstract method
in the child class, or make the child class abstract.
Abstraction using abstract class
Abstraction is an important feature of OOPS. It means hiding complexity. Abstract class is used
to provide abstraction. Although it does not provide 100% abstraction because it can also have
concrete method. Lets see how abstract class is used to provide abstraction.
abstract class Vehicle
{
public abstract void engine();
}
public class Car extends Vehicle {

public void engine()


{
System.out.println("Car engine");
//car engine implementation
}

public static void main(String[] args)


{
Vehicle v = new Car();
v.engine();
}
}

Car engine
Here by casting instance of Car type to Vehicle reference, we are hiding the complexity
of Car type under Vechicle. Now the Vehicle reference can be used to provide the
implementation but it will hide the actual implementation process.

When to use Abstract Methods & Abstract Class?


Abstract methods are usually declared where two or more subclasses are expected to do a similar
thing in different ways through different implementations. These subclasses extend the same
Abstract class and provide different implementations for the abstract methods.
Abstract classes are used to define generic types of behaviors at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of the
abstract class.

Interface
Interface is a pure abstract class.They are syntactically similar to classes, but you cannot create
instance of an Interface and their methods are declared without any body. Interface is used to
achieve complete abstraction in Java. When you create an interface it defines what a class can
do without saying anything about how the class will do it.
Syntax :
interface interface_name { }

Example of Interface
interface Moveable
{
int AVERAGE-SPEED=40;
void move();
}
NOTE : Compiler automatically converts methods of Interface as public and abstract, and the
data members as public, static and final by default.

Rules for using Interface

 Methods inside Interface must not be static, final, native or strictfp.


 All variables declared inside interface are implicitly public static final variables(constants).
 All methods declared inside Java Interfaces are implicitly public and abstract, even if you
don't use public or abstract keyword.
 Interface can extend one or more other interface.
 Interface cannot implement a class.
 Interface can be nested inside another interface.

Example of Interface implementation


interface Moveable
{
int AVG-SPEED = 40;
void move();
}

class Vehicle implements Moveable


{
public void move()
{
System .out. print in ("Average speed is"+AVG-SPEED");
}
public static void main (String[] arg)
{
Vehicle vc = new Vehicle();
vc.move();
}
}

Average speed is 40.

Interfaces supports Multiple Inheritance


Though classes in java doesn't suppost multiple inheritance, but a class can implement more than
one interface.
interface Moveable
{
boolean isMoveable();
}

interface Rollable
{
boolean isRollable
}

class Tyre implements Moveable, Rollable


{
int width;

boolean isMoveable()
{
return true;
}

boolean isRollable()
{
return true;
}
public static void main(String args[])
{
Tyre tr=new Tyre();
System.out.println(tr.isMoveable());
System.out.println(tr.isRollable());
}
}

true
true

Interface extends other Interface


Classes implements interfaces, but an interface extends other interface.
interface NewsPaper
{
news();
}

interface Magazine extends NewsPaper


{
colorful();
}

Difference between an interface and an abstract class?

Abstract class Interface

Abstract class is a class which contain one or Interface is a Java Object containing method
more abstract methods, which has to be declaration but no implementation. The classes
implemented by its sub classes. which implement the Interfaces must provide the
method definition for all the methods.
Abstract class Interface

Abstract class is a Class prefix with an Interface is a pure abstract class which starts with
abstract keyword followed by Class interface keyword.
definition.

Abstract class can also contain concrete Whereas, Interface contains all abstract methods and
methods. final variable declarations.

Abstract classes are useful in a situation that Interfaces are useful in a situation that all properties
Some general methods should be should be implemented.
implemented and specialization behavior
should be implemented by child classes.

Nested Class
A class defined within another class is known as Nested class. The scope of the nested class is
bounded by the scope of its enclosing class.
Syntax:
class Outer{
//class Outer members

class Inner{
//class Inner members
}

} //closing of class Outer


Advantages of Nested Class

1. It is a way of logically grouping classes that are only used in one place.
2. It increases encapsulation.
3. It can lead to more readable and maintainable code.

If you want to create a class which is to be used only by the enclosing class, then it is not
necessary to create a separate file for that. Instead, you can add it as "Inner Class"

Static Nested Class


If the nested class i.e the class defined within another class, has static modifier applied in it, then
it is called as static nested class. Since it is, static nested classes can access only static members
of its outer class i.e it cannot refer to non-static members of its enclosing class directly. Because
of this restriction, static nested class is rarely used.

Non-static Nested class


Non-static Nested class is the most important type of nested class. It is also known as Inner
class. It has access to all variables and methods of Outer class including its private data members
and methods and may refer to them directly. But the reverse is not true, that is, Outer class
cannot directly access members of Inner class. Inner class can be declared private, public,
protected, or with default access whereas an Outer class can have only public or default access.
One more important thing to notice about an Inner class is that it can be created only within the
scope of Outer class. Java compiler generates an error if any code outside Outer class attempts to
instantiate Inner class directly.

A non-static Nested class that is created outside a method is called Member inner class.
A non-static Nested class that is created inside a method is called local inner class. If you want
to invoke the methods of local inner class, you must instantiate this class inside the method. We
cannot use private, public or protected access modifiers with local inner class. Only abstract and
final modifiers are allowed.

Example of Inner class(Member class)


class Outer
{
public void display()
{
Inner in=new Inner();
in.show();
}

class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}
}

class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}

Inside inner

Example of Inner class inside a method(local inner class)


class Outer
{
int count;
public void display()
{
for(int i=0;i<5;i++)
{
class Inner <font color="green">//Inner class defined inside for loop</font>
{
public void show()
{
System.out.println("Inside inner "+(count++));
}
}
Inner in=new Inner();
in.show();
}
}
}

class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}

Inside inner 0
Inside inner 1
Inside inner 2
Inside inner 3
Inside inner 4

Example of Inner class instantiated outside Outer class


class Outer
{
int count;
public void display()
{
Inner in=new Inner();
in.show();
}
class Inner
{
public void show()
{
System.out.println("Inside inner "+(++count));
}
}
}

class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
Outer.Inner in= ot.new Inner();
in.show();
}
}

Inside inner 1

Annonymous class
A class without any name is called Annonymous class.
interface Animal
{
void type();
}
public class ATest {
public static void main(String args[])
{
Animal an = new Animal(){ //Annonymous class created
public void type()
{
System.out.println("Annonymous animal");
}
};
an.type();
}
}

Annonymous animal
Here a class is created which implements Animal interace and its name will be decided by the
compiler. This annonymous class will provide implementation of type() method.

Introduction to String Handling


String is probably the most commonly used class in java library. String class is encapsulated
under java.lang package. In java, every string that you create is actually an object of type String.
One important thing to notice about string object is that string objects are immutable that means
once a string object is created it cannot be altered.

What is an Immutable object?


An object whose state cannot be changed after it is created is known as an Immutable object.
String, Integer, Byte, Short, Float, Double and all other wrapper classes objects are immutable.

Creating an Immutable class


public final class MyString
{
final String str;
MyString(String s)
{
this.str = s;
}
public String get()
{
return str;
}
}
In this example MyString is an immutable class. MyString's state cannot be changed once it is
created.

Creating a String object


String can be created in number of ways, here are a few ways of creating string object.
1) Using a String literal
String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String
object.
String str1 = "Hello";

2) Using another String object


String str2 = new String(str1);

3) Using new Keyword


String str3 = new String("Java");

4) Using + operator (Concatenation)


String str4 = str1 + str2;
or,
String str5 = "hello"+"Java";
Each time you create a String literal, the JVM checks the string pool first. If the string literal
already exists in the pool, a reference to the pool instance is returned. If string does not exist in
the pool, a new string object is created, and is placed in the pool. String objects are stored in a
special memory area known as string constant pool inside the heap memory.

String object and How they are stored


When we create a new string object using string literal, that string literal is added to the string
pool, if it is not present there already.
String str= "Hello";

And, when we create another object with same string, then a reference of the string literal already
present in string pool is returned.
String str2=str;
But if we change the new string, its reference gets modified.
str2=str2.concat("world");
Concatenating String
There are 2 methods to concatenate two or more string.

1. Using concat() method


2. Using + operator

1) Using concat() method


string s = "Hello";
string str = "Java";
string str2 = s.concat(str);
String str1 = "Hello".concat("Java"); //works with string literals too.

2) Using + operator
string str = "Rahul";
string str1 = "Dravid";
string str2 = str + str1;
string st = "Rahul"+"Dravid";

String Comparison
String comparison can be done in 3 ways.

1. Using equals() method


2. Using == operator
3. By CompareTo() method

Using equals() method


equals() method compares two strings for equality. Its general syntax is,
boolean equals (Object str)
It compares the content of the strings. It will return true if string matches, else returns false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2); //true
s.equals(s1) ; //false

Using == operator
== operator compares two object references to check whether they refer to same instance. This
also, will return true on successful match.
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(s1 == s2) //true
test(s1 == s3) //false
Reason:
Its because we are creating a new object using new operator, and thus it gets created in a non-
pool memory area of the heap. s1 is pointing to the String in string pool while s3 is pointing to
the String in heap and hence, when we compare s1 and s3, the answer is false.
The following image will explain it more clearly.
By compareTo() method
compareTo() method compares values and returns an int which tells if the string compared is less
than, equal to or greater than the other string. It compares the String based on natural ordering i.e
alphabetically. Its general syntax is,
int compareTo(String str)
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
s1.compareTo(S2); //return -1 because s1 < s2
s1.compareTo(S3); //return 0 because s1 == s3
s2.compareTo(s1); //return 1 because s2 > s1

String class function


The following methods are some of the most commonly used methods of String class.
charAt()
charAt() function returns the character located at the specified index.
String str = "studytonight";
System.out.println(str.charAt(2));
Output: u
NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of the String
str.

equalsIgnoreCase()
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower
case doesn't matters with this fuction ).
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));

true
indexOf()
indexOf() function returns the index of first occurrence of a substring or a
character. indexOf()method has four forms:

 int indexOf(String str): It returns the index within this string of the first occurrence of the
specified substring.
 int indexOf(int ch, int fromIndex): It returns the index within this string of the first
occurrence of the specified character, starting the search at the specified index.
 int indexOf(int ch): It returns the index within this string of the first occurrence of the
specified character.
 int indexOf(String str, int fromIndex): It returns the index within this string of the first
occurrence of the specified substring, starting at the specified index.

Example:
public class StudyTonight {
public static void main(String[] args) {
String str="StudyTonight";
System.out.println(str.indexOf('u')); //3rd form
System.out.println(str.indexOf('t', 3)); //2nd form
String subString="Ton";
System.out.println(str.indexOf(subString)); //1st form
System.out.println(str.indexOf(subString,7)); //4th form
}
}

2
11
5
-1
NOTE: -1 indicates that the substring/Character is not found in the given String.
length()
length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());

replace()
replace() method replaces occurances of character with a specified new character.
String str = "Change me";
System.out.println(str.replace('m','M'));

Change Me

substring()
substring() method returns a part of the string. substring() method has two forms,
public String substring(int begin);

public String substring(int begin, int end);


/*
character of begin index is inclusive and character of end index is exclusive.
*/
The first argument represents the starting point of the subtring. If the substring() method is called
with only one argument, the subtring returned, will contain characters from specified starting
point to the end of original string.
But, if the call to substring() method has two arguments, the second argument specify the end
point of substring.
String str = "0123456789";
System.out.println(str.substring(4));
456789
System.out.println(str.substring(4,7));

456

toLowerCase()
toLowerCase() method returns string with all uppercase characters converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());

abcdef

toUpperCase()
This method returns string with all lowercase character changed to uppercase.
String str = "abcdef";
System.out.println(str.toUpperCase());

ABCDEF

valueOf()
Overloaded version of valueOf() method is present in String class for all primitive data types and
for type Object.
NOTE: valueOf() function is used to convert primitive data types into Strings.
public class Example{
public static void main(String args[]){
int num = 35;
String s1 = String.valueOf(num); //converting int to String
System.out.println(s1+"IAmAString");
}
}

35IAmAString
But for objects, valueOf() method calls toString() function.

toString()
toString() method returns the string representation of the object used to invoke this
method. toString() is used to represent any Java Object into a meaningful string representation. It
is declared in the Object class, hence can be overrided by any java class. (Object class is super
class of all java classes.)
public class Car {
public static void main(String args[])
{
Car c = new Car();
System.out.println(c);
}
public String toString()
{
return "This is my car object";
}
}

This is my car object


Whenever we will try to print any object of class Car, its toString() function will be called.
toString() can also be used with normal string objects.
String str = "Hello World";
System.out.println(str.toString());

Hello World
NOTE: If we don't override the toString() method and directly print the object, then it would
print the object id.
Example:
public class Car {
public static void main(String args[])
{
Car c = new Car();
System.out.println(c);
}
}

studytonight.Car@15db9742 (here studytonight is a user-defined package).

toString() with Concatenation


Whenever we concatenate any other primitive data type, or object of other classes with a String
object, toString() function or valueOf() function is called automatically to change the other
object or primitive type into string, for successful concatenation.
int age = 10;
String str = "He is" + age + "years old.";
In above case 10 will be automatically converted into string for concatenation
using valueOf()function.

trim()
This method returns a string from which any leading and trailing whitespaces has been removed.
String str = " hello ";
System.out.println(str.trim());

hello
NOTE: If the whitespaces are between the string, for example: String s1 = "study
tonight"; then System.out.println(s1.trim()); will output "study tonight".
trim() method removes only the leading and trailing whitespaces.
StringBuffer class
StringBuffer class is used to create a mutable string object i.e its state can be changed after it is
created. It represents growable and writable character sequence. As we know that String objects
are immutable, so if we do a lot of changes with String objects, we will end up with a lot of
memory leak.
So StringBuffer class is used when we have to make lot of modifications to our string. It is also
thread safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4
constructors. They are,

1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )

 StringBuffer() creates an empty string buffer and reserves room for 16 characters.
 stringBuffer(int size) creates an empty string and takes an integer argument to set capacity of
the buffer.

Example showing difference between String and StringBuffer


class Test {
public static void main(String args[])
{
String str = "study";
str.concat("tonight");
System.out.println(str); // Output: study

StringBuffer strB = new StringBuffer("study");


strB.append("tonight");
System.out.println(strB); // Output: studytonight
}
}
Reason:
Output is such because String objects are immutable objects. Hence, if we concatenate on the
same String object, it won't be altered(Output: study). But StringBuffer creates mutable objects.
Hence, it can be altered(Output: studytonight)

Important methods of StringBuffer class


The following methods are some most commonly used methods of StringBuffer class.
append()
This method will concatenate the string representation of any type of data to the end of the
invoking StringBuffer object. append() method has several overloaded forms.
StringBuffer append(String str)

StringBuffer append(int n)

StringBuffer append(Object obj)


The string representation of each parameter is appended to StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.append(123);
System.out.println(str);

test123

insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)

StringBuffer insert(int index, int num)

StringBuffer insert(int index, Object obj)


Here the first parameter gives the index at which position the string will be inserted and string
representation of second parameter is inserted into StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.insert(4, 123);
System.out.println(str);

test123

reverse()
This method reverses the characters within a StringBuffer object.
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);

olleH

replace()
This method replaces the string from specified start index to the end index.
<

StringBuffer str = new StringBuffer("Hello World");


str.replace( 6, 11, "java");
System.out.println(str);

Hello java

capacity()
This method returns the current capacity of StringBuffer object.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );
16
Note: Empty constructor reserves space for 16 characters. Therefore the output is 16.

ensureCapacity()
This method is used to ensure minimum capacity of StringBuffer object.
If the argument of the ensureCapacity() method is less than the existing capacity, then there will
be no change in existing capacity.
If the argument of the ensureCapacity() method is greater than the existing capacity, then there
will be change in the current capacity using following rule: newCapacity = (oldCapacity*2) +
2.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity()); //output: 16 (since empty constructor reserves space for 16
characters)
str.ensureCapacity(30); //greater than the existing capacity
System.out.println( str.capacity()); //output: 34 (by following the rule - (oldcapacity*2) + 2.) i.e
(16*2)+2 = 34.

StringBuilder class
StringBuilder is identical to StringBuffer except for one important difference that it is not
synchronized, which means it is not thread safe. Its because StringBuilder methods are not
synchronised.

StringBuilder Constructors

1. StringBuilder ( ), creates an empty StringBuilder and reserves room for 16 characters.


2. StringBuilder ( int size ), create an empty string and takes an integer argument to set
capacity of the buffer.
3. StringBuilder ( String str ), create a StringBuilder object and initialize it with string str.
Difference between StringBuffer and StringBuilder class

StringBuffer class StringBuilder class

StringBuffer is synchronized. StringBuilder is not


synchronized.

Because of synchronisation, StringBuffer operation is slower than StringBuilder operates faster.


StringBuilder.

Example of StringBuilder
class Test {
public static void main(String args[])
{
StringBuilder str = new StringBuilder("study");
str.append( "tonight" );
System.out.println(str);
str.replace( 6, 13, "today");
System.out.println(str);
str.reverse();
System.out.println(str);
str.replace( 6, 13, "today");
}
}

studytonight
studyttoday
yadottyduts

Exception Handling
Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such
exceptions to prevent abrupt termination of program. The term exception means exceptional
condition, it is a problem that may arise during the execution of program. A bunch of things can
lead to exceptions, including programmer error, hardware failures, files that need to be opened
cannot be found, resource exhaustion etc.

Exception
A Java Exception is an object that describes the exception that occurs in a program. When an
exceptional events occurs in java, an exception is said to be thrown. The code that's responsible
for doing something about the exception is called an exception handler.

Exception class Hierarchy


All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.

 Exception class is for exceptional conditions that program should catch. This class is
extended to create user specific exception classes.
 RuntimeException is a subclass of Exception. Exceptions under this class are automatically
defined for programs.
 Exceptions of type Error are used by the Java run-time system to indicate errors having to
do with the run-time environment, itself. Stack overflow is an example of such an error.

Exception are categorized into 3 category.

 Checked Exception

The exception that can be predicted by the programmer at the compile time.Example : File
that need to be opened is not found. These type of exceptions must be checked at compile
time.

 Unchecked Exception

Unchecked exceptions are the class that extends RuntimeException. Unchecked exception
are ignored at compile time. Example : ArithmeticException, NullPointerException, Array
Index out of Bound exception. Unchecked exceptions are checked at runtime.

 Error

Errors are typically ignored in code because you can rarely do anything about an
error. Example :if stack overflow occurs, an error will arise. This type of error cannot be
handled in the code.

Uncaught Exceptions
When we don't handle the exceptions, they lead to unexpected program termination. Lets take an
example for better understanding.
class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a; // Divide by zero, will lead to exception
}
}
This will lead to an exception at runtime, hence the Java run-time system will construct an
exception and then throw it. As we don't have any mechanism for handling exception in the
above program, hence the default handler will handle the exception and will print the details of
the exception on the terminal.

Exception Handling Mechanism


In java, exception handling is done using five keywords,

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

Exception handling is done by transferring the execution of a program to an appropriate


exception handler when exception occurs.

Using try and catch


Try is used to guard a block of code in which exception may occur. This block of code is called
guarded region. A catch statement involves declaring the type of exception you are trying to
catch. If an exception occurs in guarded code, the catch block that follows the try is checked, if
the type of exception that occured is listed in the catch block then the exception is handed over to
the catch block which then handles it.
Example using Try and catch
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}

Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero
inside try block. The program control is transferred outside try block. Thus the line "This line
will not be executed" is never parsed by the compiler. The exception thrown is handled
in catch block. Once the exception is handled, the program control is continue with the next line
in the program i.e after catch block. Thus the line "After exception is handled" is printed.

Multiple catch blocks:


A try block can be followed by multiple catch blocks. You can have any number of catch blocks
after a single try block.If an exception occurs in the guarded code the exception is passed to the
first catch block in the list. If the exception type of exception, matches with the first catch block
it gets caught, if not the exception is passed down to the next catch block. This continue until the
exception is caught or falls through all catches.

Example for Multiple Catch blocks


class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}

divide by zero
Note: Although both ArrayIndexOutOfBoundsException and ArithmeticException occured, but
since first catch is of Arithmetic Exception, It will be caught there and program control will be
continued after the catch block.
Note: At a time, only one exception is processed and only one respective catch block is
executed.
Example for Unreachable Catch block
While using multiple catch statements, it is important to remember that sub classes of class
Exception inside catch must come before any of their super classes otherwise it will lead to
compile time error. This is because in Java, if any code is unreachable, then it gives compile time
error.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(Exception e) //This block handles all Exception
{
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
{
System.out.println("array index out of bound exception");
}
}
}

Generic exception

Nested try statement


try statement can be nested inside another block of try. Nested try block is used when a part of a
block may cause one error while entire block may cause another error. In case if inner try block
does not have a catch handler for a particular exception then the outer try catch block is
checked for match.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x=arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}

divide by zero
array index out of bound exception

Important points to Remember

1. If you do not explicitly use the try catch blocks in your program, java will provide a default
exception handler, which will print the exception details on the terminal, whenever exception
occurs.
2. Super class Throwable overrides toString() function, to display error message in form of
string.
3. While using multiple catch block, always make sure that sub-classes of Exception class
comes before any of their super classes. Else you will get compile time error.
4. In nested try catch, the inner try block uses its own catch block as well as catch block of the
outer try, if required.
5. Only the object of Throwable class or its subclasses can be thrown.

Try with Resource Statement


JDK 7 introduces a new version of try statement known as try-with-resources statement. This
feature add another way to exception handling with resources management. It is also referred to
as automatic resource management.
Syntax
try(resource-specification(there can be more than one resource))
{
//use the resource
}catch()
{...}
This try statement contains a parenthesis in which one or more resources is declared. Any
object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed as a
parameter to try statement. A resource is an object that is used in program and must be closed
after the program is finished. The try-with-resources statement ensures that each resource is
closed at the end of the statement of the try block. You do not have to explicitly close the
resources.

Example without using try with Resource Statement


import java.io.*;
class Test
{
public static void main(String[] args)
{
try{
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt"));
while((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close(); //closing BufferedReader stream
}catch(IOException ie)
{ System.out.println("exception"); }
}
}

Example using try with Resource Statement


import java.io.*;
class Test
{
public static void main(String[] args)
{
try(BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt")))
{
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
}catch(IOException ie)
{ System.out.println("exception"); }
}
}
NOTE: In the above example, we do not need to explicitly call close() method to
close BufferedReader stream.
Points to Remember

1. A resource is an object in a program that must be closed after the program has finished.
2. Any object that implements java.lang.AutoCloseable or java.io.Closeable can be passed as a
parameter to try statement.
3. All the resources declared in the try-with-resources statement will be closed automatically
when the try block exits. There is no need to close it explicitly.
4. We can write more than one resources in the try statement.
5. In a try-with-resources statement, any catch or finally block is run after the resources
declared have been closed.

throw Keyword
throw keyword is used to throw an exception explicitly. Only object of Throwable class or its
sub classes can be thrown. Program execution stops on encountering throw statement, and the
closest catch statement is checked for matching type of exception.
Syntax :
throw ThrowableInstance

Creating Instance of Throwable class


There are two possible ways to create an instance of class Throwable,

1. Using a parameter in catch block.


2. Creating instance with new operator.

new NullPointerException("test");

This constructs an instance of NullPointerException with name test.


Example demonstrating throw Keyword
class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}

public static void main(String args[])


{
avg();
}
}
In the above example the avg() method throw an instance of ArithmeticException, which is
successfully handled using the catch statement and thus, the program outputs "Exception
caught".

throws Keyword
Any method that is capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions are
to be handled. A method can do so by using the throws keyword.
Syntax :
type method_name(parameter_list) throws exception_list
{
//definition of method
}

Example demonstrating throws Keyword


class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}

public static void main(String args[])


{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}

Inside check function


caughtjava.lang.ArithmeticException: demo

Difference between throw and throws


throw throws
throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.

throw keyword is followed by an instance of throws keyword is followed by one or more


Throwable class or one of its sub-classes. Exception class names separated by commas.

throw keyword is declared inside a method throws keyword is used with method signature
body. (method declaration).

We cannot throw multiple exceptions using We can declare multiple exceptions (separated by
throw keyword. commas) using throws keyword.

finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of
code is always executed whether an exception has occurred or not. Using a finally block, it lets
you run any cleanup type statements that you want to execute, no matter what happens in the
protected code. A finally block appears at the end of catch block.
Example demonstrating finally Clause
Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}

Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound exception.
You can see in above example even if exception is thrown by the program, which is not handled
by catch block, still finally block will get executed.

User defined Exception subclass


You can also create your own exception sub class simply by extending java Exception class.
You can define a constructor for your Exception sub class (not compulsory) and you can
override the toString() function to display your customized message on catch.
class MyException extends Exception
{
private int ex;
MyException(int a)
{
ex=a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}

class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception class
}
else
{
System.out.println(a+b);
}
}

public static void main(String[] args)


{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); //it calls the toString() method of user-defined Exception
}
}
}

MyException[-10] is less than zero

Points to Remember

1. Extend the Exception class to create your own exception class.


2. You don't have to implement anything inside it, no methods are required.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.

Method Overriding with Exception Handling


There are few things to remember when overriding a method with exception handling. If super
class method does not declare any exception, then sub class overriden method cannot declare
checked exception but it can declare unchecked exceptions.

Example of Subclass overriden Method declaring Checked Exception


import java.io.*;
class Super
{
void show() { System.out.println("parent class"); }
}

public class Sub extends Super


{
void show() throws IOException //Compile time error
{ System.out.println("parent class"); }

public static void main( String[] args )


{
Super s=new Sub();
s.show();
}
}
As the method show() doesn't throw any exception while in Super class, hence its overridden
version also cannot throw any checked exception.

Example of Subclass overriden Method declaring Unchecked Exception


import java.io.*;
class Super
{
void show(){ System.out.println("parent class"); }
}
public class Sub extends Super
{
void show() throws ArrayIndexOutOfBoundsException //Correct
{ System.out.println("child class"); }

public static void main(String[] args)


{
Super s=new Sub();
s.show();
}
}

child class
Because ArrayIndexOutOfBoundsException is an unchecked exception hence,
overrided show()method can throw it.

More about Overriden Methods and Exceptions


If Super class method throws an exception, then Subclass overriden method can throw the same
exception or no exception, but must not throw parent exception of the exception thrown by Super
class method.
It means, if Super class method throws object of NullPointerException class, then Subclass
method can either throw same exception, or can throw no exception, but it can never throw
object of Exception class (parent of NullPointerException class).

Example of Subclass overriden method with same Exception


import java.io.*;
class Super
{
void show() throws Exception
{ System.out.println("parent class"); }
}

public class Sub extends Super {


void show() throws Exception //Correct
{ System.out.println("child class"); }

public static void main(String[] args)


{
try {
Super s=new Sub();
s.show();
}
catch(Exception e){}
}
}

child class

Example of Subclass overriden method with no Exception


import java.io.*;
class Super
{
void show() throws Exception
{ System.out.println("parent class"); }
}

public class Sub extends Super {


void show() //Correct
{ System.out.println("child class"); }

public static void main(String[] args)


{
try {
Super s=new Sub();
s.show();
}
catch(Exception e){}
}
}

child class

Example of Subclass overriden method with parent Exception


import java.io.*;
class Super
{
void show() throws ArithmeticException
{ System.out.println("parent class"); }
}

public class Sub extends Super {


void show() throws Exception //Cmpile time Error
{ System.out.println("child class"); }

public static void main(String[] args)


{
try {
Super s=new Sub();
s.show();
}
catch(Exception e){}
}
}

Chained Exception
Chained Exception was added to Java in JDK 1.4. This feature allow you to relate one exception
with another exception, i.e one exception describes cause of another exception. For example,
consider a situation in which a method throws an ArithmeticException because of an attempt to
divide by zero but the actual cause of exception was an I/O error which caused the divisor to be
zero. The method will throw only ArithmeticException to the caller. So the caller would not
come to know about the actual cause of exception. Chained Exception is used in such type of
situations.
Two new constructors and two new methods were added to Throwable class to support chained
exception.

1. Throwable( Throwable cause )


2. Throwable( String str, Throwable cause )

In the first form, the paramter cause specifies the actual cause of exception. In the second form,
it allows us to add an exception description in string form with the actual cause of exception.
getCause() and initCause() are the two methods added to Throwable class.

 getCause() method returns the actual cause associated with current exception.
 initCause() set an underlying cause(exception) with invoking exception.

Example
import java.io.IOException;
public class ChainedException
{
public static void divide(int a, int b)
{
if(b==0)
{
ArithmeticException ae = new ArithmeticException("top layer");
ae.initCause( new IOException("cause") );
throw ae;
}
else
{
System.out.println(a/b);
}
}

public static void main(String[] args)


{
try {
divide(5, 0);
}
catch(ArithmeticException ae) {
System.out.println( "caught : " +ae);
System.out.println("actual cause: "+ae.getCause());
}
}
}

caught:java.lang.ArithmeticException: top layer


actual cause: java.io.IOException: cause

Introduction to Multithreading
A program can be divided into a number of small processes. Each small process can be
addressed as a single thread (a lightweight process). You can think of a lightweight process as a
virtual CPU that executes code or system calls. You usually do not need to concern yourself with
lightweight processes to program with threads. Multithreaded programs contain two or more
threads that can run concurrently and each thread defines a separate path of execution. This
means that a single program can perform two or more tasks simultaneously. For example, one
thread is writing content on a file at the same time another thread is performing spelling check.
In Java, the word thread means two different things.

 An instance of Thread class.


 or, A thread of execution.
An instance of Thread class is just an object, like any other object in java. But a thread of
execution means an individual "lightweight" process that has its own call stack. In java each
thread has its own call stack.

The main thread


When we run any java program, the program begins to execute its code starting from the main
method. Therefore, the JVM creates a thread to start executing the code present in main method.
This thread is called as main thread. Although the main thread is automatically created, you can
control it by obtaining a reference to it by calling currentThread() method.
Two important things to know about main thread are,

 It is the thread from which other threads will be produced.


 main thread must be always the last thread to finish execution.

class MainThread
{
public static void main(String[] args)
{
Thread t=Thread.currentThread();
t.setName("MainThread");
System.out.println("Name of thread is "+t);
}
}
Name of thread is Thread[MainThread,5,main]

Life cycle of a Thread

1. New : A thread begins its life cycle in the new state. It remains in this state until the start()
method is called on it.
2. Runnable : After invocation of start() method on new thread, the thread becomes runnable.
3. Running : A thread is in running state if the thread scheduler has selected it.
4. Waiting : A thread is in waiting state if it waits for another thread to perform a task. In this
stage the thread is still alive.
5. Terminated : A thread enter the terminated state when it complete its task.

Thread Priorities
Every thread has a priority that helps the operating system determine the order in which threads
are scheduled for execution. In java thread priority ranges between 1 to 10,
 MIN-PRIORITY (a constant of 1)
 MAX-PRIORITY (a constant of 10)

By default every thread is given a NORM-PRIORITY(5). The main thread always have NORM-
PRIORITY.
Note: Thread priorities cannot guarantee that a higher priority thread will always be executed
first than the lower priority thread. The selection of the threads for execution depends upon the
thread scheduler which is platform dependent.

Thread Class
Thread class is the main class on which Java's Multithreading system is based. Thread class,
along with its companion interface Runnable will be used to create and run threads for utilizing
Multithreading feature of Java.

Constructors of Thread class

1. Thread ( )
2. Thread ( String str )
3. Thread ( Runnable r )
4. Thread ( Runnable r, String str)

You can create new thread, either by extending Thread class or by implementing Runnable
interface. Thread class also defines many methods for managing threads. Some of them are,

Method Description

setName() to give thread a name

getName() return thread's name

getPriority() return thread's priority


Method Description

isAlive() checks if thread is still running or not

join() Wait for a thread to end

run() Entry point for a thread

sleep() suspend thread for a specified time

start() start a thread by calling run() method

Some Important points to Remember

1. When we extend Thread class, we cannot override setName() and getName() functions,
because they are declared final in Thread class.
2. While using sleep(), always handle the exception it throws.

static void sleep(long milliseconds) throws InterruptedException

Creating a thread
Java defines two ways by which a thread can be created.

 By implementing the Runnable interface.


 By extending the Thread class.
Implementing the Runnable Interface
The easiest way to create a thread is to create a class that implements the runnable interface.
After implementing runnable interface , the class needs to implement the run() method, which is
of form,
public void run()

 run() method introduces a concurrent thread into your program. This thread will end when
run() method terminates.
 You must specify the code that your thread will execute inside run() method.
 run() method can call other methods, can use other classes and declare variables just like any
other normal method.

class MyThread implements Runnable


{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

class MyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}

concurrent thread started running..


To call the run() method, start() method is used. On calling start(), a new stack is provided to
the thread and run() method is called to introduce the new thread into the program.
Note: If you are implementing Runnable interface in your class, then you need to explicitly
create a Thread class object and need to pass the Runnable interface implemented class object as
a parameter in its constructor.

Extending Thread class


This is another way to create a thread by a new class that extends Thread class and create an
instance of that class. The extending class must override run() method which is the entry point
of new thread.
class MyThread extends Thread
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

classMyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
}
}

concurrent thread started running..


In this case also, we must override the run() and then use the start() method to run the thread.
Also, when you create MyThread class object, Thread class constructor will also be invoked, as
it is the super class, hence MyThread class object acts as Thread class object.
What if we call run() method directly without using start() method ?
In above program if we directly call run() method, without using start() method,
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.run();
}
Doing so, the thread won't be allocated a new call stack, and it will start running in the current
call stack, that is the call stack of the main thread. Hence Multithreading won't be there.

Can we Start a thread twice ?


No, a thread cannot be started twice. If you try to do so, IllegalThreadStateException will be
thrown.
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
mt.start(); //Exception thrown
}
When a thread is in running state, and you try to start it again, or any method try to invoke that
thread again using start() method, exception is thrown.

Joining threads
Sometimes one thread needs to know when other thread is terminating. In
java, isAlive() and join()are two different methods that are used to check whether a thread has
finished its execution or not.
The isAlive() method returns true if the thread upon which it is called is still running otherwise
it returns false.
final boolean isAlive()
But, join() method is used more commonly than isAlive(). This method waits until the thread on
which it is called terminates.
final void join() throws InterruptedException
Using join() method, we tell our thread to wait until the specified thread completes its execution.
There are overloaded versions of join() method, which allows us to specify time for which you
want to wait for the specified thread to terminate.
final void join(long milliseconds) throws InterruptedException
As we have seen in the Introduction to MultiThreading, the main thread must always be the last
thread to finish its execution. Therefore, we can use Thread join() method to ensure that all the
threads created by the program has been terminated before the execution of the main thread.

Example of isAlive method


public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie) { }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}

r1
true
true
r1
r2
r2

Example of thread without join() method


public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie){ }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}

r1
r1
r2
r2
In this above program two thread t1 and t2 are created. t1 starts first and after printing "r1" on
console thread t1 goes to sleep for 500 ms. At the same time Thread t2 will start its process and
print "r1" on console and then go into sleep for 500 ms. Thread t1 will wake up from sleep and
print "r2" on console similarly thread t2 will wake up from sleep and print "r2" on console. So
you will get output like r1 r1 r2 r2

Example of thread with join() method


public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}catch(InterruptedException ie){ }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();

try{
t1.join(); //Waiting for t1 to finish
}catch(InterruptedException ie){}

t2.start();
}
}

r1
r2
r1
r2
In this above program join() method on thread t1 ensures that t1 finishes it process before thread
t2 starts.

Specifying time with join()


If in the above program, we specify time while using join() with t1, then t1 will execute for that
time, and then t2 will join it.
t1.join(1500);
Doing so, initially t1 will execute for 1.5 seconds, after which t2 will join it.

Synchronization
At times when more than one thread try to access a shared resource, we need to ensure that
resource will be used by only one thread at a time. The process by which this is achieved is
called synchronization. The synchronization keyword in java creates a block of code referred to
as critical section.
General Syntax :
synchronized (object)
{
//statement to be synchronized
}
Every Java object with a critical section of code gets a lock associated with the object. To enter
critical section a thread need to obtain the corresponding object's lock.

Why we use Syncronization ?


If we do not use syncronization, and let two or more threads access a shared resource at the same
time, it will lead to distorted results.
Consider an example, Suppose we have two different threads T1 and T2, T1 starts execution and
save certain values in a file temporary.txt which will be used to calculate some result when T1
returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved by T1 in the file
temporary.txt (temporary.txt is the shared resource). Now obviously T1 will return wrong result.
To prevent such problems, synchronization was introduced. With synchronization in above case,
once T1 starts using temporary.txt file, this file will be locked(LOCK mode), and no other thread
will be able to access or modify it until T1 returns.

Using Synchronized Methods


Using Synchronized methods is a way to accomplish synchronization. But lets first see what
happens when we do not use synchronization in our program.

Example with no Synchronization


class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}

class Second extends Thread


{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
fobj.display(msg);
}
}

public class Syncro


{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second (fnew,"new");
Second ss2 = new Second(fnew, "programmer");
}
}
[welcome [ new [ programmer]
]
]
In the above program, object fnew of class First is shared by all the three running threads(ss, ss1
and ss2) to call the shared method(void display). Hence the result is unsynchronized and such
situation is called Race condition.

Synchronized Keyword
To synchronize above program, we must synchronize access to the shared display() method,
making it available to only one thread at a time. This is done by using
keyword synchronized with display() method.
synchronized void display (String msg)

Using Synchronized block


If you have to synchronize access to an object of a class or you only want a part of a method to
be synchronized to an object then you can use synchronized block for it.
class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}

class Second extends Thread


{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
synchronized(fobj) //Synchronized block
{
fobj.display(msg);
}
}
}

public class Syncro


{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second (fnew,"new");
Second ss2 = new Second(fnew, "programmer");
}
}
[welcome]
[new]
[programmer]
Because of synchronized block this program gives the expected output.

Difference between synchronized keyword and synchronized block


When we use synchronized keyword with a method, it acquires a lock in the object for the whole
method. It means that no other thread can use any synchronized method until the current thread,
which has invoked it's synchronized method, has finished its execution.
synchronized block acquires a lock in the object only between parentheses after the synchronized
keyword. This means that no other thread can acquire a lock on the locked object until the
synchronized block exits. But other threads can access the rest of the code of the method.

Which is more preferred - Synchronized method or Synchronized block?


In Java, synchronized keyword causes a performance cost. A synchronized method in Java is
very slow and can degrade performance. So we must use synchronization keyword in java when
it is necessary else, we should use Java synchronized block that is used for synchronizing critical
section only.

Interthread Communication
Java provide benefits of avoiding thread pooling using inter-thread communication.
The wait(), notify(), and notifyAll() methods of Object class are used for this purpose. These
method are implemented as final methods in Object, so that all classes have them. All the three
method can be called only from within a synchronized context.

 wait() tells calling thread to give up monitor and go to sleep until some other thread enters
the same monitor and call notify.
 notify() wakes up a thread that called wait() on same object.
 notifyAll() wakes up all the thread that called wait() on same object.
Difference between wait() and sleep()

wait() sleep()

called from synchronised block no such requirement

monitor is released monitor is not released

gets awake when notify() or notifyAll() does not get awake when notify() or notifyAll()
method is called. method is called

not a static method static method

wait() is generaly used on condition sleep() method is simply used to put your thread on
sleep.

Thread Pooling
Pooling is usually implemented by loop i.e to check some condition repeatedly. Once condition
is true appropriate action is taken. This waste CPU time.
Deadlock

Deadlock is a situation of complete Lock, when no thread can complete its execution because
lack of resources. In the above picture, Thread 1 is holding a resource R1, and need another
resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is
locked by Thread 3. Hence none of them can finish and are stuck in a deadlock.

Example of deadlock
class Pen{}
class Paper{}

public class Write {

public static void main(String[] args)


{
final Pen pn =new Pen();
final Paper pr =new Paper();

Thread t1 = new Thread(){


public void run()
{
synchronized(pn)
{
System.out.println("Thread1 is holding Pen");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
synchronized(pr)
{ System.out.println("Requesting for Paper"); }

}
}
};
Thread t2 = new Thread(){
public void run()
{
synchronized(pr)
{
System.out.println("Thread2 is holding Paper");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
synchronized(pn)
{ System.out.println("requesting for Pen"); }

}
}
};

t1.start();
t2.start();
}

}
Thread1 is holding Pen
Thread2 is holding Paper
For more details, visit the following: Deadlocks

Enumerations
Enumerations was added to Java language in JDK5. Enumeration means a list of named
constant. In Java, enumeration defines a class type. An Enumeration can have constructors,
methods and instance variables. It is created using enum keyword. Each enumeration constant
is public, static and final by default. Even though enumeration defines a class type and have
constructors, you do not instantiate an enum using new. Enumeration variables are used and
declared in much a same way as you do a primitive variable.

How to Define and Use an Enumeration

1. An enumeration can be defined simply by creating a list of enum variable. Let us take an
example for list of Subject variable, with different subjects in the list.
2. enum Subject //Enumeration defined
3. {
4. Java, Cpp, C, Dbms
}

5. Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are public,
static and final by default.
6. Variables of Enumeration can be defined directly without any new keyword.

Subject sub;

7. Variables of Enumeration type can have only enumeration constants as value. We define an
enum variable as enum_variable = enum_type.enum_constant;
sub = Subject.Java;

8. Two enumeration constants can be compared for equality by using the = = relational
operator.

Example:
if(sub == Subject.Java) {
...
}

Example of Enumeration
enum WeekDays
{ sun, mon, tues, wed, thurs, fri, sat }

class Test
{
public static void main(String args[])
{
WeekDays wk; //wk is an enumeration variable of type WeekDays
wk = WeekDays.sun; //wk can be assigned only the constants defined under enum type
Weekdays
System.out.println("Today is "+wk);
}
}

Today is sun

Example of Enumeration using switch statement


enum Restaurants {
dominos, kfc, pizzahut, paninos, burgerking
}
class Test {
public static void main(String args[])
{
Restaurants r;
r = Restaurants.paninos;
switch(r) { //The name of the enumertion constants are used without their enumeration
type name i.e only r, not Restaurants.r
case dominos: //only constants defined under enum Restaurants can be used
System.out.println("I AM " + r.dominos);
break;
case kfc:
System.out.println("I AM " + r.kfc);
break;
case pizzahut:
System.out.println("I AM " + r.pizzahut);
break;
case paninos:
System.out.println("I AM " + r.paninos);
break;
case burgerking:
System.out.println("I AM " + r.burgerking);
break;
}
}
}

I AM paninos

Values( ) and ValueOf( ) method


All the enumerations predefined methods values() and valueOf(). values() method returns an
array of enum-type containing all the enumeration constants in it. Its general form is,
public static enum-type[ ] values()
valueOf() method is used to return the enumeration constant whose value is equal to the string
passed in as argument while calling this method. It's general form is,
public static enum-type valueOf (String str)

Example of enumeration using values() and valueOf() methods:

enum Restaurants {
dominos, kfc, pizzahut, paninos, burgerking
}
class Test {
public static void main(String args[])
{
Restaurants r;
System.out.println("All constants of enum type Restaurants are:");
Restaurants rArray[] = Restaurants.values(); //returns an array of constants of type Restaurants
for(Restaurants a : rArray) //using foreach loop
System.out.println(a);

r = Restaurants.valueOf("dominos");
System.out.println("I AM " + r);
}
}

All constants of enum type Restaurants are:


dominos
kfc
pizzahut
paninos
burgerking
I AM dominos
Points to remember about Enumerations

1. Enumerations are of class type, and have all the capabilities that a Java class has.
2. Enumerations can have Constructors, instance Variables, methods and can even implement
Interfaces.
3. Enumerations are not instantiated using new keyword.
4. All Enumerations by default inherit java.lang.Enum class.

Enumeration with Constructor, instance variable and Method


enum Student
{
John(11), Bella(10), Sam(13), Viraaj(9);
private int age; //variable defined in enum Student
int getage { return age; } //method defined in enum Student
public Student(int age) //constructor defined in enum Student
{
this.age= age;
}
}

class EnumDemo
{
public static void main( String args[] )
{
Student S;
System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ "years");
}
}

Age of Viraaj is 9 years


In this example as soon as we declare an enum variable(Student S), the constructor is called once,
and it initializes age for every enumeration constant with values specified with them in
parenthesis.

type wrapper
Java uses primitive data types such as int, double, float etc. to hold the basic data types for the
sake of performance. Despite the performance benefits offered by the primitive data types, there
are situations when you will need an object representation of the primitive data type. For
example, many data structures in Java operate on objects. So you cannot use primitive data types
with those data structures. To handle such type of situations, Java provides type
Wrappers which provide classes that encapsulate a primitive type within an object.

 Character : It encapsulates primitive type char within object.

Character (char ch)

 Boolean : It encapsulates primitive type boolean within object.

Boolean (boolean boolValue)

 Numeric type wrappers : It is the most commonly used type wrapper.

Byte Short Integer Long Float Double

 Above mentioned Classes comes under Numeric type wrapper. These classes encapsulate
byte, short, int, long, float, double primitive type.

Autoboxing and Unboxing

 Autoboxing and Unboxing features was added in Java5.


 Autoboxing is a process by which primitive type is automatically encapsulated(boxed) into
its equivalent type wrapper
 Auto-Unboxing is a process by which the value of an object is automatically extracted from
a type Wrapper class.
Example of Autoboxing and Unboxing
class Test
{
public static void main(String[] args)
{
Integer iob = 100; //Auto-boxing of int i.e converting primitive data type int to a Wrapper class
Integer
int i = iob; //Auto-unboxing of Integer i.e converting Wrapper class Integer to a primitve type
int
System.out.println(i+" "+iob);

Character cob = 'a'; //Auto-boxing of char i.e converting primitive data type char to a Wrapper
class Character
char ch = cob; //Auto-unboxing of Character i.e converting Wrapper class Character to a
primitive type char
System.out.println(cob+" "+ch);
}
}

100 100
aa

Autoboxing / Unboxing in Expressions


Whenever we use object of Wrapper class in an expression, automatic unboxing and boxing is
done by JVM.
Integer iOb;
iOb = 100; //Autoboxing of int
++iOb;
When we perform increment operation on Integer object, it is first unboxed, then incremented
and then again reboxed into Integer type object.
This will happen always, when we will use Wrapper class objects in expressions or conditions
etc.
Benefits of Autoboxing / Unboxing

1. Autoboxing / Unboxing lets us use primitive types and Wrapper class objects
interchangeably.
2. We don't have to perform Explicit typecasting.
3. It helps prevent errors, but may lead to unexpected results sometimes. Hence must be used
with care.
4. Auto-unboxing also allows you to mix different types of numeric objects in an expression.
When the values are unboxed, the standard type conversions can be applied.

Example:
class Test {
public static void main(String args[]) {
Integer i = 35;
Double d = 33.3;
d = d + i;
System.out.println("Value of d is " + d);
}
}

Value of d is 68.3
Note: When the statement d = d + i; was executed, i was auto-unboxed into int, d was auto-
unboxed into double, addition was performed and then finally, auto-boxing of d was done into
Double type Wrapper class.

IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.

Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream
and OutputStream.

These two abstract classes have several concrete classes that handle various devices such as disk
files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype


DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are

1. read() : reads byte of data.


2. write() : Writes byte of data.

Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.

These two abstract classes have several concrete classes that handle unicode character.
Some important Charcter stream classes.

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Reading Console Input


We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}

Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
Program to take String input from Keyboard in Java
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}

Program to read from a file using BufferedReader class


import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}

Program to write to a File using FileWriter class


import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}

Serialization and Deserialization in Java


Serialization is a process of converting an object into a sequence of bytes which can be persisted
to a disk or database or can be sent through streams. The reverse process of creating object from
sequence of bytes is called deserialization.
A class must implement Serializable interface present in java.io package in order to serialize its
object successfully. Serializable is a marker interface that adds serializable behaviour to the
class implementing it.
Java provides Serializable API encapsulated under java.io package for serializing and
deserializing objects which include,

 java.io.serializable
 java.io.Externalizable
 ObjectInputStream
 and ObjectOutputStream etc.

Marker interface
Marker Interface is a special interface in Java without any field and method. Marker interface is
used to inform compiler that the class implementing it has some special behaviour or meaning.
Some example of Marker interface are,

 java.io.serializable
 java.lang.Cloneable
 java.rmi.Remote
 java.util.RandomAccess

All these interfaces does not have any method and field. They only add special behavior to the
classes implementing them. However marker interfaces have been deprecated since Java 5, they
were replaced by Annotations. Annotations are used in place of Marker Interface that play the
exact same role as marker interfaces did before.

Signature of writeObject() and readObject()


writeObject() method of ObjectOutputStream class serializes an object and send it to the output
stream.
public final void writeObject(object x) throws IOException
readObject() method of ObjectInputStream class references object out of stream and deserialize
it.
public final Object readObject() throws IOException,ClassNotFoundException
while serializing if you do not want any field to be part of object state then declare it either static
or transient based on your need and it will not be included during java serialization process.
Serializing an Object
import java.io.*;
class studentinfo implements Serializable
{
String name;
int rid;
static String contact;
studentinfo(string n, int r, string c)
{
this.name = n;
this.rid = r;
this.contact = c;
}
}

class Test
{
public static void main(String[] args)
{
try
{
Studentinfo si = new studentinfo("Abhi", 104, "110044");
FileOutputStream fos = new FileOutputStream("student.ser");
Objectoutputstream oos = new ObjectOutputStream(fos);
oos.writeObject(si);
oos.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Object of Studentinfo class is serialized using writeObject() method and written
to student.ser file.

Deserialization of Object
import java.io * ;
class DeserializationTest
{
public static void main(String[] args)
{
studentinfo si=null ;
try
{
FileInputStream fis = new FileInputStream("student.ser");
ObjectOutputStream ois = new ObjectOutputStream(fis);
si = (studentinfo)ois.readObject();
}
catch (Exception e)
{
e.printStackTrace(); }
System.out.println(si.name);
System.out. println(si.rid);
System.out.println(si.contact);
}
}

Abhi
104
null
Contact field is null because,it was marked as static and as we have discussed earlier static fields
does not get serialized.
NOTE: Static members are never serialized because they are connected to class not object of
class.

transient Keyword
While serializing an object, if we don't want certain data member of the object to be serialized
we can mention it transient. transient keyword will prevent that data member from being
serialized.
class studentinfo implements Serializable
{
String name;
transient int rid;
static String contact;
}

 Making a data member transient will prevent its serialization.


 In this example rid will not be serialized because it is transient, and contact will also remain
unserialized because it is static.

Networking in Java
Java is a premier language for network programming. java.net package encapsulate large
number of classes and interface that provides an easy-to use means to access network resources.
Here are some important classes and interfaces of java.net package.

Some Important Classes

CLASSES

CacheRequest CookieHandler

CookieManager Datagrampacket

Inet Address ServerSocket

Socket DatagramSocket

Proxy URL

URLConnection

Some Important Interfaces

INTERFACES

CookiePolicy CookieStore

FileNameMap SocketOption
InetAddress ServerSocket

SocketImplFactory ProtocolFamily

InetAddress
Inet Address encapsulates both numerical IP address and the domain name for that address. Inet
address can handle both IPv4 and Ipv6 addresses. Inet Address class has no visible constructor.
To create an inet Address object, you have to use Factory methods.
Three commonly used Inet Address factory methods are.

1. static InetAddress getLocalHost() throws UnknownHostException


2. static InetAddress getByName (String hostname) throws UnknownHostException
3. static InetAddress[ ] getAllByName (String hostname) throws UnknownHostException

Example using InetAddress class


import java.net.*;
class Test
{
public static void main(String[] args)
{
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
address = InetAddress.getByName("www.studytonight.com");
System.out.println(address);
InetAddress sw[] = InetAddress.getAllByName("www.google.com");
for(int i=0; i< sw.length; i++)
{
System.out.println(sw[i]);
}
}
}

Welcome-PC/59.161.87.227
www.studytonight.com/208.91.198.55
www.google.com/74.125.236.115
www.google.com/74.125.236.116
www.google.com/74.125.236.112
www.google.com/74.125.236.113
www.google.com/74.125.236.114
www.google.com/2404:6800:4009:802:0:0:0:1014

Socket and ServerSocket Class


Socket is foundation of modern networking, a socket allows single computer to serve many
different clients at once. Socket establishes connection through the use of port, which is a
numbered socket on a particular machine. Socket communication takes place via a protocol.
Socket provides communication mechanism between two computers using TCP. There are two
kind of TCP sockets in Java. One is for server and other is for client.

 ServerSocket is for servers.


 Socket class is for client.
URL class
Java URL Class present in java.net package, deals with URL (Uniform Resource Locator) which
uniquely identify or locate resources on internet.

Important Methods of URL class

 getProtocol() : Returns protocol of URL


 getHost() : Returns hostname(domain name) of URL
 getPort() : Returns port number of URL
 getFile() : Returns filename of URL

Program using URL class


import java.net.*;
class Test
{
public static void main(String[] arg) throws MalFormedURLException
{
URL hp = New URL("http://www.studytonight.com/index");
system.out.println(hp.getProtocol[]);
System.out.println(hp.getFile[]);
}
}
http
-1
www.studytonight.com
/index

Generics
Generics was first introduced in Java5. Now it is one of the most profound feature of java
programming language. Generic programming enables the programmer to create
classes,interfaces and methods in which type of data is specified as a parameter. It provides a
facility to write an algorithm independent of any specific type of data. Generics also provide type
safety. Type safety means ensuring that an operation is being performed on the right type of data
before executing that operation.
Using Generics, it has become possible to create a single class ,interface or method that
automatically works with all types of data(Integer, String, Float etc). It has expanded the ability
to reuse the code safely and easily.
Before Generics was introduced, generalized classes,interfaces or methods were created using
references of type Object because Object is the super class of all classes in Java, but this way of
programming did not ensure type safety.
Syntax for creating an object of a generic type
Class_name <data type> reference_name = new Class_name<data type> ();
OR
Class_name <data type> reference_name = new Class_name<>();
This is also known as Diamond Notation of creating an object of Generic type.

Example of Generic class


class Gen <T> //<> brackets indicates that the class is of generic type
{
T ob; //an object of type T is declared
Gen(T o) //constructor
{
ob = o;
}
public T getOb()
{
return ob;
}
}

class Test
{
public static void main (String[] args)
{
Gen < Integer> iob = new Gen<>(100); //instance of Integer type Gen Class.
int x = iob.getOb();
System.out.println(x);
Gen < String> sob = new Gen<>("Hello"); //instance of String type Gen Class.
String str = sob.getOb();
System.out.println(str);
}
}

100
Hello
In the above program, we first passed an Integer type parameter to the Generic class. Then, we
passed a String type parameter to the same Generic class. Hence, we reused the same class for
two different data types. Thus, Generics helps in code reusability with ease.

Generics Work Only with Objects


Generics work only with objects i.e the type argument must be a class type.You cannot use
primitive datatypes such as int, char etc. with Generics type. It should always be an object. We
can use all the Wrapper Class objects and String class objects as Generic type.
Gen<int> iOb = new Gen<int>(07); //Error, can't use primitive type
Generics Types of different Type Arguments are never same
Reference of one generic type is never compatible with other generic type unless their type
argument is same. In the example above we created two objects of class Gen, one of
type Integer, and other of type String, hence,
iob = sob; //Absolutely Wrong

An array of Generic type cannot be created


Creation of a generic type array is not allowed in Generic programming. We can make a
reference of an array, but we cannot instantiate it.
For example, In the above program, in class Gen,
T a[]; //this is allowed
T a[] = new T[10]; //this is not allowed

Generic Type with more than one parameter


In Generic parameterized types, we can pass more than 1 data type as parameter. It works the
same as with one parameter Generic type.
class Gen <T1,T2>
{
T1 name;
T2 value;

Gen(T1 o1,T2 o2)


{
name = o1;
value = o2;
}
public T1 getName()
{
return name;
}
public T2 getValue()
{
return value;
}

class Test
{
public static void main (String[] args)
{
Gen < String,Integer> obj = new Gen<>("StudyTonight",1);

String s = obj.getName();
System.out.println(s);

Integer i = obj.getValue();
System.out.println(i);
}
}

StudyTonight
1
Note: Since there are two parameters in Generic class - T1 and T2, therefore, while creating an
instance of this Generic class, we need to mention two data types that needs to be passed as
parameter to this class.
Generic Methods
You can also create generic methods that can be called with different types of arguments. Based
on the type of arguments passed to generic method, the compiler handles each method.
The syntax for a generic method includes a type-parameter inside angle brackets, and should
appear before the method's return type.
<type-parameter> return_type method_name (parameters) {...}
Example of Generic method
class GenTest
{
static <b>< V, T></b> void display (V v, T t)
{
System.out.println(v.getClass().getName()+" = " +v);
System.out.println(t.getClass().getName()+" = " +t);
}
public static void main(String[] args)
{
display(88,"This is string");
}
}

java lang.Integer = 88
java lang.String = This is string

Generic Constructors
It is possible to create a generic constructor even if the class is not generic.
Example of Generic Constructor
class Gen
{
private double val;
< T extends Number> Gen(T ob)
{
val=ob.doubleValue();
}
void show()
{
System.out.println(val);
}
}

class Test
{
public static void main(String[] args)
{
Gen g = new Gen(100);
Gen g1 = new Gen(121.5f);
g.show();
g1.show();
}
}

100.0
121.5

Generic Interface
Like classes and methods, you can also create generic interfaces.
interface MyInterface< T >
{ .. }

Generic Bounded type Parameter


You can also set restriction on the type that will be allowed to pass to a type-parameter. This is
done with the help of extends keyword when specifying the type parameter.
< T extends Number >
Here we have taken Number class, it can be any wrapper class name. This specifies that T can
be only be replaced by Number class data itself or any of its subclass.
Generic Method with bounded type Parameters.
class Gen
{
static < T, V extends number> void display(T t, V v)
{
System.out.println(v.getClass().getName()+" = " +v);
System.out.println(t.getClass().getName()+" = " +t);
}
public static void main(String[] args)
{
// display(88,"This is string");
display ("this is string",99);
}
}

java.lang.String = This is string


java.lang.Double = 99.O

 Type V is bounded to Number type and its subclass only.


 If display(88,"This is string") is uncommented, it will give an error of type incompatibility,
as String is not a subclass of Number class.

Collection Framework
Collections framework was not a part of original Java release. Collections was added to J2SE
1.2. Prior to Java 2, Java provided adhoc classes such as Dictionary, Vector, Stack and Properties
to store and manipulate groups of objects.
Framework in java means hierarchy of classes and interfaces.Collections framework is contained
in java.util package. It provides many important classes and interfaces to collect and organize
group of alike objects.
Important Interfaces of Collection API

Interface Description

Collection Enables you to work with groups of object; it is at the top of Collection hierarchy

Deque Extends Queue to handle double ended queue.

List Extends Collection to handle sequences list of object.

Queue Extends Collection to handle special kind of list in which element are removed only
from the head.

Set Extends Collection to handle sets, which must contain unique element.

SortedSet Extends Set to handle sorted set.


Collection Heirarchy
All these Interfaces give several methods which are defined by collections classes which
implement these interfaces.
Why Collections were made Generic ?
Generics added type safety to Collection framework. Earlier collections stored Object
classreferences which meant any collection could store any type of object. Hence there were
chances of storing incompatible types in a collection, which could result in run time mismatch.
Hence Generics was introduced through which you can explicitly state the type of object being
stored.

Collections and Autoboxing


We have studied that Autoboxing converts primitive types into Wrapper class Objects. As
collections doesn't store primitive data types(stores only refrences), hence Autoboxing facilitates
the storing of primitive data types in collection by boxing it into its wrapper type.

Most Commonly thrown Exceptions in Collections Framework

Exception Name Description

UnSupportedOperationException occurs if a Collection cannot be modified

ClassCastException occurs when one object is incompatible with another

NullPointerException occurs when you try to store null object in Collection

IllegalArgumentException thrown if an invalid argument is used

IllegalStateException thrown if you try to add an element to an already full Collection

Interfaces of Collection Framework


The Collections framework has a lot of Interfaces, setting the fundamental nature of various
collection classes. Lets study the most important Interfaces in the Collections framework.
The Collection Interface

1. It is at the top of collection heirarchy and must be implemented by any class that defines a
collection. Its general declaration is,

interface Collection < E >

2. Following are some of the commonly used methods in this interface.

Methods Description

boolean add( E obj ) Used to add objects to a collection. Returns true if obj was
added to the collection. Returns false if obj is already a
member of the collection, or if the collection does not allow
duplicates.

boolean addAll( Collection C ) Add all elements of collection C to the invoking collection.
Returns true if the element were added. Otherwise, returns
false.

boolean remove( Object obj ) To remove an object from collection. Returns true if the
element was removed. Otherwise, returns false.

boolean removeAll( Collection C ) Removes all element of collection C from the invoking
collection. Returns true if the collection's elements were
removed. Otherwise, returns false.

boolean contains( Object obj ) To determine whether an object is present in collection or


not. Returns true if obj is an element of the invoking
collection. Otherwise, returns false.

boolean isEmpty() Returns true if collection is empty, else returns false.


int size() Returns number of elements present in collection.

void clear() Removes total number of elements from the collection.

Object[] toArray() Returns an array which consists of the invoking collection


elements.

boolean retainAll(Collection c) Deletes all the elements of invoking collection except the
specified collection.

Iterator iterator( ) Returns an iterator for the invoking collection.

boolean equals(Object obj) Returns true if the invoking collection and obj are equal.
Otherwise, returns false.

Object[] toArray(Object array[]) Returns an array containing only those collection elements
whose type matches of the specified array.

The List Interface

1. It extends the Collection Interface, and defines storage as sequence of elements. Following is
its general declaration,

interface List < E >

2. Allows random access and insertion, based on position.


3. It allows Duplicate elements.
4. Apart from methods of Collection Interface, it adds following methods of its own.
Methods Description

Object get( int index ) Returns object stored at the specified index

Object set( int index, E obj) Stores object at the specified index in the calling collection

int indexOf( Object obj ) Returns index of first occurrence of obj in the collection

int lastIndexOf( Object obj ) Returns index of last occurrence of obj in the collection

List subList( int start, int end ) Returns a list containing elements between start and end index in
the collection

The Set Interface

1. This interface defines a Set. It extends Collection interface and doesn't allow insertion of
duplicate elements. It's general declaration is,

interface Set < E >

2. It doesn't define any method of its own. It has two sub


interfaces, SortedSet and NavigableSet.
3. SortedSet interface extends Set interface and arranges added elements in an ascending order.
4. NavigabeSet interface extends SortedSet interface, and allows retrieval of elements based
on the closest match to a given value or values.
The Queue Interface

1. It extends collection interface and defines behaviour of queue, that is first-in, first-out. It's
general declaration is,

interface Queue < E >

2. There are couple of new and interesting methods added by this interface. Some of them are
mentioned in below table.

Methods Description

Object poll() removes element at the head of the queue and returns null if queue
is empty

Object remove() removes element at the head of the queue and


throws NoSuchElementException if queue is empty

Object peek() returns the element at the head of the queue without removing it.
Returns null if queue is empty

Object element() same as peek(), but throws NoSuchElementException if queue is


empty

boolean offer( E obj ) Adds object to queue.

The Dequeue Interface

1. It extends Queue interface and implements behaviour of a double-ended queue. Its general
declaration is,
interface Dequeue < E >

2. Since it implements Queue interface, it has the same methods as mentioned there.
3. Double ended queues can function as simple queues as well as like standard Stacks.

The Collection classes


There are some standard classes that implements Collection interface. Some of the classes
provide full implementations that can be used as it is.Others are abstract classes, which provides
skeletal implementations that can be used as a starting point for creating concrete collections.
The standard collection classes are:
Class Description

AbstractCollection Implements most of the Collection interface.

AbstractList Extends AbstractCollection and implements most of the List interface.

AbstractQueue Extends AbstractCollection and implements parts of the Queue interface.

Extends AbstractList for use by a collection that uses sequential rather


AbstractSequentialList
than random access of its elements.

LinkedList Implements a linked list by extending AbstractSequentialList

ArrayList Implements a dynamic array by extending AbstractList

Implements a dynamic double-ended queue by extending


ArrayDeque AbstractCollection and implementing the Deque interface(Added by Java
SE 6).

AbstractSet Extends AbstractCollection and implements most of the Set interface.

EnumSet Extends AbstractSet for use with enum elements.

HashSet Extends AbstractSet for use with a hash table.

LinkedHashSet Extends HashSet to allow insertion-order iterations.

PriorityQueue Extends AbstractQueue to support a priority-based queue.

TreeSet Implements a set stored in a tree. Extends AbstractSet.


Note:

1. To use any Collection class in your program, you need to import it in your program. It is
contained inside java.util package.
2. Whenever you print any Collection class, it gets printed inside the square brackets [].

ArrayList class
Simple arrays have fixed size i.e it can store fixed number of elements. But, sometimes you may
not know beforehand about the number of elements that you are going to store in your array. In
such situations, We can use an ArrayList, which is an array whose size can increase or decrease
dynamically.

1. ArrayList class extends AbstractList class and implements the List interface.
2. ArrayList supports dynamic array that can grow as needed. ArrayList has three constructors.
3. ArrayList() //It creates an empty ArrayList
4.
5. ArrayList( Collection C ) //It creates an ArrayList that is initialized with elements of the Col
lection C
6.
7. ArrayList( int capacity ) //It creates an ArrayList that has the specified initial capacity

8. ArrayLists are created with an initial size. When this size is exceeded, the size of the
ArrayList increases automatically.
9. It can contain Duplicate elements and it also maintains the insertion order.
10. Manipulation is slow because a lot of shifting needs to be occurred if any element is removed
from the array list.
11. ArrayLists are not synchronized.
12. ArrayList allows random access because it works on the index basis.

Example of ArrayList
import java.util.*
class Test
{
public static void main(String[] args)
{
ArrayList< String> al = new ArrayList< String>();
al.add("ab");
al.add("bc");
al.add("cd");
system.out.println(al);
}
}

[ab,bc,cd]

Getting Array from an ArrayList


toArray() method is used to get an array containing all the contents of the ArrayList. Following
are some reasons for why you can need to obtain an array from your ArrayList:

 To obtain faster processing for certain operations.


 To pass an array to methods which do not accept Collection as arguments.
 To integrate and use collections with legacy code.

Storing User-Defined classes


In the above mentioned example we are storing only string object in ArrayList collection. But
You can store any type of object, including object of class that you create in Collection classes.

Example of storing User-Defined object


Contact class
class Contact
{
String first_name;
String last_name;
String phone_no;

public Contact(String fn,String ln,String pn)


{
first_name = fn;
last_name = ln;
phone_no = pn;
}

public String toString()


{
return first_name+" "+last_name+"("+phone_no+")";
}
}
Storing Contact class
public class PhoneBook
{

public static void main(String[] args)


{
Contact c1 = new Contact("Ricky", "Pointing","999100091");
Contact c2 = new Contact("David", "Beckham","998392819");
Contact c3 = new Contact("Virat", "Kohli","998131319");

ArrayList< Contact> al = new ArrayList< Contact>();


al.add(c1);
al.add(c2);
al.add(c3);
System.out.println(al);
}
}

[Ricky Pointing(999100091), David Beckham(998392819), Virat Kohli(998131319)]

LinkedList class

1. LinkedList class extends AbstractSequentialList and


implements List,Deque and Queueinteface.
2. LinkedList has two constructors.
3.
4. LinkedList() //It creates an empty LinkedList
5.
LinkedList( Collection C ) //It creates a LinkedList that is initialized with elements of the
Collection c

6. It can be used as List, stack or Queue as it implements all the related interfaces.
7. They are dynamic in nature i.e it allocates memory when required. Therefore insertion and
deletion operations can be easily implemented.
8. It can contain duplicate elements and it is not synchronized.
9. Reverse Traversing is difficult in linked list.
10. In LinkedList, manipulation is fast because no shifting needs to be occurred.

Example of LinkedList class


import java.util.* ;
class Test
{
public static void main(String[] args)
{
LinkedList< String> ll = new LinkedList< String>();
ll.add("a");
ll.add("b");
ll.add("c");
ll.addLast("z");
ll.addFirst("A");
System.out.println(ll);
}
}

[A, a, b,c, z]

Difference between ArrayList and Linked List


ArrayList and LinkedList are the Collection classes, and both of them implements the List
interface. The ArrayList class creates the list which is internally stored in a dynamic array that
grows or shrinks in size as the elements are added or deleted from it. LinkedList also creates the
list which is internally stored in a DoublyLinked List. Both the classes are used to store the
elements in the list, but the major difference between both the classes is that ArrayList allows
random access to the elements in the list as it operates on an index-based data structure. On the
other hand, the LinkedList does not allow random access as it does not have indexes to access
elements directly, it has to traverse the list to retrieve or access an element from the list.
Some more differences:

 ArrayList extends AbstarctList class whereas LinkedList extends AbstractSequentialList.


 AbstractList implements List interface, thus it can behave as a list only whereas LinkedList
implements List, Deque and Queue interface, thus it can behave as a Queue and List both.
 In a list, access to elements is faster in ArrayList as random access is also possible. Access to
LinkedList elements is slower as it follows sequential access only.
 In a list, manipulation of elements is slower in ArrayList whereas it is faster in LinkedList.

HashSet class
1. HashSet extends AbstractSet class and implements the Set interface.
2. HashSet has three constructors.

HashSet() //This creates an empty HashSet

HashSet( Collection C ) //This creates a HashSet that is initialized with the elements of the
Collection C

HashSet( int capacity ) //This creates a HashSet that has the specified initial capacity

3. It creates a collection that uses hash table for storage. A hash table stores information by
using a mechanism called hashing.
4. In hashing, the informational content of a key is used to determine a unique value, called its
hash code. The hash code is then used as the index at which the data associated with the key
is stored.
5. HashSet does not maintain any order of elements.
6. HashSet contains only unique elements.

Example of HashSet class


import java.util.*;
class HashSetDemo
{
public static void main(String args[])
{
HashSet< String> hs = new HashSet< String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}

[D, E, F, A, B, C]

LinkedHashSet Class

1. LinkedHashSet class extends HashSet class


2. LinkedHashSet maintains a linked list of entries in the set.
3. LinkedHashSet stores elements in the order in which elements are inserted i.e it maintains
the insertion order.

Example of LinkedHashSet class


import java.util.*;
class LinkedHashSetDemo
{
public static void main(String args[])
{
LinkedHashSet< String> hs = new LinkedHashSet< String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
[B, A, D, E, C, F]

TreeSet Class

1. It extends AbstractSet class and implements the NavigableSet interface.


2. It stores the elements in ascending order.
3. It uses a Tree structure to store elements.
4. It contains unique elements only like HashSet.
5. It's access and retrieval times are quite fast.
6. It has four Constructors.

TreeSet() //It creates an empty tree set that will be sorted in an ascending order according t
o the
natural order of the tree set

TreeSet( Collection C ) //It creates a new tree set that contains the elements of the Collectio
nC

TreeSet( Comparator comp ) //It creates an empty tree set that will be sorted according to gi
ven Comparator

TreeSet( SortedSet ss ) //It creates a TreeSet that contains the elements of given SortedSet

Example of TreeSet class


import java.util.*;
class TestCollection11{
public static void main(String args[]){
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Ajay
Ravi
Vijay

PriorityQueue Class

1. It extends the AbstractQueue class.


2. The PriorityQueue class provides the facility of using queue.
3. It does not orders the elements in FIFO manner.
4. PriorityQueue has six constructors. In all cases, the capacity grows automatically as elements
are added.
5. PriorityQueue( ) //This constructor creates an empty queue. By default, its starting capacity
is 11
6.
7. PriorityQueue(int capacity) //This constructor creates a queue that has the specified initial
capacity
8.
9. PriorityQueue(int capacity, Comparator comp) //This constructor creates a queue with the
specified capacity
10. and comparator
11.
12. //The last three constructors create queues that are initialized with elements of Collection
passed in c
13. PriorityQueue(Collection c)
14.
15. PriorityQueue(PriorityQueue c)
16.
PriorityQueue(SortedSet c)
Note: If no comparator is specified when a PriorityQueue is constructed, then the default
comparator for the type of data stored in the queue is used. The default comparator will order the
queue in ascending order. Thus, the head of the queue will be the smallest value. However, by
providing a custom comparator, you can specify a different ordering scheme.
Note: Although you can iterate through a PriorityQueue using an iterator, the order of that
iteration is undefined. To properly use a PriorityQueue, you must call methods such as offer( )
and poll( ), which are defined by the Queue interface.

Example of PriorityQueue class


import java.util.*;

class StudyTonight
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("WE");
queue.add("LOVE");
queue.add("STUDY");
queue.add("TONIGHT");
System.out.println("At head of the queue:"+queue.element());
System.out.println("At head of the queue:"+queue.peek());
System.out.println("Iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("After removing two elements:");
Iterator itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}

At head of the queue:LOVE


At head of the queue:LOVE
Iterating the queue elements:
LOVE
TONIGHT
STUDY
WE
After removing two elements:
TONIGHT
WE

Accessing a Collection
To access, modify or remove any element from any collection we need to first find the element,
for which we have to cycle through the elements of the collection. There are three possible ways
to cycle through the elements of any collection.

1. Using Iterator interface


2. Using ListIterator interface
3. Using for-each loop
Steps to use an Iterator

1. Obtain an iterator to the start of the collection by calling the collection's iterator() method.
2. Set up a loop that makes a call to hasNext() method. Make the loop iterate as long
as hasNext()method returns true.
3. Within the loop, obtain each element by calling next() method.

Accessing elements using Iterator


Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify
the elements of the collection. Each collection classes provide iterator() method to return an
iterator.
Methods of Iterator:

Method Description

boolean hasNext() Returns true if there are more elements in the collection. Otherwise, returns
false.

E next() Returns the next element present in the collection. Throws


NoSuchElementException if there is not a next element.

void remove() Removes the current element. Throws IllegalStateException if an attempt is


made to call remove() method that is not preceded by a call to next() method.

import java.util.*;
class Test_Iterator
{
public static void main(String[] args)
{
ArrayList< String> ar = new ArrayList< String>();
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
Iterator it = ar.iterator(); //Declaring Iterator
while(it.hasNext())
{
System.out.print(it.next()+" ");
}
}
}

ab bc cd de

Accessing elements using ListIterator


ListIterator Interface is used to traverse a list in both forward and backward direction. It is
available to only those collections that implements the List Interface.
Methods of ListIterator:

Method Description

void add(E obj) Inserts obj into the list in front of the element that will be returned by the
next call to next() method.

boolean hasNext() Returns true if there is a next element. Otherwise, returns false.

boolean hasPrevious() Returns true if there is a previous element. Otherwise, returns false.

E next() Returns the next element. A NoSuchElementException is thrown if there is


not a next element.
int nextIndex() Returns the index of the next element. If there is not a next element, returns
the size of the list.

E previous() Returns the previous element. A NoSuchElementException is thrown if there


is not a previous element.

int previousIndex() Returns the index of the previous element. If there is not a previous element,
returns -1.

void remove() Removes the current element from the list. An IllegalStateException is
thrown if remove() method is called before next() or previous() method is
invoked.

void set(E obj) Assigns obj to the current element. This is the element last returned by a call
to either next() or previous() method.

import java.util.*;
class Test_Iterator
{
public static void main(String[] args)
{
ArrayList< String> ar = new ArrayList< String>();
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
ListIterator litr = ar.listIterator();
while(litr.hasNext()) //In forward direction
{
System.out.print(litr.next()+" ");
}
while(litr.hasPrevious()) //In backward direction
{
System.out.print(litr.previous()+" ");
}
}
}

ab bc cd de
de cd bc ab

Using for-each loop


for-each version of for loop can also be used for traversing the elements of a collection. But this
can only be used if we don't want to modify the contents of a collection and we don't want
any reverseaccess. for-each loop can cycle through any collection of object that
implements Iterableinterface.
import java.util.*;
class ForEachDemo
{
public static void main(String[] args)
{
LinkedList< String> ls = new LinkedList< String>();
ls.add("a");
ls.add("b");
ls.add("c");
ls.add("d");
for(String str : ls)
{
System.out.print(str+" ");
}
}
}
abcd

Map Interface
A Map stores data in key and value association. Both key and values are objects. The key must
be unique but the values can be duplicate. Although Maps are a part of Collection Framework,
they can not actually be called as collections because of some properties that they posses.
However we can obtain a collection-view of maps.

Interface Description

Map Maps unique key to value.

Map.Entry Describe an element in key and value pair in a map. Entry is sub
interface of Map.

NavigableMap Extends SortedMap to handle the retrienal of entries based on closest


match searches

SortedMap Extends Map so that key are maintained in an ascending order.


Commonly used Methods defined by Map

 boolean containsKey(Object k): returns true if map contain k as key. Otherwise false.
 Object get(Object k) : returns values associated with the key k.
 Object put(Object k, Object v) : stores an entry in map.
 Object putAll(Map m) : put all entries from m in this map.
 Set keySet() : returns Set that contains the key in a map.
 Set entrySet() : returns Set that contains the entries in a map.

HashMap class

1. HashMap class extends AbstractMap and implements Map interface.


2. It uses a hashtable to store the map. This allows the execution time of get() and put() to
remain same.
3. HashMap has four constructor.
4. HashMap()
5. HashMap(Map< ? extends k, ? extends V> m)
6. HashMap(int capacity)
HashMap(int capacity, float fillratio)

7. HashMap does not maintain order of its element.

Example
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap< String,Integer> hm = new HashMap< String,Integer>();
hm.put("a",new Integer(100));
hm.put("b",new Integer(200));
hm.put("c",new Integer(300));
hm.put("d",new Integer(400));

Set< Map.Entry< String,Integer> > st = hm.entrySet(); //returns Set view


for(Map.Entry< String,Integer> me:st)
{
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
}
}

c 300
a 100
d 400
b 200

TreeMap class

1. TreeMap class extends AbstractMap and implements NavigableMap interface.


2. It creates Map, stored in a tree structure.
3. A TreeMap provides an efficient means of storing key/value pair in efficient order.
4. It provides key/value pairs in sorted order and allows rapid retrieval.

Example
import java.util.*;
class TreeMapDemo
{
public static void main(String args[])
{
TreeMap< String,Integer> tm = new TreeMap< String,Integer>();
tm.put("a",new Integer(100));
tm.put("b",new Integer(200));
tm.put("c",new Integer(300));
tm.put("d",new Integer(400));

Set< Map.Entry< String,Integer> > st = tm.entrySet();


for(Map.Entry me:st)
{
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
}
}

a 100
b 200
c 300
d 400

LinkedHashMap class

1. LinkedHashMap extends HashMap class.


2. It maintains a linked list of entries in map in order in which they are inserted.
3. LinkedHashMap defines the following constructor
4. LinkedHashMap()
5.
6. LinkedHashMap(Map< ? extends k, ? extends V> m)
7.
8. LinkedHashMap(int capacity)
9.
10. LinkedHashMap(int capacity, float fillratio)
11.
LinkedHashMap(int capacity, float fillratio, boolean order)

12. It adds one new method removeEldestEntry(). This method is called by put() and putAll() By
default this method does nothing. However we can override this method to remove oldest
element in the map. Syntax

protected boolean removeEldestEntry(Map.Entry e)

EnumMap class

1. EnumMap extends AbstractMap and implements Map interface.


2. It is used for key as enum

Comparator Interface
In Java, Comparator interface is used to order(sort) the objects in the collection in your own way.
It gives you the ability to decide how elements will be sorted and stored within collection and
map.
Comparator Interface defines compare() method. This method has two parameters. This method
compares the two objects passed in the parameter. It returns 0 if two objects are equal. It returns
a positive value if object1 is greater than object2. Otherwise a negative value is returned. The
method can throw a ClassCastException if the type of object are not compatible for
comparison.

Rules for using Comparator interface


Rules for using Comparator interface:

1. If you want to sort the elements of a collection, you need to implement Comparator interface.
2. If you do not specify the type of the object in your Comparator interface, then, by default, it
assumes that you are going to sort the objects of type Object. Thus, when you override the
compare() method ,you will need to specify the type of the parameter as Object only.
3. If you want to sort the user-defined type elements, then while implementing the Comparator
interface, you need to specify the user-defined type generically. If you do not specify the
user-defined type while implementing the interface,then by default, it assumes Object type
and you will not be able to compare the user-defined type elements in the collection

For Example:
If you want to sort the elements according to roll number, defined inside the class Student, then
while implementing the Comparator interface, you need to mention it generically as follows:
class MyComparator implements Comparator<Student>{}
If you write only,
class MyComparator implements Comparator {}
Then it assumes, by default, data type of the compare() method's parameter to be Object, and
hence you will not be able to compare the Student type(user-defined type) objects.

Example
Student class
class Student
int roll;
String name;
Student(int r,String n)
{
roll = r;
name = n;
}
public String toString()
{
return roll+" "+name;
}
MyComparator class
This class defines the comparison logic for Student class based on their roll. Student object will
be sorted in ascending order of their roll.
class MyComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
if(s1.roll == s2.roll) return 0;
else if(s1.roll > s2.roll) return 1;
else return -1;
}
}
public class Test
{

public static void main(String[] args)


{
TreeSet< Student> ts = new TreeSet< Student>(new MyComparator());
ts.add(new Student(45, "Rahul"));
ts.add(new Student(11, "Adam"));
ts.add(new Student(19, "Alex"));
System.out.println(ts);
}

[ 11 Adam, 19 Alex, 45 Rahul ]


As you can see in the ouput Student object are stored in ascending order of their roll.

Note:

 When we are sorting elements in a collection using Comparator interface, we need to pass
the class object that implements Comparator interface.
 To sort a TreeSet collection, this object needs to be passed in the constructor of TreeSet.
 If any other collection, like ArrayList,was used, then we need to call sort method of
Collections class and pass the name of the collection and this object as a parameter.
 For example, If the above program used ArrayList collection, the public class test would be
as follows:

public class Test


{
public static void main(String[] args)
{
ArrayList< Student> ts = new ArrayList< Student>();
ts.add(new Student(45, "Rahul"));
ts.add(new Student(11, "Adam"));
ts.add(new Student(19, "Alex"));
Collections.sort(ts,new MyComparator()); /*passing the name of the ArrayList and the
object of the class that implements Comparator in a predefined sort() method in Collections
class*/
System.out.println(ts);
}
}

Legacy Classes
Early version of java did not include the Collections framework. It only defined several classes
and interfaces that provide methods for storing objects. When Collections framework were added
in J2SE 1.2, the original classes were reengineered to support the collection interface. These
classes are also known as Legacy classes. All legacy classes and interface were redesign by JDK
5 to support Generics. In general, the legacy classes are supported because there is still some
code that uses them.
The following are the legacy classes defined by java.util package

1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
There is only one legacy interface called Enumeration
NOTE: All the legacy classes are synchronized

Enumeration interface

1. Enumeration interface defines method to enumerate(obtain one at a time) through collection


of objects.
2. This interface is superseded(replaced) by Iterator interface.
3. However, some legacy classes such as Vector and Properties defines several method in
which Enumeration interface is used.
4. It specifies the following two methods

boolean hasMoreElements() //It returns true while there are still more elements to extract,
and returns false when all the elements have been enumerated.

Object nextElement() //It returns the next object in the enumeration i.e. each call to
nextElement() method
obtains the next object in the enumeration. It throws NoSuchElementException when the
enumeration is complete.

Vector class

1. Vector is similar to ArrayList which represents a dynamic array.


2. There are two differences between Vector and ArrayList. First, Vector is synchronized
while ArrayList is not, and Second, it contains many legacy methods that are not part of the
Collections Framework.
3. With the release of JDK 5, Vector also implements Iterable. This means that Vector is fully
compatible with collections, and a Vector can have its contents iterated by the for-each loop.
4. Vector class has following four constructor
5. Vector() //This creates a default vector, which has an initial size of 10.
6.
7. Vector(int size) //This creates a vector whose initial capacity is specified by size.
8.
9. Vector(int size, int incr) //This creates a vector whose initial capacity is specified by size and
whose
10. increment is specified by incr. The increment specifies the number of elements to allocate
each time
11. when a vector is resized for addition of objects.
12.
Vector(Collection c) //This creates a vector that contains the elements of collection c.
Vector defines several legacy methods. Lets see some important legacy methods defined
by Vectorclass.

Method Description

void addElement(E element) adds element to the Vector

E elementAt(int index) returns the element at specified index

Enumeration elements() returns an enumeration of element in vector

E firstElement() returns first element in the Vector

E lastElement() returns last element in the Vector

void removeAllElements() removes all elements of the Vector

Example of Vector
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Vector ve = new Vector();
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);

Enumeration en = ve.elements();

while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}
}

10
20
30
40
50
60
Hashtable class

1. Like HashMap, Hashtable also stores key/value pair. However neither keys nor values can
be null.
2. There is one more difference between HashMap and Hashtable that is Hashtable is
synchronized while HashMap is not.
3. Hashtable has following four constructor
4. Hashtable() //This is the default constructor. The default size is 11.
5.
6. Hashtable(int size) //This creates a hash table that has an initial size specified by size.
7.
8. Hashtable(int size, float fillratio) //This creates a hash table that has an initial size specified
by size
9. and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it
determines how full
10. the hash table can be before it is resized upward. Specifically, when the number of elements
is greater
11. than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded.
12. If you do not specify a fill ratio, then 0.75 is used.
13.
14. Hashtable(Map< ? extends K, ? extends V> m) //This creates a hash table that is initialized
with the
15. elements in m. The capacity of the hash table is set to twice the number of elements in m.
The default load factor of 0.75 is used.

Example of Hashtable
import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
Hashtable< String,Integer> ht = new Hashtable< String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));

Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
}
}
}

a 100
b 200
c 300
d 400

Difference between HashMap and Hashtable

Hashtable HashMap

Hashtable class is synchronized. HashMap is not synchronized.

Because of Thread-safe, Hashtable is slower HashMap works faster.


than HashMap

Neither key nor values can be null Both key and values can be null
Order of table remain constant over time. does not guarantee that order of map will remain
constant over time.

Properties class

1. Properties class extends Hashtable class.


2. It is used to maintain list of value in which both key and value are String
3. Properties class define two constructor
4. Properties() //This creates a Properties object that has no default values
5.
Properties(Properties propdefault) //This creates an object that uses propdefault for its default
values.

6. One advantage of Properties over Hashtable is that we can specify a default property that
will be useful when no value is associated with a certain key.

Note: In both cases, the property list is empty

7. In Properties class, you can specify a default property that will be returned if no value is
associated with a certain key.

Example of Properties class


import java.util.*;

public class Test


{

public static void main(String[] args)


{
Properties pr = new Properties();
pr.put("Java", "James Ghosling");
pr.put("C++", "Bjarne Stroustrup");
pr.put("C", "Dennis Ritchie");
pr.put("C#", "Microsoft Inc.");
Set< ?> creator = pr.keySet();

for(Object ob: creator)


{
System.out.println(ob+" was created by "+ pr.getProperty((String)ob) );
}

Java was created by James Ghosling


C++ was created by Bjarne Stroustrup
C was created by Dennis Ritchie
C# was created by Microsoft Inc

Stack class

1. Stack class extends Vector.


2. It follows last-in, first-out principle for the stack elements.
3. It defines only one default constructor

Stack() //This creates an empty stack

4. If you want to put an object on the top of the stack, call push() method. If you want to
remove and return the top element, call pop() method. An EmptyStackException is thrown if
you call pop() method when the invoking stack is empty.
You can use peek() method to return, but not remove, the top object. The empty() method returns
true if nothing is on the stack. The search() method determines whether an object exists on the
stack and returns the number of pops that are required to bring it to the top of the stack.

Example of Stack
import java.util.*;

class StackDemo {
public static void main(String args[]) {
Stack st = new Stack();
st.push(11);
st.push(22);
st.push(33);
st.push(44);
st.push(55);
Enumeration e1 = st.elements();

while(e1.hasMoreElements())
System.out.print(e1.nextElement()+" ");

st.pop();
st.pop();

System.out.println("\nAfter popping out two elements");

Enumeration e2 = st.elements();

while(e2.hasMoreElements())
System.out.print(e2.nextElement()+" ");

}
}
11 22 33 44 55
After popping out two elements
11 22 33

Dictionary class

1. Dictionary is an abstract class.


2. It represents a key/value pair and operates much like Map.
3. Although it is not currently deprecated, Dictionary is classified as obsolete, because it is fully
superseded by Map class.

Applet in Java

 Applets are small Java applications that can be accessed on an Internet server, transported
over Internet, and can be automatically installed and run as apart of a web document.
 After a user receives an applet, the applet can produce a graphical user interface. It has
limited access to resources so that it can run complex computations without introducing the
risk of viruses or breaching data integrity.
 Any applet in Java is a class that extends the java.applet.Applet class.
 An Applet class does not have any main() method. It is viewed using JVM. The JVM can use
either a plug-in of the Web browser or a separate runtime environment to run an applet
application.
 JVM creates an instance of the applet class and invokes init() method to initialize an Applet.

A Simple Applet
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}

Every Applet application must import two packages - java.awt and java.applet.
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user
(either directly or indirectly) through the AWT. The AWT contains support for a window-based,
graphical user interface. java.applet.* imports the applet package, which contains the class
Applet. Every applet that you create must be a subclass of Applet class.
The class in the program must be declared as public, because it will be accessed by code that is
outside the program.Every Applet application must declare a paint() method. This method is
defined by AWT class and must be overridden by the applet. The paint() method is called each
time when an applet needs to redisplay its output. Another important thing to notice about applet
application is that, execution of an applet does not begin at main() method. In fact an applet
application does not have any main() method.

Advantages of Applets

1. It takes very less response time as it works on the client side.


2. It can be run on any browser which has JVM running in it.

Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that load
and play audio clips.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.

 init() : init() is the first method to be called. This is where variable are initialized. This
method is called only once during the runtime of applet.
 start() : start() method is called after init(). This method is called to restart an applet after it
has been stopped.
 stop() : stop() method is called to suspend thread that does not need to run when applet is not
visible.
 destroy() : destroy() method is called when your applet needs to be removed completely
from memory.

Note: The stop() method is always called before destroy() method.

Example of an Applet Skeleton


import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public void init()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop()
{
//suspend execution
{
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}

Example of an Applet
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
g.drawRoundRect(10, 30, 120, 120, 2, 3);
}
}

How to run an Applet Program


An Applet program is compiled in the same way as you have been compiling your console
programs. However there are two ways to run an applet.

 Executing the Applet within Java-compatible web browser.


 Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes
your applet in a window

For executing an Applet in an web browser, create short HTML file in the same directory.
Inside bodytag of the file, include the following code. (applet tag loads the Applet class)
< applet code = "MyApplet" width=400 height=400 >
< /applet >
Run the HTML file

Running Applet using Applet Viewer


To execute an Applet with an applet viewer, write short HTML file as discussed above. If you
name it as run.htm, then the following command will run your applet program.
f:/>appletviewer run.htm
Event Handling
Any program that uses GUI (graphical user interface) such as Java application written for
windows, is event driven. Event describes the change in state of any object. For Example
: Pressing a button, Entering a character in Textbox, Clicking or Dragging a mouse, etc.

Components of Event Handling


Event handling has three main components,

 Events : An event is a change in state of an object.


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified when an
event occurs.

How Events are handled ?


A source generates an Event and send it to one or more listeners registered with the source. Once
event is received by the listener, they process the event and then return. Events are supported by
a number of Java packages, like java.util, java.awt and java.awt.event.
Important Event Classes and Interface

Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu-item is ActionListener


selected, list-item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and also when
it enters or exit a component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is TextListener


changed

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

WindowEvent generated when window is activated, deactivated, WindowListener


deiconified, iconified, opened or closed

ComponentEvent generated when component is hidden, moved, ComponentEventListener


resized or set visible

ContainerEvent generated when component is added or removed ContainerListener


from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener


FocusEvent generated when component gains or loses FocusListener
keyboard focus

Steps to handle events:

1. Implement appropriate interface in the class.


2. Register the component with the listener.

Example of Event Handling


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class Test extends Applet implements KeyListener


{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
HTML code :
< applet code="Test" width=300, height=100 >

Abstract Window Toolkit(AWT)


AWT contains large number of classes and methods that allows you to create and manage
graphical user interface ( GUI ) applications, such as windows, buttons, scroll bars,etc. The
AWT was designed to provide a common set of tools for GUI design that could work on a
variety of platforms. The tools provided by the AWT are implemented using each platform's
native GUI toolkit, hence preserving the look and feel of each platform. This is an advantage of
using AWT.But the disadvantage of such an approach is that GUI designed on one platform may
look different when displayed on another platform.
AWT is the foundation upon which Swing is made i.e Swing is a set of GUI interfaces that
extends the AWT. But now a days AWT is merely used because most GUI Java programs are
implemented using Swing because of its rich implementation of GUI controls and light-weighted
nature.

AWT Hierarchy

Component class
Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all the attributes of visual component. A component object is responsible for
remembering the current foreground and background colors and the currently selected text font.

Container
Container is a component in AWT that contains another component like button, text field, tables
etc. Container is a subclass of component class. Container class keeps track of components that
are added to another component.
Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or
border. It is container that is used for holding components.

Window class
Window class creates a top level window. Window does not have borders and menubar.

Frame
Frame is a subclass of Window and have resizing canvas. It is a container that contain several
different components like button, title bar, textfield, label etc. In Java, most of the AWT
applications are created using Frame window. Frame class has two different constructors,
Frame() throws HeadlessException

Frame(String title) throws HeadlessException

Creating a Frame
There are two ways to create a Frame. They are,

1. By Instantiating Frame class


2. By extending Frame class

Creating Frame Window by Instantiating Frame class


import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame.
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame.
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true.
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}

Creating Frame window by extending Frame class


package testawt;

import java.awt.*;
import java.awt.event.*;

public class Testawt extends Frame


{
public Testawt()
{

Button btn=new Button("Hello World");


add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("StudyTonight"); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.

public static void main (String[] args)


{
Testawt ta = new Testawt(); //creating a frame.
}
}
Points to Remember:

1. While creating a frame (either by instantiating or extending Frame class), Following two
attributes are must for visibility of the frame:
o setSize(int width, int height);
o setVisible(true);
2. When you create other components like Buttons, TextFields, etc. Then you need to add it to
the frame by using the method - add(Component's Object);
3. You can add the following method also for resizing the frame - setResizable(true);

Swing
Swing Framework contains a set of classes that provides more powerful and flexible GUI
components than those of AWT. Swing provides the look and feel of modern Java GUI. Swing
library is an official Java GUI tool kit released by Sun Microsystems. It is used to create
graphical user interface with Java.
Swing classes are defined in javax.swing package and its sub-packages.
Main Features of Swing Toolkit

1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel

Swing and JFC


JFC is an abbreviation for Java Foundation classes, which encompass a group of features for
building Graphical User Interfaces(GUI) and adding rich graphical functionalities and
interactivity to Java applications. Java Swing is a part of Java Foundation Classes (JFC).

Features of JFC

 Swing GUI components.


 Look and Feel support.
 Java 2D.
AWT and Swing Hierarchy

Introduction to Swing Classes


JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout,
FlowLayout. JPanel is descended directly from JComponent.
JFrame : JFrame is Swing's version of Frame and is descended directly from Frame class. The
component which is added to the Frame, is refered as its Content.
JWindow : This is Swing's version of Window and has descended directly from Window class.
Like Window it uses BorderLayout by default.
JLabel : JLabel has descended from JComponent, and is used to create text labels.
JButton : JButton class provides the functioning of push button. JButton allows an icon, string
or both associated with a button.
JTextField : JTextFields allow editing of a single line of text.
Creating a JFrame
There are two ways to create a JFrame Window.

1. By instantiating JFrame class.


2. By extending JFrame class.

Creating JFrame window by Instantiating JFrame class


import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class First
{
JFrame jf;
public First() {
jf = new JFrame("MyWindow"); //Creating a JFrame with name MyWindow
JButton btn = new JButton("Say Hello");//Creating a Button named Say Hello
jf.add(btn); //adding button to frame
jf.setLayout(new FlowLayout()); //setting layout using FlowLayout object
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close operation.
jf.setSize(400, 400); //setting size
jf.setVisible(true); //setting frame visibility
}
public static void main(String[] args)
{
new First();
}
}
Creating JFrame window by extending JFrame class
import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class Second extends JFrame
{
public Second()
{
setTitle("MyWindow"); //setting title of frame as MyWindow
JLabel lb = new JLabel("Welcome to My Second Window");//Creating a label named Welcome
to My Second Window
add(lb); //adding label to frame.
setLayout(new FlowLayout()); //setting layout using FlowLayout object.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close operation.
setSize(400, 400); //setting size
setVisible(true); //setting frame visibility
}
public static void main(String[] args)
{
new Second();
}
}

Points To Remember

1. Import the javax.swing and java.awt package to use the classes and methods of Swing.
2. While creating a frame (either by instantiating or extending Frame class), following two
attributes are must for visibility of the frame:
3. setSize(int width, int height);
setVisible(true);
4. When you create objects of other components like Buttons, TextFields, etc. Then you need to
add it to the frame by using the method - add(Component's Object);
5. You can add the following method also for resizing the frame - setResizable(true);

Swing Components and Containers


A component is an independent visual control. Swing Framework contains a large set of
components which provide rich functionalities and allow high level of customization. They all
are derived from JComponent class. All these components are lightweight components. This
class provides some common functionality like pluggable look and feel, support for accessibility,
drag and drop, layout, etc.
A container holds a group of components. It provides a space where a component can be
managed and displayed. Containers are of two types:

1. Top level Containers


o It inherits Component and Container of AWT.
o It cannot be contained within other containers.
o Heavyweight.
o Example: JFrame, JDialog, JApplet
2. Lightweight Containers
o It inherits JComponent class.
o It is a general purpose container.
o It can be used to organize related components together.
o Example: JPanel

JButton
JButton class provides functionality of a button. JButton class has three constuctors,
JButton(Icon ic)

JButton(String str)

JButton(String str, Icon ic)


It allows a button to be created using icon, a string or both. JButton supports ActionEvent.
When a button is pressed an ActionEvent is generated.

Example using JButton


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{

testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.

setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}
JTextField
JTextField is used for taking input of single line of text. It is most widely used text component.
It has three constructors,
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
cols represent the number of columns in text field.

Example using JTextField


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends JFrame
{
public MyTextField()
{
JTextField jtf = new JTextField(20); //creating JTextField.
add(jtf); //adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new MyTextField();
}
}
JCheckBox
JCheckBox class is used to create checkboxes in frame. Following is constructor for
JCheckBox,
JCheckBox(String str)

Example using JCheckBox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("no"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}
JRadioButton
Radio button is a group of related button in which only one can be selected. JRadioButton class
is used to create a radio button in Frames. Following is the constructor for JRadioButton,
JRadioButton(String str)

Example using JRadioButton


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JRadioButton jcb = new JRadioButton("A"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("B"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("C"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("none");
add(jcb);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

JComboBox
Combo box is a combination of text fields and drop-down list.JComboBox component is used to
create a combo box in Swing. Following is the constructor for JComboBox,
JComboBox(String arr[])

Example using JComboBox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.
public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list of name.
add(jc); //adding JComboBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

A program to change background color of a frame (Using Action Event)


import java.awt.*; //importing awt package
import javax.swing.*; //importing swing package
import java.awt.event.*; //importing event package
//For an event to occur upon clicking the button, ActionListener interface should be implemented
class StColor extends JFrame implements ActionListener{

JFrame frame;
JPanel panel;
JButton b1,b2,b3,b4,b5;

StColor(){

frame = new JFrame("COLORS");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new JPanel(); //Creating a panel which is a container and will hold all the buttons
panel.setSize(100, 50);

b1 = new JButton("BLUE"); //Creating a button named BLUE


b1.addActionListener(this); //Registering the button with the listener

b2 = new JButton("RED"); //Creating a button named RED


b2.addActionListener(this); //Registering the button with the listener

b3 = new JButton("CYAN");//Creating a button named CYAN


b3.addActionListener(this);//Registering the button with the listener

b4 = new JButton("PINK"); //Creating a button named PINK


b4.addActionListener(this); //Registering the button with the listener

b5 = new JButton("MAGENTA"); //Creating a button named MAGENTA


b5.addActionListener(this); //Registering the button with the listener

//Adding buttons to the Panel


panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(b4);
panel.add(b5);

frame.getContentPane().add(panel); //adding panel to the frame


frame.setSize(500,300);
frame.setVisible(true);
frame.setLayout(new FlowLayout());

}
//The below method is called whenever a button is clicked
@Override
public void actionPerformed(ActionEvent e) {

//This method returns an object of the button on which the Event-


Pressing of button initially occurred
Object see = e.getSource();

if(see ==(b1)){ //Checking if the object returned is of button1


frame.getContentPane().setBackground(java.awt.Color.blue); //changing the panel color to
blue
}
if(see == b2){ //Checking if the object returned is of button2
frame.getContentPane().setBackground(java.awt.Color.red); //changing the panel color
to red
}
if(see == b3){ //Checking if the object returned is of button3
frame.getContentPane().setBackground(java.awt.Color.cyan);//changing the panel color to
cyan
}
if(see == b4){ //Checking if the object returned is of button4
frame.getContentPane().setBackground(java.awt.Color.pink); //changing the panel color
to pink
}
if(see == b5){ //Checking if the object returned is of button5
frame.getContentPane().setBackground(java.awt.Color.magenta); //changing the panel
color to magenta
}
}
}

class Test {
public static void main(String[] args) {
StColor o = new StColor();
}
}

Ouput:

Reflection API
Reflection means ability of a software to analyze itself. In Java, Reflection API provides facility
to analyze and change runtime behaviour of a Class, at runtime.
For example, using reflection at the runtime you can determine what method, field, constructor
or modifers a class supports.
What is reflect package ?
java.lang.reflect package encapsulates several important interfaces and classes. These classes and
interface define methods which are used for reflection.

Some Important Classes of java.lang.reflect package

Class What it does ?

Array allow you to dynamically create and manipulate arrays

Constructor gives information about constructor of a class

Field provide information about field

Method provide information about method

Modifier provide information about class and member access modifier

Proxy supports dynamic proxy classes

Apart from these classes java.lang.Class is another very important class used in Reflection API.

Uses of Reflection

 Developing IDE
 Debugging and Test tools
 Loading drivers and providing dynamic information
Disadvantages of Reflection

 Low performance
 Security risk
 Violation of Oops concept

java.lang.Class class
Class is a final class in java.lang package which extends Object class. Instance of this class
represents classes and interfaces in a running Java application. It is used to analyze and change
dynamic behaviour of a class at runtime.

Some Important Methods of java.lang.Class class


This class defines several methods using which we can get information
about methods, constructors, modifiers and members of a class at runtime.

forName()
This method takes fully qualified name of classes or interface as its argument and returns
instance of the class assocaited with it. Syntax
static Class< ?> forName(String className)

Example using forName() method


class Student{}
class Test
{
public static void main(String args[])
{
Class c = Class.forName("Student");
System.out.println(c.getName());
}
}

Student

getConstructors() and getDeclaredConstructors()


getConstructors() method returns array of Constructors object that represent all the public
constructors of the invoking object. Remember, this method only returns public constructors. If
you want to see all the declared constructors of a class then use getDeclaredConstructors().
Following is the general syntax of both,
Constructor< ?>[] getConstructors();
Constructor< ?>[] getDeclaredConstructors();

Example using getConstructors() and getDeclaredConstructors() method


import java.lang.reflect.*;
class Student
{
public Student(){}
public Student(String name){}
}

class Test
{
public static void main(String args[])
{
try
{
Class c = Class.forName("Student");
Constructor< Student>[] ct = c.getConstructors();
for(int i=0; i< ct.length; i++)
{ System.out.println(ct[i]); }
Constructor< Student>[] cdt = c.getDeclaredConstructors();
for(int i=0;i< cdt.length;i++)
{ System.out.println(cdt[i]);}

}
catch(Exception e)
{ e.printStackTrace();}
}
}

public Student()
public Student()
Student(java.lang.String)

getMethods() and getDeclaredMethods()


getMethods() method returns array of Method object that reflect all the public method of
invoking object. getDeclaredMethods() returns only the declared methods of the invoking class
object. Syntax for both is following,
Method< ?>[] getMethods();
Method< ?>[] getDeclaredMethods();

Example using getDeclaredMethods() method


import java.lang.reflect.*;
class Student
{
public void show(){}
void display(){}
}

class Test
{
public static void main(String args[])
{
try
{
Class c = Class.forName("Student");
Method md[] = c.getDeclaredMethods();
for(int i=0; i< md.length; i++ )
{ System.out.println(md[i]); }
}
catch(Exception e)
{ e.printStackTrace();}
}
}

public void Student.show()


void Student.display()

getFields() and getDeclaredFields()


getFields() returns an array containing Field objects reflecting all the accessible public members
of the class or interface represented by this Class object. getDeclaredFields() returns array of
Field objects reflecting all the fields declared by the class or interface represented by this Class
object.
Field< ?>[] getFields();
Field< ?>[] getDeclaredFields();

Example using getFields() and getDeclaredFields() method


import java.lang.reflect.*;
class Student
{
public String name;
int roll;
}

class Test
{
public static void main(String args[])
{
try
{
Class c = Class.forName("Student");
Field ff[] = c.getFields();
for(int i=0; i< ff.length; i++)
{ System.out.println(ff[i]); }
Field f[] = c.getDeclaredFields();
for(int i=0;i< f.length; i++)
{ System.out.println(f[i]); }
}
catch(Exception e)
{ e.printStackTrace();}
}
}

public java.lang.String Student.name


public java.lang.String Student.name
int Student.roll

RMI
Remote method invocation(RMI) allow a java object to invoke method on an object running on
another machine. RMI provide remote communication between java program. RMI is used for
building distributed application.
Concept of RMI application
A RMI application can be divided into two part,Client program and Server program.
A Server program creates some remote object, make their references available for the client to
invoke method on it. A Client program make request for remote objects on server and invoke
method on them. Stub and Skeleton are two important object used for communication with
remote object.

Stub and Skeleton


Stub act as a gateway for Client program. It resides on Client side and communicate
with Skeletonobject. It establish the connection between remote object and transmit request to it.

Skeleton object resides on server program. It is responsible for passing request from Stub to
remote object.

Creating a Simple RMI application involves following steps

 Define a remote interface.


 Implementing remote interface.
 create and start remote application
 create and start client application
Define a remote interface
A remote interface specifies the methods that can be invoked remotely by a client. Clients
program communicate to remote interfaces, not to classes implementing it. To be a remote
interface, a interface must extend the Remote interface of java.rmi package.
import java.rmi.*;
public interface AddServerInterface extends Remote
{
public int sum(int a,int b);
}

Implementation of remote interface


For implementation of remote interface, a class must either extend UnicastRemoteObject or use
exportObject() method of UnicastRemoteObject class.
import java.rmi.*;
import java.rmi.server.*;
public class Adder extends UnicastRemoteObject implements AddServerInterface
{
Adder()throws RemoteException{
super();
}
public int sum(int a,int b)
{
return a+b;
}
}

Create AddServer and host rmi service


You need to create a server application and host rmi service Adder in it. This is done
using rebind()method of java.rmi.Naming class. rebind() method take two arguments, first
represent the name of the object reference and second argument is reference to instance
of Adder
import java.rmi.*;
import java.rmi.registry.*;
public class AddServer{
public static void main(String args[]){
try{
AddServerInterface addService=new Adder();
Naming.rebind("AddService",addService);
//addService object is hosted with name AddService.

}catch(Exception e){System.out.println(e);}
}
}

Create client application


Client application contains a java program that invokes the lookup() method of
the Naming class. This method accepts one argument, the rmi URL and returns a reference to an
object of type AddServerInterface. All remote method invocation is done on this object.
import java.rmi.*;
public class Client{
public static void main(String args[]){
try{
AddServerInterface st=(AddServerInterface)Naming.lookup("rmi://"+args[0]+"/AddService");
System.out.println(st.sum(25,8));
}catch(Exception e){System.out.println(e);}
}
}

Steps to run this RMI application


Save all the above java file into a directory and name it as "rmi"

 compile all the java files

javac *.java
 Start RMI registry

start rmiregistry
 Run Server file

java AddServer
 Run Client file in another command prompt abd pass local host port number at run time

java Client 127.0.0.1

Vous aimerez peut-être aussi