Você está na página 1de 216

Java

Java is a technology and it has 2 things

1.programming language

2.platform

Note: java is not only programming language it is also a platform. Java programming
language used to develop apptions and services

Apption: an apption is a program in which we interact with on the desktop.

Types of apptions:

1.stand alonone apptions

2.distributed apptions

1.standalone apption:

A stand alone apption is an apption which runs on only one system

2.distributed apption:

A distributed apption is an apption which runs on two or more systems

Types of stand alone apptions:

1.console apptions:(character user interface (CUI))

2.window apptions(Graphical user interface(GUI)

console apptions:

a console apption is an apption in which we interact with commands by using keyboard


ex: command prompt, sql prompt…. Etc.

window apptions:

a window apption is an apption in which we interact with keyboard and mouse

Ex: Ms-word,Ms-excel, Ms-powerpoint….etc

Types of distributed apption:-

1.Web apptions

2.Enterprise apptions

Web apption: it is a distributed apptions which runs on web browser and web server.

Types of web apptions:

1.static web apptions

2.dynamic web apptions

1.Static web apption:

A static web apption is a web apption which resides in server and executes in browser

Static web apptions can be developed by using HTML, java script, VB script…etc

2. Dynamic web apptions:

A dynamic web apption is a web apption which resides in server and executes in server
only

dynamic web apptions can be developed by using Servlets, java server pages…etc
Enterprise apption:

An enterprise apption is a distributed apption which performs business functions.

Ex: ATM banking, Railway reservation system…etc

Services:

A service is a process and process is an instance of .exe file

Ex: Notepad Notepad

Notepad.exe

Services used by apptions to run under operating system.

Types of services:

1.window services

2. Web services

1.Window service: it is a service and it is used by window apption to run under operating
system

2. Web service: it is a method of communication b/w 2 electronic devices

Platform: it can be a software or hardware environment in which program runs

There are 4 java platforms:

1.javaSE

2.javaEE

3.javaME
4.javaFX

1.javaSE

It is the widely used java platform for developing console apptions, window apption and
static web apptions.

2.javaEE

It is a widely used java platform for developing dynamic web apptions, enterprise
apptions and services.

3.javaME

it is a platform designed for embedded systems. Embedded devices are industrial


controls, mobile phones, TV set-up boxes

4.javaFX:

It is java platform designed for rich internet apptions. Rich internet apptions means
which contains more graphics

JDK
JDK stands for Java Development Kit.It physically exists.It contains JRE + development
tools.

JRE
JRE stands for Java Runtime Environment. It is used to provide runtime environment. It
is the implementation of JVM. It physically exists. It contains set of libraries +
other files that JVM uses at runtime. Jre is part of jdk

JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.

The JVM performs following main tasks:

Loads code

Verifies code

Executes code

Provides runtime environment

Declaration rules for a source file(.java)


A source file can have only one public class

A source file can have any no of non public classes.

If the source file contains public class then file neme must match with public class name

If the source file does not contain public class then no naming restriction to file name

If we define a class in side the package then then package statement must be declared at
first line in the source file.

Inside a source file, import statements must be declared between package statement and
class declaration.

Note: If there is no package statement then import statement must be declared at first
line.

Java notations : (java coding standards)


When ever we are writing the code it is highly recommended to follow coding
conventions the name of the method or class reflect the purpose of functionality
of that component

.
1.package & subpackage: all small letters. Sub packages are separated with( ) symbol

Ex: 1.java.lang

2.Java.awt.event
2.class and interface:

Usually class names are nouns, should starts with Upper case letter. If ti contains
multiple words every inner word should starts with upper case letterl. No space
between words

Ex: 1.String

2.StringBuffer

3.ArrayIndexOutOfBoundsException

Usually interface names are adjectives should starts with uppercase letter and if it
contains multiple words everyh inner word should starts with uppercase letter.
No space between the words

1.Serializable

2.Runnable

3.Cloneable

3.variable and method: second word onwards first letter of the word is capital. No space
between words

Ex.

1.empNo

2.netIncome

3.compareTo( )

4.toString

To compile:

javac filename.java

To:run:

Java classname

Temporary path setting:

C:\> set path=”%path%”.; C:\Program Files\Java\jdk1.5.0_21\bin;

Identifiers
A name in the program is an identifier it may be class name or method name,variable
name or label name.

Ex:

1) A java identifier is a sequence of characters, where each character may be a letter


from a-z or A-Z
or a digit form 0-9 or currency symbol $ or connecting punctuation – , if we are using any
other

symbol we will get Compile time error “IllegalCharacter”.

2) Identifier should not be starts with digit.

3) There is no length limit for java identifiers but it is not recommended to take more
than 15

length.

4) Java Identifiers are case sensitive

5.reserve words cannot be used as identifiers.

6.the names of predefined classes and interfaces can be used as identifiers but it is not
recommended.

Reserved Words
Some identifiers are reserved to associate some functionality or to represent values,
such type of reserved identifiers are called “ReservedWords”.

In java total 53 keywords are there. In this 50 key words and 3 reserved literals

Datatypes:
Datatype defines the type of value that can be stored in a particular variable.

It determines what value a variable can hold

Data types are used to specify the how much memory is allocated for
variables.

In java data types are devided into 2 types

1.primitive data types

2.reference data types

1.primitive data types:

There are 8 primitive data types in java and those are named by keywords.
Data type Size Range Default values

byte 1 -128 to 127 0

short 2 -32768 to 32767 0

int 4 -2147483648 to 2147483647 0

long 8 -231 to 231-1 0

float 4 -3.4e38 to 3.4e38 0.0

double 8 -1.7e308 to 1.7e308 0.0

char 2 0 to 65535 Single space character

boolean NA Not Appble False

Reference datatype:
Arrays,Strings,Classes, Interfaces

Literals:-

Literal is a constant value assigned to the variables.


Integral Literal
We can specify an integral literal in the following ways.

Decimal literals: allowed digits are 0 to 9

Octal literals: allowed digits are 0 to 7 but here literal value should be prefixed with
0(zero)

Hexadecimal literals: the allowed digits are 0 to 9, A- F (Both lower, Upper case) literals

should be prefixed with 0x or 0X

class Demo

public static void main(String arg[])


{

int x = 10;

int y = 010;

int z = 0x10;

System.out.println(x + "..." + y + "..." + z);

Note: By default every integral lateral is of int datatype

An integral literal is of long type should suffixing with l or L.

Floating – point literals


By default floating-point literals are double type we can specify explicitly as float type by
suffixing

with ‘f’ or ‘F’.

A. float f = 10.5; X C.E possible loss of precision

B. float f = 10.5f;

we can specify explicitly a floating point literal of double type by suffixing with d or D.

double d = 10.5D;

Boolean Literals
The only allowed values for boolean datatype are true, false.

1. boolean b = true;

character literal
A char literal can be represented as a single character with in single quotes.

Ex:

char ch = 'a';
we can represent a char literal by using it’s Unicode value. For the allowed Unicode
values are 0 to

65535.

Ex:

char ch = 97;

System.out.println(ch);  O/P: a

String literal
A sequence of character with in double quotes is String literal.

String s = "Java";

Variable:

A variable is a container which contains data

A Java variable is a piece of memory that can contain a data


value. every variable has a data type .
Declaration: datatype variable;

Ex: int a;

Assignment:

Variable=literal;

Ex a=10;

Initialization:

Datatype variable=literal;

Ex:

Int x=10;
Note: primitive type variable stores data where as reference variable stores hashcode

Object Oriented Programming:

Java is a object oriented programming language.

A language that supports all the principles of Object Oriented programming is known as
object oriented programming language.

Object Oriented Principles:

1.Encapsulation

2.Abstraction

3.Inheritance

4.Polymorphism

To use the above principles in a java programming we need following language


constructs.

1.Class

2.Object

1.Class:
A class is a collection of variables and methods.

“A class is a way of binding the data and associated methods in a single unit”.

Any JAVA program if we want to develop then that should be developed with respect
class only i.e., without class there is no JAVA program.

Syntax:

class class_name

Datatype variable1;
Datatype variable2;

--------

returntype method_name(arguments list)

---method definition

Note: class will not occupy memory where as file occupies memory.

2.Object:

An instance of a class is called object.

In order to store the data for the data members of the class, we must create an object.

Instance (instance is a mechanism of allocating sufficient amount of memory space for


data members of a class) of a class is known as an object.

Class variable is known as an object.

Syntax-1 for defining an OBJECT:

classsname objectname = new classsname();

Ex: Demo ob=new Demo( );

“ob” is called as Object name or Reference variable or Object Refrence

“new” is called dynamic memory allocation operator. Because it allocates the memory at
runtime.

Emp e1=new Emp( );

e1 Emp object
eno
data

Hashcode

Reference variable

Each and every object occupies memory.

Every object reference also occupies memory


Object contains data where object reference contains hashcode
hash code is an unique id number allocated to an object by JVM. The
hashcode of a Java Object is simply a number, it is 32-bit signed int

Types of variables:
Instance variables
Class variables.
Local variables
Instance variables:
If the value of the variable is varied from object to object such
type of variables are called instance variable
The scope of the instance variable is exactly same as the object
because instance variables are created at the time of object
creation and will be destroyed at the time of object
destruction
Instance variables should be declared inside the class and out
side the method and constructors.
Instance variables cannot be accessed from static area directly
we can access by using object or object reference
A variable which is defined as a member of a class is know as an
instance variable
Memory allocated to instance variable ever an object is created
Instance variables are stored in heap area.
Separate copy of instance variable exist for every instance
There are two ways to access instance variables
1.by using object
2.by using object reference
Use object to access instance variable if it is required only one
time
Use object reference to access instance variable if it is required
more than one time
For instance variables it is not required to perform
initialization explicitely , jvm will provide default values

Static variables/class variables:


A variable which is defined inside a class and out side the
methods and constructros with static modifier is called as
static variable or class variable.
Memory allocated to class variables when class is loaded .
Class variables are stored in method area.
The value of static variable is not varies from object to object,
for all the objects only one copy of static variable is
available. Static variables are called as class level variables
Static variables are created at the time of class loading and
destroyed at the time of class is unloading. Hence the scope
of the static variable is exactly same as the scope of the
class.
Static variables are created at the time of class loading i.e.(at
the beginning of the program) hence we can access from
both instance and static area directly
For the static variables it is not required to perform
initialization explicitely compulsory jvm will provide
default values
There are 4 ways to access class variables
1.directly
2.by using class name
3.by using object
4.by using object reference
Last two ways are not recommended
Access class variables directly if they are present in the same
class.
Use class name to access the static variables if they are present
in the different class.
If we perform any changes to the static variables using one
object it will reflect in remaining objects also because
single copy will be shared by all the objects
Local variables:
To meet temporary requirements of the programmer some
times we have to create the variables inside the method or
a block or constructors . such type of variables are called
as local variables
Memory is allocated to local variables when ever a
method/block/constructor is called
Local variables are stored in stack area of the memory
Note: local variables cannot be static in java.
There is only one way to access the local variables i.e. directly.
For the local variable jvm wont provide any default values,
compulsory we should perform initialization explicitely,
before using that variable.
The only appble modifier for local variables is final.
Arrays:
array is a collection of similar type of elements that have contiguous memory location.

Java array is an object the contains elements of similar data type.

An array is an indexed collection of fixed number of homogenous data elements

The main advantage of arrays is we can represent a group of values with single name
hence readability of the code will be improved

The main limitation of arrays is they are fixed in size.i.e once we constructed an array
there is no chance of increasing or decreasing bases on our requirement
Array Declaration,Construction &Initialization

Array Declaration:
The following are the ways to declare an array.

int [] a;

int a[];

int [] a;

At the first time of declarations we are not allowed to specify the size. Violation leads to
compile time

Declaring Multidimensional Arrays

int[ ][ ] a;

int a[][];

int [][]a;

int[] a[];

int[] []a;

Construction of Arrays

Single Dimension : Arrays are internally implemented as object hence by using new
operator we can construct an array. Compulsory at the time of construction we
should specify the size otherwise compile time error.

int[] a = new int[10];//valid

int[] a = new int[];//invalid

It is legal to have an array with size 0 there is no compile time error or run time error.

int[] a = new int[0];

If we are specifying array size with some –ve integer we will get run time exception
saying NegativeArraySizeException.

int[] a = new int[-10];

The only allowed Data type to allow the size are byte, short,char,int. if we are using any
other datatype we will get a compile time error.

int[] a = new int[10];

int[] a1 = new int[100];

int[] a = new int[10L]; // compile time error: possible loss of precision found: long

required: int

int[] a = new int[10.5];// compile time error


int[] a = new int[true]; // compile time error: Incompatible types found : boolean
required:int.

Multi Dimension: In java multidimensional arrays are implemented as single dimension


arrays. This approach improves performance with respect to memory.

int[][] a = new int[3][2];

int[][] a = new int[4][]

a[0] = new int[1];

a[1] = new int[2];

a[2] = new int[4];

a[3] = new int[3];

Initialization of arrays

Once we created an array all it’s elements initialized with default values. If we are
providing any explicit initialization then default values will be overridden with
our provided values.

Example:1
int[] a = new int[3];

System.out.println(a[0]);//Output: 0

System.out.println(a);//O/P: [I@12dacd1

when ever we are trying to access an array with int index which is not in valid range
then we will get runtime exception saying “ArrayIndexOutOfBoundsException”
but there is no compile time error.
If we are trying to access an array index with the following datatype we will get
compile time error.
float, double, long, boolean.

Declaration Construction and Initialization in a single line


int []a;
a = new int[3];
a[0] = 10;
a[1] = 20;
a[2] = 30;
All the above statements we can replace with a single line as
follows.
int[] a = {10,20,30};
If we want to use the above shortcut technique compulsory we
should perform declaration,construction initialization in a
single line only. If we are dividing into 2 lines we will get
compile time error.
int[][] a = {{10,20},{30,40,50}};
int[][][] a = {{{10,20},{30,40}},{{50,60},{70,80}}};
Array length:

length is a final variable which is used to find the length(no of


characters of an array)
Anonymous Arrays

Some times we can declare an array with out name also such
type of arrays are called anonymous arrays.
The main objective of anonymous arrays is just for temporary
usage. We can create an anonymous arrays as follows.
new int[]{10,20,30,40}
Package
package in java is an encapsulation mechanism to group related classes and interfaces
into a single

module. The main objective of package is to resolve naming conflicts.

There is universally accepted convention to name the package i.e to use internet domain
name in

reverse.
a package is a collection of subpackage, classes , interface

java library organised in the form of packages

it is an encapsulation mechanism to group related classes and interfaces into a single


module

the main purpose of packages are

1.to resolve naming conflicts

2.to provide security to the classes and interfaces so that out side person

cant access directly

3.it improves modularity of the apption

there is one universally accepted convension to name packages i.e. to use

intertent domain name in reverse

Compile:

javac –d . Test.java

-d means destination to place generated class files “.” means current working directory.

Generated class file will be placed into corresponding package structure.

If the specified package structure is not already available then this command itself will

create the required package structure.

As the destination we can use any valid directory.

If the specified destination is not available then we will get compile time error.

How to execute package program:java com.rajusoft Test


package com.rajusoft;

class Test

public static void main(String arg[])

System.out.println("package name");

The first non-comment statement in any java source file is package statement.
import Statement
the main objective of import statement is it acts as typing shortcut.

1) implicit class import.

2) explicit class import.

Explicit class import:

Example: Import java.util.ArrayList

This type of import is highly recommended to use because it improves readability of the

code.

Implicit class import:

Example: import java.util.*;

It is never recommended to use because it reduces readability of the code.

class MyArrayList extends java.util.ArrayList

The code compiles fine even though we are not using import statements because we

used fully qualified name.

Whenever we are using fully qualified name it is not required to use import statement.
Similarly whenever we are using import statements it is not require to use fully qualified

name.

static imports
The main objective of static imports is to import static members of a particular class

Without static import:

class Test

public static void main(String args[]){

System.out.println(Math.sqrt(4));

System.out.println(Math.max(10,20));

System.out.println(Math.random());

}}

With static import:

import static java.lang.Math.*;

class Test

public static void main(String arg[])

System.out.println(sqrt(4));

System.out.println(random());

System.out.println(max(10,20));

}
class modifier

when ever we are writing our own classes compulsory we should provide information about
our class to the JVM like.

1) child class creation is possible or not

2) Instantiation is possible or not

3) Whether we can access this class from any where

We can specify this information by declaring the corresponding modifier.

The only appble modifier for the top level classes are

public, <default>, final, abstract, strictfp

For the inner classes the appble modifiers are

public, <default>, final, abstract, strictfp, private, protected, static

public classes
If a class declared as the public then we can access that class from any where.

<default> classes
If a class declared as default then we can access that class only in the current package.
<default>

access is also known as package level access.

abstract
abstract is the modifier appble only for classes and methods i.e we can’t use abstract for

variables.

If we don’t know about implementation still we are allowed to declare methods with
abstract

modifier.

abstract method should have only declaration but not implementation hence abstract
method

declaration should ends with ;(semicolon)

child class is responsible to provide implementation for abstract methods.

abstract never talks about implementation, if any modifier talks about implementation it is

considered as illegal combination with abstract.

Hence the following 6 combinations are illegal.

abstract final
synchronized
native
static
strictfp
private

If we don’t want instantiation for any class such type of classes we have to declare with
abstract

modifier. i.e for abstract classes instantiation is not possible

If a class contain at least one abstract method then the corresponding class should be
declared as

abstract otherwise C.E.


Even though class doesn’t contain any abstract method still we can declare that class with
abstract

modifier.i.e abstract class can contain zero no of abstract methods.

If we are creating any child class for abstract class then compulsory we should provide

implementation for all abstract methods of parent class other wise the child class also
should be

declared as abstract

final
final is the modifier appble for classes, methods and variables.

If a method is not allowed to override in the child class then we should declare that method
as ‘final’.

i.e for the final methods overriding is not possible.

for any class if we are not allow to create child class, such type of classes we have to declare
with

final i.e for final classes inheritance is not possible.

final method should not be overridden but we should override abstract method to provide

implementation. Hence final & abstract combination is always illegal for both method and
class

public abstract final void m1(){}X

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

abstract and strictfp is a legal combination for the classes(Illegal for the methods)
member modifiers

public members
we can access public members from any where but the corresponding class must be visible.

<default> members
If a member declared as a default we can access that member only in the current package.

private members
If a member declared as private we can access that member only in the current class.

protected members
If a member declared as protected then we can access that member from any where with in
the

current package and only in child classes from outside package.

We can access protected members from outside package only in child class.

And we should use child class reference only. i.e parent class reference is not allowed to
access protected members from

outside package violation leads to C.E but in the current package we can access protected
members

either by using parent class reference or by child class reference.

The Most Restricted Modifier is Private.

The Modifier Which provides wide range of access is Public .

Public > Protected > Default > Private

Recommended Modifier for data members is Private.


And for methods is public .

Final Variables
For the Static and instance variables no need to perform initialization, JVM Will Provide
default

initialization.

For the local variables compulsory we should perform initialization before using.

Final Instance Variables


For the final instance variables JVM won’t provide any default values, compulsory we should

perform initialization before completion of constructor.

The following are the places to perform this

1) At the time of declaration:.

final int i = 0;

2) Inside instance initialization block

3) Inside constructor

Final static Variables


For the final static variables compulsory we should perform initialization.

1) At the time of declaration

final static int i = 0;

2) Inside static blocks

Final local Variables


Before using a local variable(whether it is final or non-final) we should perform
initialization. If we

are not using local variable then no need of perform initialization even though it is final.

static Modifier
static is the modifier is appble for methods and variables.

we can’t declare top level classes as static but inner classes can be declares as static( static
nested class).

Instance variables(methods) can’t be accessed from static area directly, But Static members
can be accessed from any where.

abstract and static combination is illegal for methods.

Overloading is possible for static methods.

overriding is not appble for static methods but seems to be overriding is possible, but it is
method hiding.

native
native is the modifier appble only for methods

we can’t declare classes and variables as native.

The methods which are implemented in non-java are called “native methods” or “foreign
methods”.

Synchronized
It is a keyword appble only for methods and blocks. We can’t declare variables and classes
with

synchronized keyword.

If a method declared as synchronized at a time only one thread is allowed to execute on the
given

object. Hence the main advantage of synchronized keyword is we can overcome data
inconsistency

problem.

Use of synchronized keyword may effect performance of the system.


Transient Modifier
transient keyword is used along with instance variables to exclude them from serialization
process.

Transient is the keyword appble only for variables. i.e we can’t apply transient for
methods and classes.

While performing serialization if u don’t want to save the value of a particular variable, that

variable we have declared with transient keyword.

At the time of serialization, JVM ignores the value of transient variable and saves it’s default

value.

i.e Transient means not to serialize.

Declaring a static variable as transient there is no impact.

Similarly declaring final variables with transient keyword creates no impact.

VolatileModifier
Volatile is the keyword appble only for variables. We can’t declare methods and classes with

volatile modifier.

If the value of a variable keep on changing then we have to declare that variable as volatile.

volatile and final is illegal combination for the variables.

Interfaces
1) Introduction.

2) Declaring Interface.
3) Interface Methods.

4) Interface variables.

5) Naming conflicts in interface.

6) Marker/Tag interface.

Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.

The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple
inheritance in Java.

properties of Interface
It is implicitly abstract. So we no need to use the abstract keyword when declaring
an interface.

Each method in an interface is also implicitly abstract, so the abstract keyword is


not needed.

Methods in an interface are implicitly public.

All the data members of interface are implicitly public static final.

How interface is different from class ?


You can not instantiate an interface.

It does not contain any constructors.

All methods in an interface are abstract.

Interface can not contain instance fields. Interface only contains public static final
variables.

Interface is can not extended by a class; it is implemented by a class.

Interface can extend multiple interfaces. It means interface support multiple


inheritance
A class uses the implements keyword to implement an interface.

The allowed modifiers for interface are

public

abstract

strictfp

<default>

When ever we are implementing an interface method compulsory we should declare that
method as

public otherwise compile time error.

extends vs implements
A class can extends only one class at a time. But an interface can extends any no of interfaces

simultaneously.

But an interface can’t implement another interface.

Difference between Abstract class and Interface

Abstract class Interface

It is collection of abstract method and


1 It is collection of abstract method.
concrete methods.

3 It does not support multiple inheritance. It support multiple inheritance.

Abstract class is preceded by abstract


4 It is preceded by Interface keyword.
keyword.

5 Which may contain either variable or Which should contains only constants.
constants.

The default access specifier of abstract There default access specifier of interface
6
class methods are default. method are public.

These class properties can be reused in


These properties can be reused in any other
7 other class using extends
class using implements keyword.
keyword.

Inside abstract class we can take Inside interface we can not take any
8
constructor. constructor.

For the abstract class there is no


For the interface it should be compulsory to
restriction like initialization of
9 initialization of variable at the time of
variable at the time of variable
variable declaration.
declaration.

For the interface variable can not declare


There are no any restriction for abstract
10 variable as private, protected,
class variable.
transient, volatile.

There are no any restriction for abstract For the interface method can not declare
11 class method modifier that method as strictfp, protected, static,
means we can use any modifiers. native, private, final, synchronized.

interface Methods
Every Interface method is by default public and abstract whether we r declaring or not.

As the interface method are by default public and abstract, we r not allowed to use the
following

modifiers.

private

protected

static
final

native

strictfp

synchronized.

Interface variables
An interface can contain variables also every interface variable is by default public static
and final

whether we r declaring or not.

As interface variables already public static and final we r not allowed to declare with the
following

modifiers.

private, protected, volatile, transient.

For the interface variables compulsory we should perform initialization at the time of
declarations

only.

Marker Interface
An interface that have no member is known as marker or tagged interface.

By implementing an interface if our objects will get some ability, Such type of interfaces are
called

“marker” or “taginterface”.

Ex:

Serializable, Clonable interfaces are marked for some ability.

OO CONCEPTS:

Data Hiding
The data should not go out directly i.e outside person is not allowed to access the data this is
nothing but

“Data Hiding”.

The main advantage of data hiding is we can achieve security.

By using private modifier we can achieve this.

Abstraction
Hiding implementation details is nothing but abstraction. The main advantages of
abstraction are we can achieve security as we r not highlighting internal
implementation.

Enhancement will become easy. With out effecting outside person we can change our
internal

implementation.

Hiding of data is known as data abstraction. In object oriented programming language this
is implemented automatically while writing the code in the form of class and object.

It improves maintainability.

Encapsulation
is a process of wrapping of data and methods in a single unit is called encapsulation.
Encapsulation is achieved in java language by class concept.

If a class follows data hiding and abstraction such type of class is said to be ‘Encapsulated’
class.

Encapsulation = Data Hiding + Abstraction

Ex:

class Employee

{
private String name;

public String getName()

return name;

public void setName(String name){

this.name=name;

class Demo

public static void main(String[] args)

Employee e=new Employee();

e.setName("Harry");

System.out.println(e.getName());

The main advantage of using of encapsulation is to secure the data from other methods, when
we make a data private then these data only use within the class, but these data not
accessible outside the class.

. i.e hiding data behind methods

is the central concept of encapsulation.

The main advantages of encapsulation are security, enhancement, maintainability.


Relationships in Java

IS – A RelationShip
In Is-A relationship one class is obtaining the features of another class by using inheritance
concept with extends keywords.

Also known as ‘inheritance’.

Creating a new class from an existing class is called as inheritance

By using extends keyword we can implement inheritance.

The main advantage is reusability.

class Parent

public void methodOne()

{}

class Child extends Parent

public void methodTwo()

{}

Class Test

Public satic void main(String args[ ])


{

Parent p=new Parent();

p.methodOne();

p.methodTwo();

Child c=new Chile();

c.methodOne();

c.methodTwo();

Parent p1=new Child();

P1.methodOne();

P1.methodTwo();

Child c1=new Parent();

Memory allocated to both super class and sub class members when ever object is created to
sub class

1) Whatever the parent has by default available to the child but whatever the child has by

default not available to the parent. Hence on the child reference we can call both parent

and child class methods. But on the parent reference we can call only methods available

in the parent class and we can’t call child specific methods.

2) Parent class reference can be used to hold child class object but by using that reference

we can call only methods available in parent class and child specific methods we can’t

call.

3) Child class reference cannot be used to hold parent class object.


Multiple inheritance:

Having more than one Parent class at the same level is called multiple inheritance with respect to
classes

Any class can extends only one class at a time and can’t extends more than one class

simultaneously hence java won’t provide support for multiple inheritance with respect to classes.

We can achieve multiple inheritance in java by using interfaces.

In java hierarchy of classes Object is class is the super class of all other classes(user defined or
predefined classes)

If our class doesn’t extends any other class then only our class is the direct child class of

object.

HAS – A RelationShip
In Has-A relationship an object of one class is created as data member in another class the
relationship between these two classes is Has-A.

Ex:

class A

public void show()

===

}
}

class B

A ob=new A();//this statement establishes the has-A relation ship

ob.show();

Also known as Composition or Aggregation .

There is no specific keyword, but most of the cases we can implemented by using new
keyword.

Main advantage is reusability.

Drawback:
HAS – A relationship increases dependency b/w components and creates maintainability
problems.

Method Signature
In java method signature consists of method name and arguments list( including order also)

In java return type is not part of the method signature.

Compiler uses method signature to resolve method calls.

Two methods with the same signature are not allowed in any java class, violation leads to
compile time error.

Public int calculateSalary(int basic,float da)

Public void calculateSalary(int basic,float da)// compile time error because both methods
are having //same signature
{

‘this’ Key word:

It is called as reference variable because it refers an object . it always refers current object

public class Demo {

int x=5;

void display()

System.out.println(x);// implicitely System.out.println(this.x);

show();// implicitely this.show();

void show()

System.out.println("this is show method");

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

Demo o=new Demo();

o.display();

class Employee {

int empNo;//instance variable

String empName;//instance variable

Employee(int eno,String name)// local variables

empNo=eno;

empName=name;

Employee getDetails()//when ever method return type is class it indicated that method
will return an object of that class

return this;//"this" statement returns the current object

}
public static void main(String args[])

Employee e1=new Employee(101, "ramesh");

Employee e3=e1.getDetails();

System.out.println(e3.empName+" "+e3.empNo);

This is key word is explicitly required to access instance variables when ever both instance
variable and local variable names are same.

public class Employee {


int empId;
String empName;
Employee(int empId ,String empName)
{
this.empId=empId;
this.empName=empName;
}
public static void main(String[] args) {
Employee e1=new Employee(101, "raj");
System.out.println(e1.empId);
System.out.println(e1.empName);
}

By default this referece is prefixed when we access instance variables and methods.

We cannot use this keyword in a static context(static method,static block)

public class Demo {

Demo()

System.out.println("default constructor..") ;

Demo(String s)

this();

System.out.println("parameterised constructor..") ;
}

public static void main(String[] args)

Demo o=new Demo("hello");

Constructors:

Constructor is a special method which has the same name as the class name .

Constructor does not have any return type

Constructor is called automatically when ever an instance is created for a class .

Constructors are used to initialize the instance variables of a class.

Constructors are of two types

1.default constructors

2.parameterised constructors

public class Demo {


public Demo()

System.out.println("this is default constructor");

public Demo(String s)

System.out.println(s);

public static void main(String[] args) {

new Demo();

new Demo("hello");

this() : it is used to call default constructor of a current class

this(…):it is used to call parameterised constructor of a current class


note : this() and this(…) must be the first statements in a constructors

note: the java compiler provides one default constructor if the class does not contain any
other constructor

in the below example the instance variables are directly initialized.

Use constructors to assign different values to the instance variables.

class Emp

int empNo=101;

String empName="suresh";

public class Demo{

public static void main(String[] args) {

Emp e1=new Emp();

Emp e2=new Emp();

System.out.println(e1.empNo +" "+e1.empName+" ");

System.out.println(e2.empNo +" "+e2.empName+" ");


}

Super keyword

It is called as reference variable or object reference because it refers super class


members(data,methods)

It is explicitly required to access super class members when ever super class members and
sub class member names are same

class A

int x=5;

class B extends A

int x=10;

void print()

int x=15;

System.out.println(x);

System.out.println(this.x);
System.out.println(super.x);

public static void main(String args[])

B ob=new B();

ob.print();

Note: static method does not refer “this” and “super” key word in any way (explicitely or
implicitly)

super() : it is used to call default constructor of a super class. This statement is provided by
java compiler in every constructor

super(…):it is used to call parameterised constructor of a super class.This statement is used


by programmer to call parameterized constructor of a super class.

Note: super() and super(…) must be the first statements in a constructor

class A

A()
{

System.out.println("super class constructor");

class Demo extends A

Demo

()

Super();

System.out.println("this is sub class constructor");

public static void main(String args[])

Demo ob=new Demo();

Block:
The group of statements between open and close flower brackes{ } is called block

One class can have any number of blocks. All the blocks are executed from top to bottom
order before constructor , when ever an object is created.

public class Demo{

System.out.println("block1");

Demo()

System.out.println("this is a default constructor");

System.out.println("block2");

public static void main(String[] args)

{
new Demo();

A block is called as initialization block because it is used to initialize the instance variables
of the class

Static block:

A block with static keyword is called static block

One class can have any number of static blocks. All the blocks are executed from top to
bottom order before constructor , when ever a class is loaded

A static block is called as static initialization block because it is used to initialize the static
variables of the class Static blocks are used in real time to load the libraries

Polymorphism:
The ability to take more than one form is called polymorphism

Poly means many, morph means form

There are two types of polymorphism

1.compile time polymorphism(static binding)

2.run-time polymorphism(dynamic binding)


1.compile time polymorphism:

Binding of method call statement with method definition is done at compile time only is
known as compile time polymorphism

Ex: method overloading

OverLoading
Whenever same method name is exiting multiple times in the same class with different number
of parameter or different order of parameters or different types of parameters is known as
method overloading.

In method overloading the return type of methods can be same or different.

The overloading method resolution is the responsibility of compiler based on reference


type and method arguments. Hence overloading is considered as compile-time
polymorphism or EarlyBinding.

Note: The scope of overloading is within the class.

We can overload main() method

class Demo

void add (int a,int b)

System.out.println(a+b);

void add (int a,int b,int c)

System.out.println(a+b+c);
}

public static void main(String args[])

Demo ob=new Demo();

ob.add(14, 15, 16);

ob.add(10,20);

2.Runtime polymorphism:

Binding of method call statement with method definition is done at runtime is known as
runtime polymorphism

Ex: method overriding.

Overriding

If two or more methods with the same name and with the same parameters list then it is
said to be method overriding

What ever the parent has by default available to the child class through inheritance,

If the child class is not satisfied with the parent class implementation then the child is
allowed to overwrite that parent class method to provide it’s own specific
implementation, this concept is nothing but “overriding”.

Note: Without Inheritance method overriding is not possible.

Methods cannot be overridden in a same class.


class A

void show()

System.out.println("A class ");

void print()

System.out.println("print method");

class Demo extends A

void show()

System.out.println("B class ");

void display()

System.out.println("display method");

}
public static void main(String args[])

Demo ob=new Demo();

ob.show();

ob.print();

ob.display();

Overriding method resolution will take care by JVM based on runtime Object. Hence
overriding is

considered as runtime polymorphism or dynamic polymorphism or latebinding.

Difference between method overloading and method overriding

Method overloading Method overriding

1.if two or more methods with the same 1. if two or more methods with the same
name and different parameters lists name and with the same parameters
then it is said to be method lists then it is said to be method
overloading overriding

2. methods can be overloaded within the 2. methods cannot be overridden within


same class the same class because of ambiguity

3.methods can be overloaded in 3.method overriding always needs


inheritance also inheritance

4. in method overloading return type can 4. in method overriding return type must
be same be same

Or different Except co-variant return type


5. in method overloading access modifiers 5. in method overriding access modifiers
can be same or different can be same or less restrictive

6. final methods can be overloaded 6. final methods cannot be overridden.


Because final modifier is used to
prevent method overriding

7. static methods can be overloaded 7. static methods cannot be overridden


because static members are not a
part of an object

8. private methods can be overloaded 8.private methods cannot be overridden.


Because private members cannot be
inherited

Co-variant return type:

Java allows sub class type as a return type while overring a method this is known as co-
variant return type.

In overriding the return types must be same but this rule is appble only until 1.4 version but

from 1.5 version onwards co-variant return types also allowed. i.e the child class method
return type

need not to be same as parent class method return type it’s child class also allowed.

Ex:

Parent : Object(covariant returntype).

Child : String, StringBuffer, Object…..

Parent : String

Child : Object X

Because String to Object is not a covariant.

A static method can’t be overridden as non-static. Similarly a non-static method can’t be


overridden as static method.
Ifboth parent and child class methods are static then there is no compile time error or run
time error

it seems that overriding is happened but it is not overriding this concept is called “method
hiding”.

All the rules of method hiding are exactly similar to overriding, except both methods
declared as

static.

In the case of method hiding method resolution will take care by compiler based on
reference

class P

public static void m1()

System.out.println("parent method");

class C extends P

public static void m1()

System.out.println("child method");

class Test

public static void main(String arg[])


{

P p = new P();

Case1: p.m1(); //parent method

C c = new C();

Case2: c.m1(); //child method

P p1 = new P();

Case3: p1.m1(); //parent method

Execution priority:

1.static variables are initialized

2.static blocks are executed

3.main method is called

Without using a main method still we can execute a program

class StaticDemo

static

System.out.println("Hello....I can print ");

System.exit(0);

public static void main(String args[])


{

Typecasting

converting one data type to another either implicitly or


explicitly.
Java supports two types of castings – primitive data type
casting and reference type casting.
Reference type casting is nothing but assigning one Java
object to another object.

1. Implicit casting

A data type of lower size is assigned to a data type of higher size. This is done implicitly by the JVM.
The lower size is widened to higher size. This is also named as automatic type
conversion.

int x = 10; // occupies 4 bytes

double y = x; // occupies 8 bytes

System.out.println(y); // prints 10.0

2. Explicit casting

A data type of higher size cannot be assigned to a data type of lower size. This is not done
implicitly by the JVM and requires explicit casting; a casting operation to be performed
by the programmer. The higher size is narrowed to lower size.

double x = 10.5;
int y = (int) x;

General syntax of typecasting

A b=(c) d;

Upcasting and Downcasting:

Assigning an object or reference variable of subclass type( child class obeject) to super class
type is known as upcasting

Upcasting done by system implicitely

Ex: 1)A ob=new B();

2)B ob1= new B();

A ob2=ob1;

Downcasting
Assigning an object or reference variable of superclass type to subclass type is known as
downcasting

Downcasting must be done by programmer explicitely

Downcasting always need upcasting

A ob1=new B();

B ob2=(B) ob1;

String handling:
There are four string handling classes are available in java to handle strings

1.java.lang.String

2.java.lang.StringBuffer

3.java.lang.StringBuilder

4.java.util.StringTokenizer

Note:java.lang is a default package which is imported automatically in every java program

String:-

String is a final class it is present in java.lang package.

String is nothing but a group of characters or character array.

Once we are creating String object it is not possible to do the


modifications on existing object called immutability nature.

In String class .equals() is used for content comparision.

Every string literal itself is an object of String class


Once we created String objects we are not allowed to perform any changes in the existing
object. If u r

trying to perform any changes with those changes a new String object will be created this
behavior is

nothing but ‘immutability’ Of the String Objects.

There are two ways to create the strings in java

1.String s1=”hello”;

2.String s2=new String(“welcome”);

First statement creates one String object in string constant pool. Where as second statement
creates two objects , one in string constant pool and the another one out side the
pool.(on heap)

When ever an object or object reference is passed in system.out.println()then implicitely


toString() is called

toString() is present in Object class and it is overridden in String class

An Object class toString() method always returns ClassName@Hashcode in hexa decimal


format.

Where as the String class toString() method always returns the contents of the string object

public class Demo{

public static void main(String[] args) {

String s=new String("hello");


System.out.println(s);

Demo ob=new Demo();

System.out.println(ob);

The object class toString method can be overridden by the programmer to change the
definition

Note: java.lang.String is a final class and it cannot be inherited

public class Demo{

public String toString()

return "welcome";

public static void main(String[] args) {

Demo ob=new Demo();

System.out.println(ob);
}

Java.lang.String

Constructors:

1.String ();

2.String (String);

Constructor-1 is used for creating empty string object.

Constructor-2 is used for creating a String object by taking another string as a parameter.

3.public String(char[]);

4.public String(char[], int, int);//first int indicates the starting index and second int
represent no of characters from the starting index

The above two constructors are used to convert the character array into a String

5.public String(byte[]);

6. public String(byte[], int, int);

The above two constructors are used to convert the byte array into a String
public class Demo{

public static void main(String[] args)

String s1=new String();

String s2=new String("hello");

char ch[]={'w','e','l','c','o','m','e'};

String s3=new String(ch);

String s5=new String(ch,3,4);

byte b[]={65,66,67,68};

String s4=new String(b);

System.out.println(s1);//prints nothing(empty string object)

System.out.println(s2);

System.out.println(s3);

System.out.println(s4);

System.out.println(s5);

}
Methods:

1.public int length();

Returns the length of this string.(no of characters present in the


given string)

2.public char charAt(int);

Returns the char value at the specified index.

3. public byte[] getBytes();

it is used to convert the given String into bytes array

4.public boolean equals(Object);

Compares this string to the specified object(string)

5.public boolean equalsIgnoreCase(String);

Compares this String to another String, ignoring case considerations.

6.public String concat(String);


Concatenates (adds) the specified string to the end of this string.

7.public String toLowerCase();

converts the given string to the lower case

8. public String toUpperCase();

converts the given string to the upper case

9. public String trim();

it is used to remove the extra spaces at the beginning of the string and at the end of the
string

10. public char[] toCharArray();

it is used to convert the given string into the character array

11. public String subString (int start);

is used for obtaining the characters from specified position to end character

position.
12. public String subString (int start, int end);

is used for obtaining those characters by specifying starting position to ending

position.

class Demo

public static void main(String[] args)

String s1=new String("welcome");

int n= s1.length();

System.out.println("the length of the string is: "+n);

char ch=s1.charAt(3);

System.out.println("the character at 3rd location: "+ch);

byte b[]=s1.getBytes();

for(byte c:b)

System.out.println(c);

String s2=new String("welcome");

boolean comp=s1.equals(s2);

if(comp)

System.out.println("both the strings are same:");

else

System.out.println("both the strings are not same:");

String s3=new String("WELCOME");

boolean comp2=s1.equalsIgnoreCase(s3);

if(comp2)

System.out.println("both the strings are same:");


else

System.out.println("both the strings are not same:");

String s4=new String("to java");

String s5=s1.concat(s4);

System.out.println(s5);

String s6=new String (" hello to all ");

System.out.println(s6);

System.out.println(s6.trim());

char ch1[]=s2.toCharArray();

for(char temp:ch1)

System.out.println(temp);

System.out.println(s6.substring(8));

equals() method of java.lang.String compares the contents of the String object

equals() method of java.lang.Object class compares the hascode of the reference variable

“ == ” operator compares the hashcode

class Demo

public static void main(String args[])

String s1=new String("Hello");


String s2=new String("Hello");

System.out.println(s1.equals(s2));

System.out.println(s1==s2);

StringBuffer class:

Whenever we create an object of StringBuffer we get 16 additional characters memory

space. Hence an object of StringBuffer is mutable object.

StringBuffer API:

1. StringBuffer ()

2. StringBuffer (String)

Constructor-1 is used for creating an object of StringBuffer whose default capacity is 16


additional characters memory space.

For example:

StringBuffer sb=new StringBuffer ();

System.out.println (sb.capacity ());

Constructor-2 is used for converting String object into StringBuffer object.

For example:

String s=”HELLO”;
StringBuffer sb=new StringBuffer (s);

System.out.println (sb.capacity ());

System.out.println (sb.length ());

Instance methods:

1. public int length ();

This method is used for determining the length of the string.

2. public int capacity ();

This method is used for determining the capacity of StringBuffer object. Capacity of

StringBuffer object is equal to the number of characters in the StringBuffer plus 16

additional characters memory space.

3. public StringBuffer reverse ();

This method is used for obtaining reverse of source StringBuffer object.

4. public void append (String);

This method is used to append string data at the end of source StringBuffer object.
5. public StringBuffer delete (int start, int end);

This method is used for removing the specified number of characters from one position to

another position.(in between characters will be deleted from starting index to the ending
index)

note : ending index is not included

ex:

StringBuffer sb=new StringBuffer("welcome");

System.out.println (sb.delete(2, 5));// weme

public StringBuffer replace (String, int, int);

ex:

StringBuffer sb=new StringBuffer("welcome");

System.out.println (sb.replace(1, 6, "he"));//whee

This method is used for replacing the string into StringBuffer object form one specified

position to another specified position.

7. public StringBuffer insert (String, int,);

This method is used for inserting the string data from one specified position to another

specified position.

Ex:

StringBuffer sb=new StringBuffer("welcome");


System.out.println (sb.insert(2, "hello"));

Difference between String and StringBuffer class:

String StringBuffer

An Object of String class is immutable An Object of StringBuffer class is mutable

Methods of String class are not Methods of StringBuffer class are


synchronized synchronized

String class overrides the equals() method StringBuffer class does not overrides the
of Object class. equals() method of Object class.

public class Demo{

public static void main(String args[]){

String s1=new String("Taj");

String s2=new String("Mahal");

s1.concat(s2);

System.out.println(s1);
StringBuffer sb1=new StringBuffer("Taj");

StringBuffer sb2=new StringBuffer("Mahal");

sb1.append(sb2);

System.out.println(sb1);

}}

StringBuilder

Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-
synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class

StringBuilder(): creates an empty string Builder with the initial capacity of 16.

StringBuilder(String str): creates a string Builder with the specified string.

StringBuilder(int length): creates an empty string Builder with the specified capacity
as length.

Difference between String, StringBuffer,StringBuilder:

String StringBuffer StringBuilder

Immutable Mutable mutable

Not synchronized synchronized Not synchronized

String tokenizer:
It allows an apption to break a string into tokens(words)

Constructor:

Public StringTokenizer(String);

Methods:

public boolean hasMoreTokens();

this method returns true if the next token is present other wise it returns false

public String nextToken();

it returns current token and moves the cursor to the next token

public int countTokens();

it returns number of tokens

import java.util.StringTokenizer;

public class Demo{

public static void main(String[] args) {

String s1=new String("welcome to java programming");


StringTokenizer st=new StringTokenizer(s1);

System.out.println("the string has :"+st.countTokens()+" tokens");

while (st.hasMoreTokens())

System.out.println(st.nextToken());

Wrapper classes:

The main objectives of wrapper classes are:

To Wrap primitives into object form. So that we can handle primitives also just like
objects.

To Define several utility functions for the primitives(like converting primitive to the
string form etc.

Each of java’s 8 primitive data types has classes. And those classes are called as
Wrapper classes because they wrap the data into an object.

Primitive data types Wrapper class

byte Byte

short Short

int Integer

long Long
float Float

double Double

boolean Boolean

char Character

All wrapper classes belongs to java.lang package

Constructing Wrapper objects by using constructors


Every Wrapper class contains 2 constructors one can take the corresponding
primitive as the argument and the other can take the corresponding string as the
argument.

Integer class
public class Demo {

public static void main(String args[]) {

Integer I = new Integer(10);

Integer I1 = new Integer("10");

System.out.println(I);

System.out.println(I1);

Note:If the String is unable to convert into the number form then we will get run time
exception saying “NumberFormatException“.
Float class
This class contains 2 constructors which can take double, String as argument.

Character class
This class contain only one constructor which can take char as the argument i.e
character class doesn’t contain a constructor which can take string as the
argument.

Boolean class

This class contains 2 constructors one can take boolean primitive. Other can take string argument. If you
are providing boolean primitive as the argument then. The allowed values are true or false.

Case is not important if the content contains ‘TRUE’ then it is considered as true other wise it considered as
false.

public class Demo {

public static void main(String args[]) {

Boolean b = new Boolean(true); //true

Boolean b1 = new Boolean(false);//not valid

Boolean b2 = new Boolean("false");//false

Boolean b3 = new Boolean("TrUE"); //true

Boolean b4 = new Boolean("raju"); //false

Boolean b5 = new Boolean("yes");//false

}
valueOf method:

All the wrapper classes except Character class contains the valueOf() method for
converting string to corresponding Wrapper Object.

public static wrapper valueOf(String s);

public class Demo {

public static void main(String args[])

Integer I = Integer.valueOf("10");//10

Float F = Float.valueOf("10.5");//10.5

Boolean B = Boolean.valueOf("java");//false

//Character ch = Character.valueOf("10");//invalid

All Integral wrapper classes “Byte, Short, Long, Integer” Contains the following
valueOf() method.
public static wrapper valueOf(String s, int radix);
The allowed base of radix is 1 to 36.Because Numerics(10) ,Alphabets(26) finally
10+26 =36

public class Demo {

public static void main(String args[]) {

Integer I = Integer.valueOf("101011", 2);


System.out.println(I);

Every Wrapper class including character class contains the following valueOf() method
to convert primitive to wrapper object form.

public static wrapper valueOf(primitive p);

public class Demo {

public static void main(String args[]) {

Integer I = Integer.valueOf(10);

Character ch = Character.valueOf('a');

Boolean B = Boolean.valueOf(true);

xxxValue() method

Every wrapper class Except character and Boolean classes contains the following
xxxValue() methods for converting wrapperObject to primitive.

public int intValue();


public byte byteValue();
public short shortValue();
public long longValue();
public float floatValue();
public int doubleValue();
public class Demo {

public static void main(String args[]) {

Integer I = Integer.valueOf(130);

System.out.println(I.byteValue());

System.out.println(I.shortValue());

System.out.println(I.intValue());

System.out.println(I.longValue());

System.out.println(I.floatValue());

System.out.println(I.doubleValue());

Character class contain charValue() method to return char primitive for the given
character wrapper object.

public char charValue();

public class Demo {

public static void main(String args[]) {

Character ch = new Character('a');

char ch1 = ch.charValue();

System.out.println(ch1);

}
Boolean class contains booleanValue() method to return boolean primitive for the given
boolean object.

public class Demo {

public static void main(String args[]) {

Boolean B = Boolean.valueOf("MNC");

boolean b1 = B.booleanValue();

System.out.println(b1);

Java.lang.Integer:

Constructor:

public Integer(int)

it is used to convert from primitive type to reference type

method:

public int intValue()

it is used to convert reference type to primitive type


ex: primitive to reference type:

int x=5;

Integer ob=new Integer(x);

Ex: reference type to primitive type:

Integer ob=new Integer(5);

int x=ob.intValue();

Autoboxing:

The process of converting primitive type variable to the corresponding reference type
variable is called autoboxing

int x=5;

Integer ob=x; // autoboxing

Auto Unboxing:

The process of converting reference type variable to the corresponding primitive type
variable is called autounboxing

Integer ob=new Integer(5);

int x=ob;

class Demo
{

public static void main(String arg[])

int x=10;

Integer ob=new Integer(x);

System.out.println(ob);

Integer ob2=new Integer(7);

int y=ob2.intValue();

System.out.println(y);

Integer ob3=87;// autoboxing

System.out.println(ob3);

Integer ob4=new Integer(100);

int z=ob;//autounboxing

System.out.println(z);

Exception Handling
Error:

A programming mistake is said to be an error

Types of errors:

1.compile time errors(syntax errors)

2.run time erros(exceptions)

3.Logical errors

Exception means runtime error

Exception is an unwanted and unexpected event that disturbs normal flow of the program is
called exception.

If we are not handling exception,the program may terminate abnormally without releasing
allocated resources.This is not a graceful termination.Being a good programming
practice compulsory we should handle exceptions for graceful termination of the
program.

Exception handling doesn’t mean repairing an exception just we have to provide alternative
path to continue the program normally.

Run time Stack Mechanism

For every thread in java JVM provides a run time stack.

All the method calls performed by that thread will be sorted in the corresponding run time
stack.

Once the method terminates normally, the corresponding entry from the stack will be
removed.

After completing all method calls the stack will become empty and JVM destroys that stack
before terminating the thread.
Ex:

public class ExcpetionHandDemo {

public static void main(String[] args) {

doStuff();

public static void doStuff() {

doMoreStuff();

public static void doMoreStuff() {

System.out.println("Exception thread..");

Default Exception Handling

When ever an exception raised by the method ,then that method is responsible for the
preparation of exception object by including the following information.

Name of Exception.

Description.

Location of Exception.

After preparation of Exception Object, The method handovers that object to the JVM.
JVM will check for Exception handling code in that method, if the method doesn’t contain
any exception handling code then JVM terminates that method abnormally and
removes corresponding entry from the stack.

JVM will check for exception handling code in the caller,and if the caller method also doesn’t
contain exception handling code then JVM terminates that caller method abnormally
and removes corresponding entry from the stack.

This process will be continued until main method and if the main method also doesn’t
contain any exception handling code then JVM terminates main method abnormally.

Just before terminating the program,JVM handovers the responsibilities of exception


handling to the default exception handler.

Default exception handler prints the exception information to the console and terminates
the program abnormally.

public class ExcpetionDemo {

public static void main(String[] args) {

doStuff();

public static void doStuff() {

doMoreStuff();

public static void doMoreStuff() {

System.out.println(10/0);

/*

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero

at ExceptionDemo.doMoreStuff(ExceptionDemo.java:12)

at ExceptionDemo.doStuff(ExceptionDemo.java:8)

at ExceptionDemo.main(ExceptionDemo.java:5)

*/

Exception Hierarchy
The Java exception hierarchy starts from Throwable class i.e for all java Exceptions and
Errors Throwable is parent class

Throwable has 2 child classes

Exception:Most of the times, Exceptions are caused by due to our program code only and
these are recoverable

Error:Most of the times errors are raised due to lack of system resources and Errors are
non-recoverable.

Checked Exceptions Vs UnChecked Exceptions


checked exceptions.
The Exceptions which are checked by the compiler for smooth execution of the program at run
time are called checked exceptions.

Example: FileNotFoundException, InterruptedException.

The exception classes which are derived from java.lang.Exception class are called
checked exceptions

They do not include java.lang.RuntimeException class and all its subclasses

All checked exceptions must be handled by the programmer explicitely by using try catch
block or throws key word other wise compile time error will occurs

The compiler checks for try and catch block or throws keyword for this kind of
exceptions.

All apption specific exceptions are comes under this category

java.io.FileInputStream:

constructor:

public FileInputStream(String) throws FileNotFoundException;

it opens a file for reading if the file is exist , otherwise FileNotFoundException is thrown.

FileNotFoundException is a checked exception and it must be handled by programmer


explicitely by using try catch block.

import java.io.FileInputStream;

public class Demo

public static void main(String[] args)

FileInputStream fis=new FileInputStream(args[0]);

2.Unchecked exceptions:
The Exceptions which are unable to checked by the compiler are called ‘unchecked
exceptions’

Runtimeexception and it’s child classes, Error and it’s child classes are considered as
unchecked

exceptions and all the remaining considered as checked.

The exception classes which are derived from java.lang.RuntimeException class are called
Unchecked exceptions

All unchecked exceptions are handled by JVM implicitely

Handling unchecked exceptions by a programmer is optional

The java compiler does not check for try catch or thorows keyword for this kind of
exceptions.

All general exceptions are comes under this category

java.lang.Integer:

Method()

public static int parseInt(String) throws NumberFormatException

Number format exception is a unchecked exception and it is handled by system implicitely

Ex: public class Demo

public static void main(String[] args)

int x=Integer.parseInt(args[0]);

}
}

The above program successfully compiles

Partially checked Vs fully checked


A checked exception is said to be fully checked iff all it’s child classes also checked.
Example: IOException.

A checked exception is said to be partially checked if some of it’s child classes are not checked.
Example:Exception.

Exception Handling By Using try ,catch


We can handle the exceptions by using try catch.
We have to place the risky code inside the try block and the corresponding
exception handling code inside catch block.
try{

//Risky code

}catch (X e){

//handling code

Without Exception handling code


public class ExceptionDemo {

public static void main(String[] args) {

System.out.println("Statement1");

System.out.println(10 / 0);

System.out.println("Statement2");

}
/*

Output:

Statement1

Exception in thread "main" java.lang.ArithmeticException: / by zero

at ExceptionDemo.main(ExceptionDemo.java:6)

*/

Note:The above program terminates abnormally.

With Exception handling code


public class ExceptionDemo {

public static void main(String[] args) {

System.out.println("Statement1");

try {

System.out.println(10 / 0);

} catch (ArithmeticException exception) {

System.out.println("Exception block:" + (10 / 2));

System.out.println("Statement2");

/*

Statement1

Exception block:5
Statement2

*/

Note:The above program terminates normally.

All exceptions are classes in java

In exception handling we use following keywords

try, catch, throw ,throws and finally

When ever exception occurs in java a related exception class object is created by jvm and it
will be thrown to a catch block

The catch block is called as an exception handler and it handles the exception object.

public class Test

{
public static void main(String[] args)

int x=Integer.parseInt(args[0]);

int y=Integer.parseInt(args[1]);

int z=x/y;

System.out.println(z);

In the above example all the exceptions are handled implicitely

In the above example throwable class toString() is called

The above example a programmer can also handle the exceptions explicitely to change the
default messages of the exceptions

Syntax of try catch block:

Try

----

Catch(Exceptionclassname objectreference)

--

-- user friendly messages/error messages

Try block must be associated with atleast one catch block or finally block

public class Test

{
public static void main(String[] args)

try

int x=Integer.parseInt(args[0]);

int y=Integer.parseInt(args[1]);

int z=x/y;

System.out.println(z);

catch(ArrayIndexOutOfBoundsException ae)

System.out.println("please pass two arguments:");

catch(NumberFormatException nfe)

System.out.println("please pass integers only:");

catch(ArithmeticException ae)

System.out.println("second argument is a non zero element");

}
}

public class Test

public static void main(String[] args)

try

int x=Integer.parseInt(args[0]);

int y=Integer.parseInt(args[1]);

int z=x/y;

System.out.println(z);

catch(RuntimeException ae)

System.out.println("please pass two integers and second argument


except zero:");

}
Note: in the above example catch block handles RuntimeException class object and all its
sub classes

Control Flow in try, catch


try

statement 1;

statement 2;

statement 3;

catch (X e)

statement 4;

statement 5;

Case1: if there is no exception

1,2,3,5 normal termination.

Case2: if there is an exception raised at statement 2 and the corresponding catch block
matched.

1,4,5 normal termination.

Case3: if an exception raised at statement 2 but the corresponding catch block is not
matched
1 Abnormal termination.

Case4: if an exception raised at statement 4 or statement 5 it is always abnormal


termination.

try with multiple catch blocks


The way of handling exception is varies from exception to exception. Hence for every
exception we should define corresponding catch blocks hence try with multiple catch
blocks is possible.

try

risky code

catch (ArithmeticException e )

//handler to A.E

catch (NullPointerException e)

//handler for N.P.E

catch(IOException e)

//handler for IOException

catch(Exception e)

//handler for Exception


}

In the case of try with multiple catch blocks the order of catch blocks is important. And it
should be from

child to parent other wise Compiler Error. Saying Exception xxx has already been caught

Example:Parent to Child
public class ExceptionDemo {

public static void main(String[] args) {

try{

System.out.println(10 / 0);

}catch (Exception ex) {

ex.printStackTrace();

}catch (ArithmeticException e){

e.printStackTrace();

Example:Child to Parent
public class ExceptionDemo {

public static void main(String[] args) {


try {

System.out.println(10 / 0);

} catch(ArithmeticException e) {

System.out.println("ArithmeticException block");

} catch(Exception ex) {

System.out.println("Exception block");

If there is no chance of raising an exception in try block then we can’t keep


corresponding catch block otherwise we will get compile time error saying
“exception is never thrown in the body of corresponding try statement“.But this rule is
appble only for fully checked exceptions.

import java.io.IOException;

public class ExceptionDemo {

public static void main(String[] args) {

try{

System.out.println("Hello");

}catch (IOException ex) {

ex.printStackTrace();

}
Note:IOException is fully checked exception.

public class ExceptionDemo {

public static void main(String[] args) {

try {

System.out.println("hello");

} catch(Exception e) {

System.out.println("Exception block");

Finally

It is not recommended to place cleanup code inside try statement because there is no
guarantee for

execution of all statements inside try block.

It is not recommended to maintain cleanup code with in the catch block because if there is
no exception the catch blocks won’t be executed.

We required a block to maintain cleanup code which should execute always irrespective of
whether the

exception is raised or not whether it is handled or not , such block is nothing but “finally
block”

Hence the main objective of finally block is to maintain cleanup code.


try

//open the database connection

//read the data

catch (X e)

finally

close the Connection

Ex:

try

System.out.println("try");

catch (ArithmeticException e)

System.out.println("catch");

finally

{
System.out.println("finally");

O/P: try

finally

Normal Termination

Ex:

try

System.out.println(10/0);

catch (ArithmeticException e)

System.out.println("catch");

finally

System.out.println("finally");

O/P: catch
Finally

Normal Termination

Ex:

try

System.out.println(10/0);

catch (NullPointerException e)

System.out.println("catch");

finally

System.out.println("finally");

O/P: finally

Abnormal termination

Hence finally block should always execute irrespective of whether the exception is raised or
not raised or

handled or not handled


Difference Between final, finally, finalize

final: It is the modifier appble for classes methods and variables. For final classes we can’t
create

child classes i.e inheritance is not possible.

final methods can’t be override in child classes for final variables reassignments is not
possible

because they are constants.

finally: It is a block associated with try catch the main objective of finally block is to
maintain

cleanup code which should execute always.

finalize: It is a method should be executed by the “Garbage Collector” just before destroying
an

object. The main objective of finalize method is to maintain cleanup code.

Possible combinations of try, catch, finally


Customized Exception
Based on our programming requirement some times we have to create our own exception,
which are nothing but “Customized Exception”.

program to create and handle checked exception


class NegetiveNumberException extends Exception

public class Demo

void cube(int a)throws NegetiveNumberException

if(a>0)

System.out.println(a*a*a);

else

throw new NegetiveNumberException();

public static void main(String[] args) throws Exception

try

int x=Integer.parseInt(args[0]);

Demo ob=new Demo();

ob.cube(x);

}
catch(NegetiveNumberException e)

System.out.println(e);

program to create and handle unchecked exception

class NegetiveNumberException extends RuntimeException

public class Demo

void cube(int a)throws NegetiveNumberException

if(a>0)

System.out.println(a*a*a);

else
throw new NegetiveNumberException();

public static void main(String[] args) throws Exception

int x=Integer.parseInt(args[0]);

Demo ob=new Demo();

ob.cube(x);

throw keyword
By using throw we can hand – over exception object to the JVM.

The output of the following two programs is same.

case:1

public class ExceptionDemo {

public static void main(String[] args) {


throw new Test();

class Test{

Compiletime Error:No exception of type Test can be thrown; an exception type must be a
subclass of Throwable

case:2

public class ExceptionDemo {

public static void main(String[] args) {

throw new Test();

class Test extends RuntimeException{

Case:3
public class ExceptionDemo {

static ArithmeticException e = new ArithmeticException("/by zero");

public static void main(String[] args) {

throw e;

Here Explicitly we created a object to the ArithmeticException class and that object was
thrown by thow to the JVM.

Case 4:
public class ExceptionDemo {

static ArithmeticException e ;

public static void main(String[] args) {

throw e;

Output:
Exception in thread “main” java.lang.NullPointerException
Here we didn’t create Object to the AritmeticException class just we created a reference,
so reference variable is not pointing to any object and we thrown only reference
variable that’s why only it shows NullPointerException.

After throw statement we are not allowed to write any statement directly other wise we will
get compile time error saying that un-reachable statement

Throws keyword:

In our program,If there is any chance of raising checked exception then compulsory we
should handle that checked exception either by using try, catch or we have to
delegate that responsibility to the caller using throws keyword other wise C.E

ex:

class Demo

public static void main(String arg[])

Thread.sleep(1000);

We can resolve this problem either by using try catch or by using throws keyword as follows
class Demo

public static void main(String arg[])

try

Thread.sleep(1000);

catch (InterruptedException e)

System.out.println(e);

}
class Demo

public static void main(String arg[])throws InterruptedException

Thread.sleep(1000);

Hence the main objective of throws keyword is to delegate the responsibilities of exception
handling to the

Caller method incase of checked exceptions

In the case of unchecked exceptions it is not required to use the throws keyword

The Methods to display Exception Information


Throwable class contains the following methods to display error information.

printStackTrace: It displays error information in the following format.


Name of Exception : Description

StackTace.

toString: it displays error in the following format.


Name of Exception : Description

getMessage: it displays error information in the following format.


Description

Ex:-

Note: by default printStackTrace method is used by default exception handler


Note: Default Exception handler always uses printStackTrace method only.

Multithreading
Multitasking Executing several tasks simultaneously is called ‘Multitasking’,
There are 2

types of multitasking.

1) Process based Multitasking.

2) Thread based Multitasking.

Process based Multi Tasking

Executing several tasks simultaneously where each task is a separate independent


process is

called ‘Process based Multitasking’.

Ex:
While writing java program in the editor we can run MP3 player. At the same time
we

can download a file from the net. All these tasks are executing simultaneously and

independent of each other. Hence it is process based Multitasking. Process based

Multitasking is best suitable at O.S level.

Thread based Multitasking.

Executing several tasks simultaneously where each task is a separate independent


part of the

same program is called Thread based Multitasking. This type of multitasking is best
suitable

at programmatic level.

Java provides in built support for thread based multitasking by providing rich
library (Thread,

ThreadGroup, Runnable ..etc)

Whether it is Processbased or Threadbased the main objective of multitasking is to


reduce

response time and improve performance of the system.

The main apption area of multithreading is videogames implementation,


,Multimedia graphics

…etc.

Defining ,Instantiating, Starting the Thread


We can define instantiate and starting a thread by using the following 2- ways.

1) By extending Thread Class.

2) By implementing Runnable interface.

By extending Thread Class


Ex:

class MyThread extends Thread

{
public void run()

for (int i=0; i<10; i++ )

System.out.println("Child Thread");

class MultiThreadDemo

public static void main(String[] args)

MyThread t = new MyThread();

t.start();

for(int i = 0; i<10; i++)

System.out.println("Main Thread");

Case1 :

Thread Shedular:

If multiple threads are there then which thread will get chance first for execution
will be

decided by “Thread Scheduler”. Thread Scheduler is the part of JVM. The behavior
of thread

scheduler is vendor dependent and hence we can’t expect exact O/P for the above
program.

The possible Outputs are:

Note: when ever the situation comes to multithreading the guarantee in behavior is
very less we can tell possible output but not exact output
Case2:

The difference between t.start() & t.run():

In the case of t.start() a new thread will be created and which is responsible for the
execution

of run( ) method. But in the case of t.run() no new thread will be created and run()
method will be executed just like a normal method by the main thread.

Hence in the above program if we are replacing t.start() with t.run() then the O/P is

Case3:

Importance of Thread Class start() method:

After Creating thread object compulsory we should perform registration with the
thread

scheduler. This will take care by start( ) of Thread class, So that the programmers
has to

concentrate on only job. With out executing Thread class start() method there is no
chance of

start a new Thread in java.

start()

Register our thread with the thread scheduler.

Invoke run method.

Case4:

If we are not overriding run() method:

Then the thread class run method will be executed which has empty
implementation.

Ex:

class MyThread extends Thread

class ThreadDemo
{

public static void main(String arg[])

MyThread t = new MyThread();

t.start();

O/P:- no output

Note: it is highly recommended to override run method to define the job of a thread

Note:overloading of run( ) method is possible but thread class start( ) method


always call no argument run only. But the other run methods has to call just
like normal method call.

Case5:

If we are overriding start() method:

Ex:

class MyThread extends Thread

public void start()

System.out.println("start() method");

public void run()

System.out.println("run method");

class ThreadDemo

{
public static void main(String arg[])

MyThread t = new MyThread();

t.start();

O/P:- start() method

In this case start() method will be executed just like a normal method.

Life cycle of Thread


When u write new MyThread()

Once we crated a thread object then it is said to be in new state or born state

If we call start( ) method then the thread will be entered into ready or runnable
state

If threadshedular allocates cpu then the thread will entered into running state

If run( ) method completes its execution then the thread will entered into deadstate

Note:- we can’t stop a running Thread explicitly. But until 1.2 version we can
achieve this by using

stop() method but it is deprecated method. Similarly suspend() and resume()


methods also

deprecated.

After starting a thread we are not allowed to restart the same thread once again,
violation leads to Runtime Error saying “IllegalThreadStateException”.
MyThread t = new MyThread();

t.start();

-----

-----

t.start(); // Illegal Thread state Exception.

Within the run method if we call super.start( ) method we get the same runtime
error “IllegalThreadStateException”.

It is never recommended to override start( ) method. But it is recommended to


override run( ) method

Defining a thread By Implementing Runnable Interface


We can define a Thread by implementing runnable interface also. Runnable
interface available in java.lang package and contains only one method

public void run();


Ex:

class MyRunnable implements Runnable

public void run()

for(int i = 0;i<=10;i++)

System.out.println("Child Thread");

class ThreadDemo

public static void main(String arg[])

MyRunnable r = new MyRunnable();

Thread t = new Thread(r);

t.start();

for(int i = 0;i<=10;i++)

System.out.println("Main Thread");

Ex:

MyRunnable r = new MyRunnable();


Thread t1 = new Thread();

Thread t2 = new Thread(r);

Case1:

t1.start();

A new thread will be started and executes Thread class run( ) method(Which is
having empty

implementation).

Case2:

t1.run();

No new thread will be created and Thread class run() method will be executed just
like a

normal method call.

Case3:

t2.start();

A new thread will be created and responsible for execution of MyRunnable run( )
method.

Case4:

t2.run();

No new thread will be created and MyRunnable run( ) method will be executed just
like a

normal method call.

Case5:

r.run();

No new thread will be created and MyRunnable run( ) method will be executed just
like a

normal method call.

Case6:

r.start();

Compiler Error: MyRunnable doesn’t contain start method.

Note:- Among 2- approaches of defining a thread – implements Runnable is always


recommended to
use in the 1st approach as we are already extending thread class. There is no chance
of extending any other class. Hence we are missing the key benefits of oops
inheritance(reusability) . hence this approach is not recommended to use.

setting and getting the name of a Thread

every thread in java has some name it may be provided by programmer or a default
name generated by jvm

Thread class defines the following methods to set and get the name of a Thread.

1) public final void setName(String name);

2) public final String getName();

Ex:

class Test

public static void main(String arg[])

System.out.println(Thread.currentThread().getName());

Thread.currentThread().setName("New Thread");

System.out.println(Thread.currentThread().getName());

Note: we can get current executing thread reference by using the following method
of thread class

public static Thread currentThread( );

Thread Priorities:

Every Thread in java having some priority. The range of valid thread priorities is
(1-10) (1 is least & 10 is Highest). Thread class defines the following
constant for representing some standard priorities.
Thread.MIN_PRIORITY 1

Thread.NORM_PRIORITY 5

Thread.MAX_PRIORITY 10

Thread scheduler use these priorities while allocating C.P.U. The Thread which is
having highest priority

will get chance first for execution. If two threads having the same priority then
which thread will get chance first for execution is decided by Thread
Scheduler, which is vendor dependent i.e we can’t expect exactly.

The default priority for the main thread only the 5, but for all the remaining threads
the priority will be inherit from parent i.e what ever the parent has the same
priority the child thread also will get.

Thread class contains the following methods to set and get priorities of thread.

public final void setPriority(int priority)

public final int getPriority();

where priority should be from 1-10 other wise R.E: IllegalArgumentException.

Ex:

class MyThread extends Thread

public void run()

for (int i=0; i< 10 ; i++ )

System.out.println("Child Thread");

class ThreadPriorityDemo

{
public static void main(String arg[])

MyThread t = new MyThread();

System.out.println(t.getPriority());

t.setPriority(10);//------------'(1)

t.start();

System.out.println("thread name is:"+Thread.currentThread().getName()+ "


priority is: "+t.getPriority());

for(int i =0;i<10;i++)

System.out.println("Main Thread");

If we are commenting line 1 then both main and child threads having the same
priority(5) and hence we cant expect exact execution order and exact output

If we are not commenting line 1 then main has the priority 5 and child thread have
the priority(10) and hence child thread will be executed first and then main
thread. In this case the output is child thread 10 times and mainthread 10
times will be executed

Note: Some Operating Systems may not provide support for thread priorities.

The methods to prevent thread execution

We can prevent a thread from execution by using the following methods.

1) yield()

2) join()

3) sleep()
yield()
The thread which is called yield() method temporarily pause the execution to give
the chance for remaining threads of same priority.

If there is no waiting thread or all waiting threads having low priority.

Then the same thread will get the chance immediately for the execution.

public static native void yield();

the thread which is yielded, when it will get chance once again for execution is
decided by ThreadSchedular and we can’t expect exactly.

Ex:

class MyThread extends Thread

public void run()

for (int i=0; i< 10 ; i++ )

Thread.yield();//-----------------------(1)

System.out.println("Child Thread");

}
}

class YieldDemo

public static void main(String arg[])

MyThread t = new MyThread();

t.start();

for(int i =0;i<10;i++)

System.out.println("Main Thread");

If we are commenting line 1 then both threads will be executed simultaneously and
we cant expect exact execution order

If we are not commenting line 1 then the chance of completing main thread first is
high because child thread always calls yield() method.

. As the yield method is native method some Operating system may not provide the
support for this.

join()
If a thread wants to wait until some other thread completion then we should go for
join method.

Ex:

If a thread t1 executes t2.join(), then t1 will be entered into waiting state until t2

completion.

public final void join() throws InterruptedException

public final void join(long ms) throws InterruptedException

public final void join(long ms, int ns) throws InterruptedException


Join() method is overloaded and every join() throws InterruptedException hence
when ever we are using join() compulsory we should handle
InterruptedException either by using try-catch block or by throws key word
otherwise we will get compile time error.

Ex:

class MyThread extends Thread

public void run()

for (int i=0; i< 10 ; i++ )

System.out.println("Child Thread");

try

Thread.sleep(2000);

catch(InterruptedException e)

e.printStackTrace();

class ThreadJoinDemo

{
public static void main(String arg[])throws InterruptedException

MyThread t = new MyThread();

t.start();

t.join();//--------------------(1)

for(int i =0;i<10;i++)

System.out.println("Main Thread");

If we are commenting line 1 then both threads will be executed simultaneously and
we cant expect exact execution order and hence we cant expect exact o/p.

If we are not commenting line 1 then main thread will wait until completing child
thread hence in this case the o/p is expected.

Sleep ( ):

If a thread has to wait some predefined amount of time with out execution then we
should go for sleep() method.

If a thread don’t want to perform any operation for a particular amount of time
(just pausing) then we should go for sleep()

public static void sleep(long ms)throws InterruptedException

public static void sleep(long ms, int ns)throws InterruptedException


When ever we are using sleep() compulsory we should handle interrupted
exception other wise we will get compile time error

Ex:

class Test

public static void main(String arg[])throws InterruptedException

System.out.println("systems");

Thread.sleep(5000);

System.out.println("domain");

Thread.sleep(5000);

System.out.println("banashankari");

interrupting a thread

If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling
the interrupt() method on the thread, breaks out the sleeping or waiting
state throwing InterruptedException. If the thread is not in the sleeping or
waiting state, calling the interrupt() method performs normal behaviour and
doesn't interrupt the thread.

we can interrupt a sleeping or waiting thread by using interrupt( ) method of


thread class.

public void interrupt()

when ever we are calling interrupt() the target thread may not be effected
immediately. At the time of calling interrupt if the target thread is not in
sleeping or in waiting state interrupt call will wait until target thread
entered into sleeping or waiting state the interrupt call will impact the target
thread..

Ex:
class MyThread extends Thread

public void run()

try

for(int i=0;i<100;i++)

System.out.println("lazy thread");

Thread.sleep(5000);

catch(InterruptedException e)

System.out.println(" i got interrupted");

class InterruptDemo

public static void main(String args[])

MyThread t=new MyThread();

t.start();

t.interrupt();//------------(1)

System.out.println("end of main method");

If we are commenting line 1 then main thread wont interrupt child thread hence
both threads will be executed until completion.
If we are not commenting line 1 then main thread interrupts the child thread rises
InterruptedException.

In this case the o/p is :

Synchronization

‘synchronized’ is the keyword appble for the methods and blocks. We can’t apply
this keyword for variables and classes.

If a method declared as synchronized at a time only one thread is allowed to


execute that method on the given object. The main advantage of
synchronized keyword is we can overcome data inconsistency problem. The
main limitation of synchronized keyword is it increases the waiting time of a
thread, and effects the performance of the system.

Hence if there is no specific requirement it’s not recommended to use synchronized


keyword.

Every object in java has a unique lock.

Synchronization concept internally implemented by using this lock concept.


Whenever we are using synchronized keyword then object level lock concept
will come into picture.

If a thread want to execute any synchronized method on the object first it should
require the lock of that object. Once a thread got the lock then it is allowed to
execute any synchronized method on that object.

Once synchronized method completes then automatically the lock will be released

While a thread executing a synchronized method on the object, then the remaining
threads are not allowed to execute any synchronized method on the same
object. But the remaining threads are allowed to execute any non-
synchronized method on the same object.

Every object in java has unique lock but a thread can acquire more than one lock at
a time.
Ex:

class Display

public synchronized void wish(String name)

for(int i =0;i<10;i++)

System.out.print("Hai.......!");

try

Thread.sleep(2000);

catch (InterruptedException e)

System.out.println(name);

class MyThread extends Thread

Display d;

String name;

MyThread(Display d,String name)

this.d = d;

this.name = name;

public void run()


{

d.wish(name);

class SynchronizedDemo

public static void main(String arg[])

Display d = new Display();

MyThread t1 = new MyThread(d," Dhoni ");

MyThread t2 = new MyThread(d," Yuvraj ");

t1.start();

t2.start();

If we are not declaring wish method as “synchronized” we will get irregular o/p
because both threads will execute simultaneously. If we are declaring wish
method as synchronized we will get regular o/p because at a time only one
thread is allowed to execute wish method.

Display d1 = new Display();

Display d2 = new Display();

MyThread t1 = new MyThread(d1,"Dhoni");

MyThread t2 = new MyThread(d2,"Yuvraj");

t1.start();

t2.start();

Even though wish method is synchronized we will get irregular o/p only because
both threads are operating on different objects.

Class level lock: If a thread want to execute any static synchronized method then
compulsory that thread should require class level lock.
While a thread executing any static synchronised method then the remaining
threads are not allowed to execute any static synchronized method of the
same class simultaneously.

But the remaining threads are allowed to execute any non-synchronized static
methods, synchronized – instance method, non – synchronized instance
method simultaneously.

Declare static synchronized in display method and try the above example we will
get regular o/p because there is class level lock.

Synchronized Blocks
It is not recommended to declare entire method as synchronized if very few lines of
code requires the synchronization concept. Such a few lines of code we can
declare in a block rather than declaring entire method as a synchronized
method

Syntax:

synchronized(b)

//critical section.

Where ‘b’ is an object reference.

To get the lock for the current object we can define synchronized block as follows

synchronized(this)

//critical section.

We can define synchronized block to get class level as follows

synchronized(Display.class)

we can define synchronized block either for object references or for class
references But not for primitives violation leads to Compile time error.
int i =10;

synchronized(i)

//------

C.E:- unexpected type

found : int.

required : reference.

Synchronized statement(Only for Interview Purpose):

The statement which are defined in inside synchronized method or synchronized


blocks are called

‘synchronized statement’.

Inter Thread Communication


Two threads can communicate with each other by using wait(), notify(), notifyAll().

These methods are available in object class but not in thread class. Because threads
are calling these methods on any object.

We should call these methods only from synchronized area other wise we get
runtime exception saying

IllegalMonitorStateException.

If a thread executes wait() method it immediately releases the lock of that


object(But not all locks) and entered into waiting state.

After giving the notification also the thread releases the lock but may not be
immediately.

public final void wait() throws InterruptedException

public final void wait(long ms) throws InterruptedException

public final void wait(long ms, int ns) throws InterruptedException

public final void notify();

public final void notifyAll();


sleep(): It is a static method on Thread class. It makes the current thread into the
"Not Runnable" state for specified amount of time. During this time, the
thread keeps the lock (monitors) it has acquired.

wait(): It is a method on Object class. It makes the current thread into the "Not
Runnable" state. Wait is called on a object, not a thread. Before calling wait()
method, the object should be synchronized, means the object should be
inside synchronized block. The call to wait() releases the acquired lock.

Ex:

class ThreadA

public static void main(String arg[])throws InterruptedException

ThreadB b = new ThreadB();

b.start();

synchronized(b)

System.out.println("Main thread is trying to call wait()");

b.wait();

System.out.println("Main thread got notification");

System.out.println(b.total);

}
class ThreadB extends Thread

int total = 0;

public void run()

synchronized(this)

System.out.println("Child thread starts calculation");

for(int i = 1; i<=100; i++)

total = total + i;

System.out.println("child thread trying to give notification ");

this.notify();

Dead Lock
If two threads are waiting for each other forever, then the threads are said to be in
“deadlock”.

There is no deadlock resolution technique but prevention technique are available

Ex:

Banker’s Algorithm.

Ex:

class A

synchronized void foo(B b)

System.out.println("Thread 1 entered foo() method");


try

Thread.sleep(600);

catch (InterruptedException e)

System.out.println("Thread 1 is trying to call b.last()");

b.last();

synchronized void last()

System.out.println("Inside A, This is last() method");

class B

synchronized void bar(A a)

System.out.println("Threas 2 entered bar() method");

try

Thread.sleep(600);

catch (InterruptedException e)

System.out.println("Thread 2 is trying to call a.last()");


a.last();

synchronized void last()

System.out.println("Inside B, This is last() method");

class DeadLock implements Runnable

A a = new A();

B b = new B();

DeadLock()

Thread t = new Thread(this);

t.start();

b.bar(a);

public void run()

a.foo(b);

public static void main(String arg[])

new DeadLock();

DaemonThread
The threads which hare running in the background to provide support for user
defined threads are called

“Daemon Thread”. Usually daemon thread are running with low priority but based
on our requirement we

can increase their priority also.

We can check whether the given thread is daemon or not by using the following
thread class thread.

public boolean isDaemon()

we can change the daemon nature of a thread by using setDaemon() method of


thread class.

public void setDaemon(Boolean b)

the daemon nature of a thread is inheriting from the parent. i.e if the parent is
daemon then the child is also

daemon and if the parent is non – daemon then the child is also non – daemon.

After starting a thread we are not allowed to change the daemon nature violation
leads to runtime exception

saying IllegalThreadStateException.

Ex:

class MyThread extends Thread

class Test

public static void main(String arg[])

System.out.println(Thread.currentThread().isDaemon());

MyThread t = new MyThread();

System.out.println(t.isDaemon());

t.setDaemon(true);

System.out.println(t.isDaemon());

t.start();

//t.setDaemon(false); - 1
}

If we don’t comment line 1 we will get the IlleagalThreadStateException, see the


following o/p.

We can’t change the daemon nature of main thread because it has started already
before main() method only.

All the daemon threads will be terminated automatically when ever last non –
daemon thread terminates.

Ex:

If we are commenting line 1, then both child and main threads are non – Daemon,
hence they will execute until their completion.

If we are not commenting line 1, then the child thread is daemon and hence it will
terminate automatically

when ever main() thread terminates.

COLLECTIONS FRAME WORK

Limitations of Object Arrays


An array is an indexed collection of fixed number of homogeneous data elements.

The main limitations of Object Arrays are

1) Arrays are fixed in size i.e once we created an array there is no chance of
increasing or

decreasing it’s size based on our requirement.

2) Arrays can hold only homogeneous data elements.

Ex:-

Student [] s = new Student [600];


s[0] = new Student;

s[1] = new Integer(10); X

s[2] = "raju"; X

We can resolve this problem by using object Arrays.

Object [] o = new Object [600];

o[0] = new Student;

o[1] = new Integer(10);

o[2] = "raju";

i.e By using Object Arrays we can hold heterogeneous data elements.

3) For the Arrays there is no underlying Data Structure i.e for every requirement
we have to code explicitly and there is no default ready made support(like
sorting, searching).

we can’t represent array elements in some sorting order by default. We can’t


prevent duplicate

object insertion etc…

To resolve the above problems of arrays, Sun people has introduced ‘collections
concept’

Collections are grow able in nature i.e based on requirement we can increase or
decrease the size.

Collections can hold heterogeneous data elements also.

Every collection class has implemented based on some data structure

Hence for every requirement ready made method support is possible.

We can represent all the elements in some sorting order. We can prevent duplicate
object insertion by default.

Comparison Between collections and Arrays


Collections Arrays

1) Collections are not fixed In size. 1) Arrays are fixed In size.

2) With respect to memory collections 2) with respect to memory arrays are


are good. not good.

3) With respect to performance 3) With respect to performance the


collections shows worst arrays are
performance.
recommended to use.

4) Collections can hold heterogeneous 4) Arrays can only hold homogeneous


data data

elements elements.

5) Every Collection class has built by 5) There is no underlying Data


using some Data structure. Structure.

6) Collection can hold only Objects but 6) Arrays can hold both Objects and
not primitives.

primitives.

Collections Frame Work


It defines group of classes and interfaces which can be used for representing a
collection of Objects as single entity.

7 key Interfaces of collection Frame Work


1) Collection :

This interface is the root interface for entire collection framework.

This interface can be used for representing a group of objects as single entity.

This interface defines the most common general methods which can be appble for
any collection object. There is no concrete class which implements collection
interface directly.

Difference Between Collection and Collections

Collection is an interface available in java.util package for representing a group of


objects as single entity.

Collections is an utility class available in java.util package and defines several


utility methods for collection implemented class object

2) List interface :

This can be used for representing a group of individual objects as a single entity
where insertion order is preserved and duplicate objects allowed. This is
child interface of collection.

The following classes implemented List interface directly.

ArrayList, LinkedList, Vector and Stack.


3) Set interface :

This can be used for representing a group of individual objects where

duplicate objects are not allowed and insertion operation is not preserved.

This is the child interface of collection

hashset and linkedHashSet are the classes which implements Set interface directly.

4) SortedSet interface :

This can be used for representing a group of individual and unique objects.

Where all the objects are inserted in some sorting order. It is the child interface of
Set interface

TreeSet is the implemented class of SortedSet


5) Queue interface:

The java.util.Queue interface is a subtype of


the java.util.Collectioninterface. It represents an
ordered list of objects just like a List , but its
intended use is slightly different. A queue is
designed to have elements inserted at the end of
the queue, and elements removed from the
beginning of the queue.

All the above interfaces(collection, List, Set, SortedSet, Queue) can be used for
representing a group of individual objects.

If u want to represent a group of objects as key value pair than we can’t use above
interfaces.

To handle this requirement sun people has introduced map interface.

6) Map:
This can be used for representing a group of objects as key value pairs. Both key
and value are

objects only.

StudentName StudentRollNo

phoneNumber contactdetails

word meaning

IP Address Domain-name

Note: Map interface is not child interface of collection.

7) SortedMap:

This can be used for representing a group of objects as key value pairs where all the
entries are

arranged in some sorting order of keys.

TreeMap is the class which implements SortedMap interface.

The following are legacy classes in collection Frame Work.

1) vector.

2) stack

3) Hashtable concrete classes

4) properties

5) Dictionary----- abstract classes


6) Enumaration--- interface

Collection
This can be used for representing a group of individual objects as a single entity.
This interface defines the most common general methods. Which can be
appble for any collection implemented class object.

Colletion Interface methods

1)boolean add(Object obj)

2) boolean addAll(Collection c)

3) boolean remove(Object obj)

4) boolean removeAll(Collection c)

(Removes particular group of objects.)

5) boolean retainAll(Collection c)

(Removes all the elements except those present in ‘c’)

6) void clear()

(Removies all objects.)

7) boolean contains(Object obj)

(Checks object is there or not.)

8) boolean contains (Collection c)

9) boolean isEmpty()

10) int size()

11) Object [] toArray()

12) Iterator iterator()

(to retrieve the objects one by one.)

List interface
This can be used for representing a group of individual objects where insertion
order is preserved and duplicate objects are allowed.
By means of index we can preserve insertion order and we can differentiate

duplicate objects.

List Interface Defines the following methods

1) boolean add(Object obj)

2) boolean add(int index, Object obj)

3) boolean addAll(Collection c)

4) boolean addAll(int index, Collection c)

5) boolean remove(Object obj)

6) Object remove(int index)

7) Object set(int index, Object new)

Old object. It replaces with the existing objected located at specified index with the
new

object. And it returns object.

8) Object get(int index)

9) int indexOf(Object obj)

10) int lastIndexOf(Object obj)

11) ListIterator listIterator()

ArrayList()
The underlying data Structure for ArrayList() is resizable Array or “Growable
Array”.

Duplicate objects are allowed.

Insertion order is preserved.

Heterogeneous objects are allowed.

‘null’ insertion is possible.

Constructors of Array List

ArrayList l = new ArrayList()

Creates an empty ArrayList object with default intitial capacity 10.

When ever ArrayList reaches its max capacity a new ArrayList Object will be
created with new

capacity.

ArrayList l = new ArrayList(int initial capacity)

Creates an empty ArrayList Object with the specified initial capacity.

ArrayList l = new ArrayList(Collection c)

For inter conversion between collection objects.

Ex:

import java.util.*;

class ArrayListDemo

public static void main(String arg[])

ArrayList a = new ArrayList();

a.add("A");

a.add(new Integer(10));

a.add("A");

a.add(null);

System.out.println(a);
a.remove(2);

System.out.println(a);

a.add(2,"M");

a.add("N");

System.out.println(a);

ArrayList and vector classes implement RandomAccess interface. So that we can


access any element with the same speed. Hence ArrayList is best suitable if
our frequent operation is retrieval operation.

Usually the collection objects can be used for data transport purpose and hence
every collection

implemented class already implemented serializable and cloneable interfaces.

ArrayList is the worst choice if u want to perform insertion or deletion in the


middle.

Note:- ArrayList is not recommended if the frequent operation is insertion or


deletion in the middle.

To handle this requirement we should go for linked list.

LinkedList()
The underlying Data Structure for linked list is doubly linked list.Duplicate objects
are allowed.

Insertion order is preserved.

Heterogeneous objects are allowed.


‘null’ insertion is possible.

Implements List, Queue, serializable, clonealbe Interfaces But not RandomAccess.

LinkedList is the bestchoice if our frequent operation is insertion or deletion in the


middle(no shift operations are required)

LinkedList is the worst choice if our frequent operation is retrieval operation.

LinkedList class usually used for implementing stacks and Queues to provide
support for this

requirement, LinkedList class contains the following specific methods.

1. void addFirst(Object obj)

2. void addLast(Object obj)

3. Object removeFirst()

4. Object removeLast()

5. Object getFirst()

6. Object getLast()

Constructors

LinkedList l = new LinkedList()

LinkedList l = new LinkedList(Collection c)

For inter conversion between collection objects

Ex:

import java.util.*;

class LinkedListDemo

public static void main(String arg[])

x --------------------------------
insertion

shifting

LinkedList l = newLinkedList();

l.add("raju");

l.add(new Integer(10));

l.add(null);

l.add("raju");

l.set(0, "chinna");

l.add(0, "Kiran");

l.addFirst("AAAA");

l.addLast("ZZZZ");

System.out.println(l);

Inter conversion between collection objects.

ArrayList l1 = new ArrayList();

l1.add(10);

l1.add(20);

l1.add(30);

System.out.println("l1--->"+l1);

LinkedList l2 = new LinkedList(l1);

l2.add(1,5);

l2.add(3,5);

l2.add(5,15);

System.out.println("l2--->"+l2);

ArrayList l3 = new ArrayList(l2)

System.out.println("l3--->"+l3);

VectorClass
The underlying Data structure for the vector is resizable array or growable array.

Insertion order is preserved.

Duplicate objects are allowed.

‘null’ insertion is possible.

Heterogeneous objects are allowed.

Best choice if the frequent operation is retrieval.

Worst choice if the frequent operation is insertion or deletion in the middle.

Vector class implemented serializable, cloneable and RandomAccess Interfaces.

Difference between vector and ArrayList?

Vector ArrayList

1) All methods of vector are 1) no method is synchronized


synchronized

2) vector object is thread safe 2) ArrayList object is not thread safe by


default

3) performance is low 3) performance is High

4) 1.0 version(Legacy) 4) 1.2 version(non Legacy)

We can get synchronized version of ArrayList of by using the following method of


collections class.

ArrayList l1 = new ArrayList();


List l2 = Collections.synchronizedList(l1);
Synchronized non-synchronized

Similarly we can find synchronized versions of set and Map objects by using the
collections class
method.

public static Set synchronizedSet(Set s1)

public static Map synchronizedMap(Map m1)

Vector methods

For adding objects.

add(Object obj)

add(int index, Object obj)

addElement(Object obj)

For removing Objects

remove(Object obj)

removeElement(Object obj)

remove(int index)

removeElementAt(int index)

clear()

removeAllElements()

For Accessing Elements

Object get(int index)

Object elementAt(int index)

Object firstElement();

Object lastElement();

OtherMethods

int size();

int capacity();

Enumaration elements();
constructors

Vector v = new Vector();

Creates an empty vector object with default initial capacity 10, when ever vector
reaches it’s max capacity a new vector object will be created with.

Vector v = new Vector(int initialCapacity)

Vector v = new Vector(int initialCapacity, int incrementalCapacity)

Vector v = new Vector(Collection c)

Ex:

import java.util.*;

class VectorDemo

public static void main(String arg[])

Vector v = new Vector();

System.out.println(v.capacity());

for (int i = 0;i<10 ;i++ )

v.addElement(i);

System.out.println(v.capacity());

v.addElement("Aa");

System.out.println(v.capacity());

System.out.println(v);

Stack
It is the child class of Vector contains only one constructor.

Stack s = new Stack();


Methods

Object push(Object obj);

For inserting an object to the stack

Object pop();

It removes and returns top of the stack.

Object peek();

Returns the top of the stack with out removal of object.

int search(Object obj);

If the specified object is available it returns its offset from top of the stack

If the object is not available then it returns -1.

boolean empty();

returns true if the stack is empty otherwise false.

Ex:

import java.util.*;

class StackDemo

public static void main(String arg[])

Stack s = new Stack();

s.push("A");

s.push("B");

s.push("C");

System.out.println(s);

System.out.println(s.search("A"));

System.out.println(s.search("Z"));

Cursors Available in collection frame work


To visit objects one by one from Collection we have to use cursors.

From the collection object to retrieve objects we can use the following 3 cursors.

1. Enumeration

2. Iterator

3. ListIterator

Enumeration
This interface has introduced in 1.0 version it contains the following 2 methods.

boolean hasMoreElements();

Object nextElement();

Ex:

import java.util.*;

class EnumaretionDemo

public static void main(String arg[])

Vector v = new Vector();

for (int i =0;i<=10 ;i++ )

v.addElement(i);

System.out.println(v);

Enumeration e = v.elements();

while (e.hasMoreElements())

Integer i = (Integer)e.nextElement();

if((i%2) == 0)

System.out.println(i);

}
System.out.println(v);

Limitations of Enumeration

1. It is appble only for legacy classes and it is not a universal cursor.

2. While iterating the elements by using enumeration we can perform only read
operation and we can’t perform any modify/removal operations.

To overcome these problems we should go for Iterator interface.

Iterator
o Introduced in 1.2 version.

o We can use Iterator Object for any collection implemented class i.e it is universal
cursor.

o By iterating the elements we can perform remove operation also in addition to


read operation.

This interface contains the following 3 methods.

boolean hasNext();

Object next();

void remove();

Ex:

import java.util.*;

class IteratorDemo

public static void main(String arg[])

ArrayList al = new ArrayList();

for (int i =0;i<=10 ;i++ )

al.add(i);
}

System.out.println(al);

Iterator itr = al.iterator();

while (itr.hasNext())

Integer i = (Integer)itr.next();

if((i%2) == 0)

System.out.println(i);

else

itr.remove();

System.out.println(al);

Note:-

1. Enumeration and Iterator are single directional cursors. They can always move
to words forward direction only.

2. By using Iterator we can perform read and remove operations. And we can’t
perform any replace or addition of new objects

To over come these limitations we should go for ListIterator interface.

ListIterator
1.It has introduced in 1.2 version and it is child interface of Iterator.

2.It is a bidirectional cursor.

3.i.e Based on requirement we can move either to the forward or backward


direction.

4.While Iterating we can perform replace and add operation in addition to read and
remove this
interface defines the following 9 methods.

1. boolean hasNext();

2. boolean hasPrevious();

3. Object next();

4. Object previous();

5. int nextIndex();

6. int previousIndex();

7. void remove();

8. void set(Object)

nextIndex(): If there is no next element it returns size of the list.

previousIndex(): If there is no previous element it returns -1 .

import java.util.*;

class ListIteratorDemo

public static void main(String arg[])

LinkedList l = new LinkedList();

l.add("balakrishna");

l.add("chiru");

l.add("venky");

l.add("nag");

System.out.println(l);

ListIterator ltr = l.listIterator();

while (ltr.hasNext())

String s = (String)ltr.next();

if(s.equals("nag"))

{
ltr.add("chaitanya");

System.out.println(l);

The most powerful cursor is listIterator. But it’s main limitation is it is appble only
for list

implemented classes (ArrayList, LinkedList, Vector, Stack).

SetInterface

This can be used for representing a group of Individual objects where insertion
order is not preserved and

duplicate objects are not allowed.

Set interface is child interface of Collection.

This interface doesn’t contain any new method and we have to use only collection
Interface methods.

HashSet( class)
The underlying Data Structure for HashSet is Hashtable.

Insertion order is not preserved and it is based on hash code of the Object.

Duplicate objects are not allowed. Violation leads to no CompileTimeError or


RuntimeError, boolean add(Object o)

Adds the specified element to this set if it is not already present.

This method simply returns false. If the object is already existing in the set.

‘null’ insertion is possible.

Heterogeneous objects are allowed.

HashSet is the best choice if the frequent operation is Search Operation.

Constructors

1. HashSet h = new HashSet()

Creates an empty HashSet object with default size


2. HashSet h = new HashSet(int initialcapacity)

3. HashSet h = new HashSet(int initialCapacity, float fillratio)

Here fillratio is 0 or 1.

HashSet h = new HashSet(Collection c)

Ex:

import java.util.*;

class HashSetDemo

public static void main(String arg[])

HashSet h = new HashSet();

h.add("B");

h.add("C");

h.add("D");

h.add("Z");

h.add(null);

h.add(new Integer(10));

System.out.println(h.add("Z"));

System.out.println(h);

LinkedHashSet (class)
It is the child class of HashSet. It is Exactly similar to HashSet. Except the following
differences.

HashSet LinkedHashSet

1) The underlying Data Structure is 1) The underlying Data Structures are


Hashtable
Hashtable and LinkedList

2) Insertion Order is not preserved 2) Insertion Order is preserved.


3) Introduced in 1.2 version 3) Introduced in 1.4 version

In the above program if u r replacing ‘HashSet’ with ‘LinkedHashSet’ the following is


the output.

Note:- For implementing caching apption the best suitable Data structure is
LinkedHashSet and LinkedHashMap where duplicate objects are not allowed
and insertion order Must be preserved.

SortedSet
This can be used for representing a group of individual objects where duplicate
objects are not

allowed.

Insertion order is not preserved but all the elements are inserted according to
some sorting order

of elements. The sorting order may be default natural sorting order or customized
sorting order.

SortedSet Interface contains the following more specific methods

1. Object first()

Returns first element in the SortedSet

2. Object last()

3. SortedSet headSet(Object obj)

Returns the SortedSet contains the elements which are less than the specified
object obj.

4. SortedSet tailSet(Object obj)

Returns the SortedSet whose elements are greater than or equal to the specified
object obj

5. SortedSet subSet(Object obj1, Object obj2)

Returns the SortedSet whose elements are >= obj1 but < Obj2

6. Comparator comparator();

Returns the comparator object describes the underlying sorting technique.


If you are using default(Assending) natural sorting order it returns null.

first()  100

last()160

headSet(140)  {100,120,130}

tailSet(140) {140,150,160}

subset(130,150) {130,140}

comparator() null

TreeSet
The underlying Data structure for the TreeSet is Balanced tree.

Duplicate objects are not allowed. If we are trying to insert duplicate object we
won’t get any

compile time error or Run time error, add method simply returns false.

Insertion order is not preserved but all the elements are inserted according to
some sorting order.

Heterogeneous objects are not allowed, violation leads to Run time error saying
class cast

Exception

Constructors

1. TreeSet t = new TreeSet();

Creates an empty TreeSet Object where the sorting order is default natural sorting

order.

2. TreeSet t= new TreeSet(Comparator c)


Creates an empty TreeSet Object where the Sorting order is specified by
comparator

object.

3. TreeSet t= new TreeSet(Collection c)

4. TreeSet t= new TreeSet(SortedSet s)

Creates TressSet Object for a given SortedSet.

Ex:

import java.util.*;

class TreeSetDemo

public static void main(String arg[])

TreeSet t = new TreeSet();

t.add("A");

t.add("B");

t.add("Z");

t.add("L");

//t.add(new Integer(10));// ? ClassCastException.

//t.add(null); //? NullPointerException.

t.add("A");// ? false.

System.out.println(t);

null Acceptance
For the empty TreeSet as the first element null insertion is possible. But after
inserting null if we are trying to insert any other element we will get
NullPointerException.

If the TreeSet already contains some elements if we are trying to insert null we will
get

NullPointerException.
Ex:

import java.util.*;

class TreeSetDemo

public static void main(String arg[])

TreeSet t = new TreeSet();

t.add(new StringBuffer("A"));

t.add(new StringBuffer("B"));

t.add(new StringBuffer("T"));

t.add(new StringBuffer("Z"));

System.out.println(t);

O/P:- R.E: ClassCastException.

If we are depending on natural sorting order compulsory the objects should be


homogeneous and comparable other wise we will get class cast Exception.

An object is said to be comparable(if and only if) the corresponding class has to
implement

comparable interface.

All wrapper classes and String class already implemented comparable interface.
But the String buffer doesn’t implement comparable interface. Hence in the
above program we got class cast exception.

Queue interface

1) If we want to represent a group of individual objects prior (happening before something

else) to processing then we should go for Queue interface.

Diagram:
2) Usually Queue follows first in first out order but based on our requirement we can

implement our own order also.

3) From 1.5v onwards LinkedList also implements Queue interface.

4) LinkedList based implementation of Queue always follows first in first out order.

Queue interface methods:

1) boolean after(Object o);

To add an object to the Queue.

2) Object poll() ;

To remove and return head element of the Queue, if Queue is empty then we will get

null.

3) Object remove();

To remove and return head element of the Queue. If Queue is empty then this method

raises Runtime Exception saying NoSuchElementException.

4) Object peek();

To return head element of the Queue without removal, if Queue is empty this method

returns null.

5) Object element();

It returns head element of the Queue and if Queue is empty then it will raise Runtime

Exception saying NoSuchElementException


PriorityQueue:

1) We can use PriorityQueue to represent a group of individual objects prior to processing

according to some priority.

2) The priority order can be either default natural sorting order (or) customized sorting

order specified by Comparator object.

3) If we are depending on default natural sorting order then the objects must be

homogeneous and Comparable otherwise we will get ClassCastException.

4) If we are defining our own customized sorting order by Comparator then the objects

need not be homogeneous and Comparable.

5) Duplicate objects are not allowed.

6) Insertion order is not preserved but all objects will be inserted according to some

priority.

7) Null is not allowed even as the 1st element for empty PriorityQueue.

Constructors:

1) PriorityQueue q=new PriorityQueue();

Creates an empty PriorityQueue with default initial capacity 11 and default natural

sorting order.

2) PriorityQueue q=new PriorityQueue(int initialcapacity,Comparator c);

3) PriorityQueue q=new PriorityQueue(int initialcapacity);

4) PriorityQueue q=new PriorityQueue(Collection c);

5) PriorityQueue q=new PriorityQueue(SortedSet s);

Example 1:

import java.util.*;

class PriorityQueueDemo

public static void main(String[] args)


{

PriorityQueue q=new PriorityQueue();

//System.out.println(q.peek());//null

//System.out.println(q.element());//NoSuchElementException

for(int i=0;i<=10;i++)

q.offer(i);

System.out.println(q);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

System.out.println(q.poll());//0

System.out.println(q);//[1, 3, 2, 7, 4, 5, 6, 10, 8, 9]

Note: Some platforms may not provide proper supports for PriorityQueue [windowsXP].

Example 2:

import java.util.*;

class PriorityQueueDemo

public static void main(String[] args)

PriorityQueue q=new PriorityQueue(15,new MyComparator());

q.offer("A");

q.offer("Z");

q.offer("L");

q.offer("B");

System.out.println(q);//[Z, B, L, A]

}
class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)

String s1=(String)obj1;

String s2=obj2.toString();

return s2.compareTo(s1);

Comparable interface:

Comparable interface present in java.lang package and contains only one method

compareTo() method.

public int compareTo(Object obj);

Example:

obj1.compareTo(obj2);

Diagram:

Example 3:

class Test

public static void main(String[] args)


{

System.out.println("A".compareTo("Z"));//-25

System.out.println("Z".compareTo("K"));//15

System.out.println("A".compareTo("A"));//0

//System.out.println("A".compareTo(new Integer(10)));//Test.java:8:

compareTo(java.lang.String) in java.lang.String cannot be applied to (java.lang.Integer)

//System.out.println("A".compareTo(null));//NullPointerException

If we are depending on default natural sorting order then internally JVM will use

compareTo() method to arrange objects in sorting order.

compareTo() method analysis:

If we are not satisfying with default natural sorting order (or) if default natural sorting

order is not available then we can define our own customized sorting by Comparator

object.

Comparable meant for default natural sorting order.

Comparator meant for customized sorting order.


Comparator interface:

Comparator interface present in java.util package this interface defines the following 2

methods.

1) public int compare(Object obj1,Object Obj2);

Diagram:

2).public boolean equals(Objectobj);

Whenever we are implementing Comparator interface we have to provide

implementation only for compare() method.

Implementing equals() method is optional because it is already available from Object

class through inheritance.

Requirement: Write a program to insert integer objects into the TreeSet where the sorting

order is descending order.

Program:

import java.util.*;

class Test

public static void main(String[] args)

TreeSet t=new TreeSet(new MyComparator());------------(1)

t.add(10);
t.add(0);

t.add(15);

t.add(5);

t.add(20);

System.out.println(t);//[20, 15, 10, 5, 0]

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)

Integer i1=(Integer)obj1;

Integer i2=(Integer)obj2;

if(i1<i2)

return +1;

else if(i1>i2)

return -100;

else return 0;

At line “1” if we are not passing Comparator object then JVM will always calls

compareTo() method which is meant for default natural sorting order(ascending

order)hence in this case the output is [0, 5, 10, 15, 20].

At line “1” if we are passing Comparator object then JVM calls compare() method of

MyComparator class which is meant for customized sorting order(descending order)

hence in this case the output is [20, 15, 10, 5, 0].

Diagram:
Various alternative implementations of compare() method:

public int compare(Object obj1,Object obj2)

Integer i1=(Integer)obj1;

Integer i2=(Integer)obj2;

//return i1.compareTo(i2);//[0, 5, 10, 15, 20]

//return -i1.compareTo(i2);//[20, 15, 10, 5, 0]

//return i2.compareTo(i1);//[20, 15, 10, 5, 0]

//return -i2.compareTo(i1);//[0, 5, 10, 15, 20]

//return -1;//[20, 5, 15, 0, 10]//reverse of insertion order

//return +1;//[10, 0, 15, 5, 20]//insertion order

//return 0;//[10]and all the remaining elements treated as duplicate.

Requirement: Write a program to insert String objects into the TreeSet where the sorting
order

is reverse of alphabetical order.

Program:

import java.util.*;

class TreeSetDemo

{
public static void main(String[] args)

TreeSet t=new TreeSet(new MyComparator());

t.add("Roja");

t.add("ShobaRani");

t.add("RajaKumari");

t.add("GangaBhavani");

t.add("Ramulamma");

System.out.println(t);//[ShobaRani, Roja, Ramulamma, RajaKumari,

GangaBhavani]

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)

String s1=obj1.toString();

String s2=(String)obj2;

//return s2.compareTo(s1);

return -s1.compareTo(s2);

Requirement: Write a program to insert StringBuffer objects into the TreeSet where the
sorting

order is alphabetical order.

Program:

import java.util.*;
class TreeSetDemo

public static void main(String[] args)

TreeSet t=new TreeSet(new MyComparator());

t.add(new StringBuffer("A"));

t.add(new StringBuffer("Z"));

t.add(new StringBuffer("K"));

t.add(new StringBuffer("L"));

System.out.println(t);// [A, K, L, Z]

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)

String s1=obj1.toString();

String s2=obj2.toString();

return s1.compareTo(s2);

Note: Whenever we are defining our own customized sorting by Comparator then the
objects

need not be Comparable.

Example: StringBuffer

Requirement: Write a program to insert String and StringBuffer objects into the TreeSet
where

the sorting order is increasing length order. If 2 objects having the same length then
consider

they alphabetical order.


Program:

import java.util.*;

class TreeSetDemo

public static void main(String[] args)

TreeSet t=new TreeSet(new MyComparator());

t.add("A");

t.add(new StringBuffer("ABC"));

t.add(new StringBuffer("AA"));

t.add("xx");

t.add("ABCD");

t.add("A");

System.out.println(t);//[A, AA, xx, ABC, ABCD]

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)

String s1=obj1.toString();

String s2=obj2.toString();

int l1=s1.length();

int l2=s2.length();

if(l1<l2)

return -1;

else if(l1>l2)

return 1;

else
return s1.compareTo(s2);

Note: If we are depending on default natural sorting order then the objects should be

“homogeneous and comparable” otherwise we will get ClassCastException. If we are


defining

our own sorting by Comparator then objects “need not be homogeneous and comparable”.

Comparable vs Comparator:

For predefined Comparable classes default natural sorting order is already available if

we are not satisfied with default natural sorting order then we can define our own

customized sorting order by Comparator.

For predefined non Comparable classes [like StringBuffer] default natural sorting order

is not available we can define our own sorting order by using Comparator object.

For our own classes [like Customer, Student, and Employee] we can define default

natural sorting order by using Comparable interface. The person who is using our class,

if he is not satisfied with default natural sorting order then he can define his own sorting

order by using Comparator object.

Example:

import java.util.*;

class Employee implements Comparable

String name;

int eid;

Employee(String name,int eid)

this.name=name;

this.eid=eid;

public String toString()


{

return name+"----"+eid;

public int compareTo(Object o)

int eid1=this.eid;

int eid2=((Employee)o).eid;

if(eid1<eid2)

return -1;

else if(eid>eid2)

return 1;

else return 0;

class CompComp

public static void main(String[] args)

Employee e1=new Employee("nag",100);

Employee e2=new Employee("balaiah",200);

Employee e3=new Employee("chiru",50);

Employee e4=new Employee("venki",150);

Employee e5=new Employee("nag",100);

TreeSet t1=new TreeSet();


t1.add(e1);

t1.add(e2);

t1.add(e3);

t1.add(e4);

t1.add(e5);

System.out.println(t1);//[chiru----50, nag----100, venki----150, balaiah----200]

TreeSet t2=new TreeSet(new MyComparator());

t2.add(e1);

t2.add(e2);

t2.add(e3);

t2.add(e4);

t2.add(e5);

System.out.println(t2);//[balaiah----200, chiru----50, nag----100, venki----150]

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)

Employee e1=(Employee)obj1;

Employee e2=(Employee)obj2;

String s1=e1.name;

String s2=e2.name;

return s1.compareTo(s2);

Comparision of Comparable and Comparator?


Comparable Comparator

1) Comparable meant for default natural 1) Comparator meant for customized

sorting order. sorting order.

2) Present in java.lang package. 2) Present in java.util package.

3) Contains only one method. 3) Contains 2 methods.

compareTo() method. Compare() method.

Equals() method.

4) String class and all wrapperClasses 4) No predefined class implements


implements Comparable Comparator.

interface.

Map Interface
If we want represent a group of objects as a key value pairs then we should go for
Map interface.Both key and and value are objects only.

Duplicate keys are not allowed but values can be duplicated.

Each key-value pair is called entry

There is no relation between Collection and Map

Collection meant for group of individual objects and Map is meant for group of key-
value pairs

Map interface is not child interface of Collection.


Each key-value pair considered as Entry object hence Map is
nothing but a set of entries.
Methods of Map interface:
1.Object put(Object key,Object value);
To add key-value pair to the map
If the specified key is already available then old value will be
replaced with new value and old value will be returned.
If the entry is added to the map then this method will return
null
2.void PutAll(Map m)
To add a group of key-value pairs
3.Object get(Object key)
Returns the value associated with specified key
If the key is not available then we will get null
4.Object remove(Object key)
5.boolean containsKey (Object key)
6.boolean containsValue (Object key)
7.int size();
8.boolean isEmpty();
9.Void clear()
Entry(Interface):
Each key-value pair is called one entry
Without existing Map object there is no chance of Entry
Object
HashMap
The underlying data structure for HashMap is Hashtable.
Duplicate keys are not allowed but values may be
duplicated.
Heterogeneous objects are allowed for both keys and values.
null is valid for both key and value
insertion order is not preserved because it is based on
Hashcode of keys
null key is allowed(only once)
null values are allowed (any no of times)
Difference between HashMap and Hashtable

HashMap Hashtable

No method is synchronized in All methods are


HashMap synchronized in
Hashtable

HashMap object is not thread Hashtable object is thread


safe safe

null is allowed for both key and null is not allowed for both
value key and value

HashMap is non-legacy class Hashtable is legacy class and


and introduced in 1.2v introduced in 1.0v

Constructors of HashMap

Construcor Description

HashMap hashMap=new Creates an empty HashMap


HashMap() object with default initial
capacity 16 and default
fill ratio 0.75

HashMap hashMap=new
HashMap(int
initialCapacity)

HashMap hashMap=new
HashMap(int
initialCapacity,float
fillratio)

HashMap hashMap=new
HashMap(Map map)

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapDemo {

public static void main(String[] args) {


HashMap map = new HashMap();
map.put("Gosling", 900);
map.put("Davidson", 800);
map.put("Bloch", 500);
map.put("Mcclanahan", 700);
System.out.println(map.put("Bloch", 678));
System.out.println(map);
// getting keys from HashMap
Set set = map.keySet();
System.out.println(set);
// getting values from HashMap
Collection collection = map.values();
System.out.println(collection);
// getting entries from HashMap
Set entrySet = map.entrySet();
Iterator iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.println(mapEntry.getKey() + "--" +
mapEntry.getValue());
if (mapEntry.getKey().equals("Gosling")) {
mapEntry.setValue(2000);
}
}
}
}
LinkedHashMap
LinkedHashMap is a child class of HashMap and
LinkedHashMap is exactly similar to the HashMap
except the following differences.

HashMap LinkedHashMap

The underlying data The underlying data structure is a


structure is combination of Hashtable and
Hashtable LinkedList

insertion order is not insertion order is preserved


preserved

introduced in 1.2v introduced in 1.4v

IdentityHashMap
In the case of HashMap to identify duplicate keys JVM
always use .equals() method of string class(compares
the content).
But in the case of IdentityHashMap instead of .equals()
method JVM will use == operator (compares the hash
code or memory reference) to identify duplicate keys.
import java.util.HashMap;
import java.util.IdentityHashMap;

public class IdentityHashMapDemo {

public static void main(String[] args) {


//HashMap implementation
HashMap map=new HashMap();
Integer i1=new Integer(100);
Integer i2=new Integer(100);
map.put(i1, "JAVA");
map.put(i2, "PHP");
System.out.println(map);
//IdentityHashMap implementation
IdentityHashMap identityHashMap=new
IdentityHashMap();
Integer i3=new Integer(100);
Integer i4=new Integer(100);
identityHashMap.put(i1, "JAVA");
identityHashMap.put(i2, "PHP");
System.out.println(identityHashMap);
}
}

WeakHashMap
In the case of HashMap an object is not eligible for garbage
collector even though it doesn’t contain any external
references if it is associated with HashMap.
In the case of WeakHashMap an object is eligible for garbage
collector if it doesn’t contain any external references
even though it is associate with WeakHashMap.
That is HashMap dominates the garbage collector where as
garbage collector dominates the WeakHashMap.
import java.util.HashMap;
import java.util.WeakHashMap;

public class WeakHashMapDemo {

public static void main(String[] args)throws


InterruptedException {
//HashMap implementation.
HashMap map=new HashMap();
Demo d=new Demo();
map.put(d, "JAVA");
System.out.println(map);
d=null;
System.gc();
Thread.sleep(5000);
System.out.println(map);

//WeakHashMap implementation.
WeakHashMap weakHashMap=new WeakHashMap();
Demo d1=new Demo();
weakHashMap.put(d1, "JAVA");
System.out.println(weakHashMap);
d1=null;
System.gc();
Thread.sleep(5000);
System.out.println(weakHashMap);
}

class Demo{
public String toString(){
return "demo";
}
public void finalize(){
System.out.println("Demo::finalize");
}
}

SortedMap
If we want arrange all entries according to some
sorting order of keys then we should go for
‘SortedMap’.
SortedMap interface defines the following 6 specific
methods.
Object firstKey()
Object lastKey()
SortedMap headMap(Object key)
SortedMap tailMap(Object key)
SortedMap subMap(Object key1,Object key2)
Comparator comparator()
TreeMap
The underlying data structure is RED-BLACK tree.
Duplicate keys are not allowed values can be duplicated.
Insertion order is not preserved and it is based on sorting
order of keys
If we are depending on natural sorting order,The keys
should be homogenous and comparable other wise we
will get ClassCastException.
If we are defining out own sorting by Comparator then keys
can be heterogeneous need not be Comparable.
There are no restrictions on values these can be
heterogeneous.
null insertion in TreeMap
If we are trying to insert null key in non empty TreeMap we
will get NullPointerException.
For the empty TreeMap as the first entry with null key is
allowed.But after inserting that entry if we are trying to
insert any other entry we will
get NullPointerException.
For the values no restrictions ,We can use any number of
nulls.
Constructors:

Constructor Description

TreeMap map=new TreeMap() It is used for natural


sorting order.

TreeMap map=new It is used for customized


TreeMap(Comparator) sorting order.

TreeMap map=new
TreeMap(Map)

TreeMap map=new
TreeMap(SortedMap)

import java.util.TreeMap;

public class TreeMapDemo {

public static void main(String[] args) {


TreeMap map=new TreeMap();
map.put("Gosling",1000);
map.put("Davidson",2000);
map.put("Mcclanahan",500);
map.put("Bloch",null);
//map.put(890,"James");//java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integer.
//map.put(null,"JAVA");//java.lang.NullPointerExceptio
n
System.out.println(map);
}
}

import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapDemo {

public static void main(String[] args) {


TreeMap map=new TreeMap(new ComaratorDemo());
map.put("Gosling",1000);
map.put("Davidson",2000);
map.put("Mcclanahan",500);
map.put("Bloch",null);
System.out.println(map);
}
}

class ComaratorDemo implements Comparator{

public int compare(Object obj1,Object obj2){


String s1=(String)obj1;
String s2=(String)obj2;
return s2.compareTo(s1);
}
}

Java Streams
Java I/O (Input and Output) is used to process the input and produce the output
based on the input.

Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.

We can perform file handling in java by java IO API.

A stream is a flow of data from source to destination

A Source can be a keyboard, file, server, client…etc

A destination can be monitor, file, client , server…etc

In java, streams are devided into three catogiries

1.Console Input/Output Streams

2.File Input/Output streams

3.Network Input/output streams


There are 3 predefined streams in java they are

1.in

2.out

3.err

1.in—it is an object reference of java.io.InputStream class

2.out &err—these are object references of java.io.PrintStream class

Note: the above all streams are defined as a static members in java.lang,System
class

Java.lang.System

Object references:

Public static final java.io.InputStream in;

Public static final java.io.PrintStream out;

Public static final java.io. PrintStream err;

File
A java file object represent just name of the file/directory.

File f = new File(“abc.txt”);

If ‘abc.txt’ is already available then ‘f’ will represent that physical file.

If it is not already available, It won’t create any new file and ‘f’ simply represents
the name of the file.
Ex:

import java.io.*;

class test

public static void main(String[] args)

File f = new File("cba.txt");

System.out.println(f.exists()); false at first time.

f.createNewFile();

System.out.println(f.exists()); true

I Run:

false

true

II Run:

true

true

A java file Object can represent directories also

Ex:

File f = new File("bbc");

System.out.println(f.exists());

f.mkdir();

System.out.println(f.exists());

I Run:

false

true

II Run:

true
true

The constructors of the file class

1) File f = new File(String name)

Here name may be file or directory name. Creates a java file object that represents a
file or directory name.

2) File f = new File(String directoryname, String subdirectory/filename)

Creates a java file object that represents file or directory name present in specified
subdirectory.

File f = new File(File directoryname, String filename/directoryname)

import java.io.*;

class Test

public static void main(String[] args)throws Exception

File f1=new File("d:\\ccccccccccc");

f1.mkdir();

File f = new File(f1, "abcd.txt");

System.out.println(f.exists());

f.createNewFile();

System.out.println(f.exists());

Important methods of File Class


1) boolean exists():

returns true if the physical file/directory presents other wise false.

2) boolean createNewFile():
returns ture if it creates a new file, if the required file is already available then

it won’t create any new file and returns false.

3) booelan mkdir()

For creation of directory.

4) boolean isFile():

returns true if the java file object represents a file.

5) boolean isDirectory():

returns true if the java file object represents a directory.

6) String [] list():

returns the names of files and directories present in the directories represented

by the file object.

If the java file object represents a file instead of directory this method returns

null.

7) Boolean delete():

for deleting the file or directory represented by java file object.

8.long length();

Returns the no characters that are present in the specified file

write a program to create a file named with ‘xyz.txt’ in the current working
directory.

File f = new File(“xyz.txt”);

f.createNewFile();

Write a program to create a directory ‘raju123’ in the current working directory


and create a

file ‘file1.txt’ in that directory.

File f = new File(“raju123”);

f.mkdir();

// File f1 = new File(“raju123”,”file1.txt”);

File f1 = new File(f,”file1.txt”);

F1.createNewFile();

Write a program to list the names of files and directories in ‘jdk’ directory.
File f = new File(“jdk”);

String [] s = f.list();

For(String s1: s)

System.out.println(s1);

FileWriter

This class can be used for writing character data to the file.

Constructors
1) FileWriter fw = new FileWriter(String fname)

2) FileWriter fw = new FileWriter(File f);

The above 2 constructors creates a file object to write character data to the file.

If the file already contains some data it will overwrite with the new data.

Instead of overriding if u have to perform append then we have to use the following
constructors.

FileWriter fw = new FileWriter(String name, boolean append);

FileWriter fw = new FileWriter(File f, boolean append);

If the underlying physical file is not already available then the above constructors
will create the required file also.

Important methods of FileWriter Class


1) void write(int ch) throws IOException

for writing single character to the file.

2) void write(String s)throws IOException.

To write String to the specified file

3) void write(char [] ch) throws IOException.

To write an array of characters to the file


void flush():-To guaranteed that the last character of the data is also writtent to the
file.

Close():- to close the file

Ex:-

class test

public static void main(String arg[])throws Exception

File f = new File("pongal.txt");

System.out.println(f.exists());

FileWriter fw = new FileWriter(f,true);

System.out.println(f.exists());

fw.write(97);//adding a single character

fw.write("run\nsoftware\n");

fw.write(‘\n’);

char [] ch1 = {'a','b','c'};

fw.write(ch1);

fw.flush();

fw.close();

FileReader

This class can be used for reading character data from the file.

Constructors
1) FileReader fr = new FileReader(String name);

2) FileReader fr = new FileReader(File f);

Important methods of FileReader Class


1) int read():

for reading next character from the file and returns it Unicode character value. If
there is no next character this method returns -1

2) int read(char[] ch): it attempts to read no of characters from file into array and
returns the no of characters which are read from the file.

3) void close():

to close FileReader

Ex:

class test

public static void main(String arg[])throws Exception

File f = new File("pongal.txt");

FileReader fr = new FileReader(f);

System.out.println(fr.read());

char [] ch2 = new char[(int) (f.length())];

System.out.println(ch2.length);

fr.read(ch2);

for(char ch1: ch2)

System.out.print(ch1);

System.out.println(“************”);

FileReader fr1=new FileReader(f);

Int i=fr1.read();

While(i!=-1)

System.out.println((char)i);

I=fr1.read();

}
}

The usage of FileReader and FileWriter is in efficient because

While writing the data by using FileWriter, programmer is responsible to insert


line separators manually.

We can read the data character by character only by using FileReader. If


increases the number of I/O operations and effect performance.

To overcome these problems sun people has introduced BufferedReader and


BufferedWriter classes.

BufferedWriter
This can be used for writing character data to the file.

Constructors
1) BufferedWriter bw = new BufferedWriter(writer w)

2) BufferedWriter bw = new BufferedWriter(writer r, int size)

BufferedWriter never communicates directly with the file. It should Communicate


through

some writer object only.

Q) Which of the following are valid declarations

1) BufferedWriter bw = new BufferedWriter(“abc.txt”); X

2) BufferedWriter bw = new BufferedWriter(new File(“abc.txt”)); X

3) BufferedWriter bw = new BufferedWriter(new FileWriter(“abc.txt”));

4) BufferedWriter bw = new BufferedWriter(new BufferedWriter(new

FileWriter(“abc.txt”)));

Important methods of BufferedWriter Class


1) void write(int ch) thorows IOException

2) void write(String s) throws IOException

3) void write(char[] ch) throws IOException

4) void newLine()

for inserting a new line character.


5) void flush()

6) void close()

Ex:-

class test

public static void main(String arg[])throws Exception

File f = new File("pongal.txt");

System.out.println(f.exists());

FileWriter fw = new FileWriter(f);

BufferedWriter bw = new BufferedWriter(fw);

bw.write(97);

bw.newLine();

char [] ch1 = {'a','b','c','d'};

bw.write(ch1);

bw.newLine();

bw.write("raju");

bw.newLine();

bw.write("software");

bw.flush();

bw.close();

Note: when ever we are closing BufferedWriter automatically under lying writers
will be closed

BufferedReader
The advantage of BufferedReader over FileReader is we can read the data line by
line instead of reading character by character. This approach improves the
performance of the system by reducing the no of read operations
Constructors
1) BufferedReader br = new BufferedReader(Reader r)

2) BufferedReader br = new BufferedReader(Reader r, int buffersize)

BufferedReader never communicates directly with the file. It should Communicate


through

some reader object only.

Important methods of BufferedReader Class

1) int read()

2) int read(char [] ch)

3) String readLine();

Reads the next line present in the file. If there is no nextline this method returns
null.

4) void close()

Ex:

class test

public static void main(String arg[])throws Exception

FileReader fr = new FileReader("pongal.txt");

BufferedReader br = new BufferedReader(fr);

String s = br.readLine();

while(s != null)

System.out.println(s);

s = br.readLine();

}
Note:- When ever we r closing BufferedReader ,automatically underlying
FileReader object will be

closed.

types of streams:

===============
1.Byte streams

2.Character streams

1.Byte streams:

these streams handle text,image graphics,animation,audio,video...etc

2.Character streams:

these streams handle only text type of data(characters)

DataInputStream and DataOutputStream classes support all primitive data types


and Strings.

ObjectInputStream and ObjectOutputStream classes support objects.

The hierarchy of byte stream classes:

object

InputStream OutputStream
The hierarchy of character stream classes:
object

Reader Writer

BufferedReader InputStreamReader
BufferedWriter Printwriter

OutputStreamWriter

FileReader
FileWriter
java.io.InputStream

================

methods:

public int read(byte[])throws java.io.IOException;

==> it is used to accept data from keyboard

//program to demonstrate

import java.io.*

class Demo

public static void main(String args[])

try

byte b=new byte[10];

System.out.println("enter any number:");

System.in.read(b);

String s1=new String(b);

String s2=s1.trim();

int x=Integer.parseInt(s2);

System.out.println(x);

catch(IOException ie)

System.out.println(ie);

}
}

FileInputStream

FileInputStream class possesses the functionality of reading one byte at a time from
a file.

java.io.FileInputStream

================

constructor:

public FileInputStream(String) throws FileNotFoundException;

==> it opens a file for reading if the file is exist, otherwise FileNotFoundException
will be thrown

methods:

1.public int read(byte[])throws java.io.IOException;

==> it is used to accept data from keyboard

2.public native int available() throws IOException;

it returns file size

3.public void close() throws IOException;

steps to develop apption

1.open a file for reading

2.find out file size

3.allocate memory in Ram according to file size

4.read data from file

5.display data on monitor.

6. close a file.
import java.io.*

class ReadDemo

public static void main(String args[])

try

FileInputStream fis=new FileInputStream(args[0]);

int n=fis.available();

byte b=new byte[n];

fis.read(b);

String s=new String(b);

System.out.println(s);

catch(Exception ie)

System.out.println(ie);

FileOutputStream:

FileOutputStream class possesses the functionality of writing one byte at a time into
a file.

java.io.FileOutputStream

================

constructor:

public FileOutputStream(String) throws FileNotFoundException;


==> it opens a file for writing if the file is exist, otherwise FileNotFoundException
will be thrown

public FileOutputStream(String,boolean) throws FileNotFoundException;

==> it opens a file in append mode

methods:

1.public void write(byte[])throws IOException;

2.public void close()throws IOException;

note: in write mode existing data will be erased

steps to develop apption

1.open a file for reading

2.find out file size

3.allocate memory in Ram according to file size

4.read data from file

5.open a file for writing or appending

6.write data to a file

7. close a file.

import java.io.*

class CopyDemo

public static void main(String args[])

try

FileInputStream fis=new FileInputStream(args[0]);

int n=fis.available();
byte b=new byte[n];

fis.read(b);

FileOutputStream fos=new FileOutputStream(args[1],true);

fos.write(b);

catch(Exception ie)

System.out.println(ie);

PrintWriter
This is the most enhanced writer to write character data to the file . by using
filewriter and bufferedwriter we can write only character data but by using
printwriter we can write any primitive datatypes to the file also

The most enhanced writer for writing character data to the file is PrintWriter

Constructors
1) PrintWriter pw = new PrintWriter(String fname)

2) PrintWriter pw = new PrintWriter(File f);

3) PrintWriter pw = new PrintWriter(Writer w);

Important methods

1) write(int ch)

2) write(char [] ch)

3) write(String s)

4) print(int i)

print(double d)

print(char ch)

print(Boolean b)

print(char ch[])
5) void flush()

6) close()

Ex:

class test

public static void main(String arg[])throws Exception

FileWriter fw = new FileWriter("pongal.txt");

PrintWriter out = new PrintWriter(fw);

out.write(97);

out.println(100);

out.println(true);

out.println('c');

out.println("FDGH");

out.flush();

out.close();

Serialization Introduction
Serialization: The Process of Saving an object to a file is called “serialization”. But
strictly speaking

serialization is the process of converting an object from java supported format to


network or file supported

format.

By using FileOutPutStream, ObjectOutPutStream classes we can achieve


serialization
Deserialization: The process of reading an object from a file is called
deserialization. But strictly speaking it

is the process of Converting an object from network supported format or file


supported format to java

supported format.

By using FileInputStream, ObjectInputStream we can achieve deserialization.

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

class Dog implements Serializable {


int i=10;

int j=20;

public class SerializeDemo {

public static void main(String[] args)throws Exception {

//Serialization

Dog d=new Dog();

FileOutputStream fos=new FileOutputStream("abc.ser");

ObjectOutputStream oos=new ObjectOutputStream(fos);

oos.writeObject(d);

//De-Serialization

FileInputStream fis=new FileInputStream("abc.ser");

ObjectInputStream ois=new ObjectInputStream(fis);

Dog d2=(Dog)ois.readObject();

System.out.println(d2.i+"----"+d2.j);

/*

Output:

10----20

*/

We can perform serialization only for serializable objects.An object is said to be


serializable if only if the corresponding class should implement Serializable
interface.

Serializable interface is defined in java.io package and doesn’t contain any method
,It is a marker inetrface.
If we are trying to perform serialization of non-serializable objects,We will get
RuntimeException saying “NotSerializableException“.

At the time of serialization,If you don’t want to send the value of a particular
variable,We have to declare that variable as transient.

At the time of serialization ,JVM ignores the original value of transient variable and
send default value.i.e transient means not to serialize.

static variables are not part of the object,Hence they won’t participate in
serialization process.

As static variables won’t participate in serialization,declaring static variable as


transient there is no impact.

Similarly,declaring final variable as transient there is no impact.

Declaration Output

int i=10; 10—20


int j=20;

transient int i=10; 0—20


int j=20;

transient static int i=10; 10—0


transient int j=20;

transient final int i=10; 10—0


transient int j=20;

Você também pode gostar