You are on page 1of 77

Exception Handling

1 Error is a abnormal condition ,it occurs when ever the execution of


the program stops temporarily
2 In general some type errors are generated because of writing wrong
instructions ina program ,Error is a abnormal condition ,it occurs
when ever the execution of the program stops temporarily so that it is
necessary to identify the errors and solve those errors.
3 While writing the java program these errors are generated at two
different locations they are
I At compile time
II At runtime

Compile time errors:

These are the errors are occurred are generated at compile time and these are
raised because of non-following of standards of specific programming
language.

Ex: Statement missing

Runtime Errors:These are the errors generated because of writing wrong


logics and these errors are generated at the run time of running of the
program and this also known as exception.

In any programing language it is some what difficult to handle run time


errors (or) exceptions,in java programing language a special concepts is
introduced to handle run time errors called Exception handling.

In general while running the program if any error is generated either because
of writing wrong logic (or) by providing wrong input values then system will
give runtime error msg called system designed error message .

This msg may (or) may not understandble develeper(or) enduser.To overcome
this problem as a java develeper this is our responsibility to convert from
system definedned error msg tosystem definedned error msg . . This is
achived by exception handling

Definition of exception handling:


It is a special mechanism to handle run time errors

(or)

It is a special mechanism to convert system defined error msg to user defined


msg.

Note: By using exception handling mechanism we can make identification of


runtime errors very easily by the end user.But it cannot be used to solve the
errors.
Classification exceptions:

Exceptions are mainly classified into 2 types

i Predifined execptions
ii User defined exception

Predefined exceptions:

This is an exception designed by sun microsystem and develeped and supplied


as a part of java api, every exception is existing as predefined class in java api
these exceptions are classified into following types

Predefined Exception

Asynchronous Exceptions Synchronous Exceptions

Checked Exceptions Unchecked Exceptions


-Asynchronous exceptions are raised because of hardware failures to handle this
exceptions sun Microsystems give a predefined class error no developer can
handle this exceptions directly

Ex: memoryfailure, keyboard failure, Ram failure

Synchronous Exceptions are raised because of writing wrong logics (or) because of
providing wrong input values Sun Microsystems was give predefined class to
handle this exceptions calledexception.

Developer can easily handle all types of synchronous exceptions

Unchecked Exceptions:

These are the exceptions both identified and raised at runtime only by verifying
primary locations like heap memory,javastack etc

Checked Exceptions:

These are the exceptions are raised at compile time verified by hard disk and raised
at run time called checked Exceptions.
javaAPI

Throwable

Error(handle asynchronous Exception) Exception(handle


synchronous Exception)

checkedException
runtimeException

classnot Found Exception


Arithmetic Exception

filenot fund Exception


ArrayIndexOutOfBoundsException

IOException
StringIndexOutOfBoundsException

Interrupted Exception
NullpointerExcepiton
NumberFormatException

NosuchMethod
Exception

NoSuchFieldException

In java language every Exceptions is existing is a predefined class and these all
classes are available at java.lang package .The Exceptions classes hierarchy is
shown in previous page

Class Not Found Exceptions:

This is an Exception raised when ever thwe given class is not available at the
Specicfic Location.

FileNot found Exceptions:

This is an Exeception raised when ever the given file name is not avialble at the
specific location .

IOException:

This exception is raised when ever problem is occoured either while writing data or
read the data from the file respectively.

Interruped exception:

This is the exception raised when ever a thread is interrupted at the time of the
exception or running.

Arithmetec exception ;

This is the raised when ever any problem occurred while performing an
mathematical or arithmetical operations.

Ex: int x=10,y=0,z;


Z=x/y;

Array index out of bounds exception:

Which is an exception raised whenever the given index value of an array out of
range.

Ex: int a[]=new int a[5];

A[0]=15;

A[10]=6; not valid

String index out of bounds exception:

This is an exception occour when ever the string index value is out of range

Ex: string s=venu;

s.charat(1)=e;

s.charat(15)=*; not valid

H
E
L
L
: out of bounds exception

Null pouinter Exception:

This is an exception raised when ever we are accessing the class properties with
the null references

Ex: class A

Void f1()
{

--

--

--

A a;

a.f1(); (null pointer Exception)

Number format Exception:

This is an exception raised when ever the string value is mismatched data type

Ex: class A

Public static void main (string args[])

Int x=Integer.parseInt(args[1]);

Java a helloin the above example it is not possible to convert direct string into
integer type.

No such method exception:

This is an exception raised whenever the excepted method is not available in the
given program.

Example:
Class A

Void f1()

-----

------

Javac A.java

Java A (main method is expecting)

In the above example main method is expected.

No such field exception:

This is an exception raised whenever the expected data member is not available at
given location.

Operation for the above figure:

While executing a program we can give an input value if that value is valid then
JVM gives a valid output else it connect to throwable class of java API and ask
for the matching exception class for that invalid input.

Throwable class will returns a matching exception class to the JVM after
verification, now JVM will execute an object for that returned exception class and
that will be thrown to the program( object holds system defined error message).

As a java developer we must convert that system defined error message into user
defined error message using exception handling mechanism.

How handle the exceptions:

In java we can handle the exceptions by using the special mechanism try-catch
construction.
Try and catch both are keywords in java language and these are represented in the
form of blocks technically called as tryblock and catch block respectively.

Catch block always contains user defined error message statements.

Syntax:

Try

---- // logic or problem code

-----

Catch( exception classname object)

------

----- user defined error message

------

------

---

--

Write a java program which will illustrate the cocept of Arithemetic exception?

Import java.util.*;

Class ArException

{
Public static void main (string args[])

Int x,y,z;

System.out.println( enter x and y values);

Scanner s=new Scanner(system.in);

X=s.nextInt();

Y=s.nextInt();

Try

Z=x/y;

System.out.println(z);

Catch(ArithmeticException ae)

System.err.println(denominator is should not be zero);

1. For one try block any number of catchblocks can be written.


2. With out try block no catch block is exist, and also with out catch no try
block can exist.
3. One try block can contain any nimber of exceptional statements but only one
one exception is raised at a time.
4. One try block can contain any number of catch blocks but one catch block
can handle only one exception at a time.
5. In every catch block we must create object reference of exception of
exception class(any type of exception)

Operation:

1. While execution of program internally control enters into try block and
start execution.
2. If no execution is raised in try block then all the statements of try block
statements are excuted by neglecting all catch blocks.
3. IF any exception is raised in the try block very immediately control is
comes out side of the block and starts comparing from first catch block
object onwards until getting match catch block (or) finding match catch
block.
4. When ever it founds matching catch block the statements of that catch
block is executed and neglect execution of remaining catch block.
5. Every after complets of a execution catch block statement control never
return back to try block to execute remaining statement.

Note:

In a java program block will be executed every time but catch will be executed
whenever an exception is raised.

(1) Javac ArException.java

Eneter x and y values

10 5

(1) Javac ArException.java

Eneter x and y values

10 0

Denominator should not be zero


Write a java program to handle multiple Exceptions one after another?

Import java.util.*;

Class Mexp

Public static void main (string args[])

Int x,y,z;

System.out.println( enter x and y values);

Scanner s=new Scanner(system.in);

X=s.nextInt();

Y=s.nextInt();

try

Z=x/y;

System.out.println(z);

int a[]=new Int[5];

int I;

System.out.println( enter array index value);

I=s.nextInt();

a[i]=200;

System.out.println(a[+i+]+a[i]);
}
Catch(ArithmeticException ae)

System.err.println(denominator is should not be zero);

Catch(ArrayIndexOutofBoundsException be)

}
System.out.println( array index is out of range);

In the above example only one exception is raised at a time whenever we solve the
first problem then only second exception is going to raised.

If we want to raise multiple exceptions at a time we have to write multiple try


catch blocks.

Syntax:

try

------

------

Catch(ExceptionClassname obj)

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

try

------

------

Catch(ExceptionClassname obj)

------

------

------

------

Write a java program to handle multiple try catch blocks?

Import java.util.*;

Class MtryExp

Public static void main (string args[])

Scanner s =new Scanner(system.in);

try

{
String s =hello;

int I;

System.out.println( Enter string index value);

I=s.nextInt();

char c =s.charAt();

System.out.println(c=+c);

Catch(StringIndexOutOFBoundsException se)

System.out.println(index value of string is out of range);

try

int a[]=new Int[5];

int i1;

System.out.println( enter array index value);

i1=s.nextInt();

a[i]=200;

System.out.println(a[+i+]+a[i]);
}

Catch(ArrayIndexOutofBoundsException ae)

}
System.out.println( array index is out of range);
}

Finally block:

Finally is keyword in java language can be used to represent set of statements in


the form of block any it is technically known as finally block

Syntax:

finally

-----

-----

The statements of finally block are excuting irrespective of raising an exception in


try block that means even exception raised in the try block the remaining
statements can be executed when ever they are kept under finally block.

Write a java program to handle finally block

Import java.util.*;

Class NfExp

Public static void main (string args[])

Int x,y,z;

X=Integer.parseInt(args[1]);

y=Integer.parseInt(args[2]);
z=x+y;

System.outprintln(z);

Catch (NumberFormatException nfe)

System.out.println(please enter integer values only);

Finally

System.out.println(hello world);

o/p:javac NFexp.java

java Nfexp 10 abc

please Enter integer values

In the above example that try block statement which are executed mandatorly as
placed inside the finally block so that those try block statements are executed with
in finally block irrespective of raising of an exception.

Handling of unknown Exception:

1. A s a java developer if we are unable identify the any type of Exception then
we can use any of following mechanisms .to know that raised Exceptiohn.
(i) Using Exception class
(ii) Using PrintStackTrace()
(iii) Using getMessage()
Using Exception Class:

If we dont know the Exactly name of exception in try block then we can create
the exception class object in the catch block and the object can be displayed.

Syntax:

Try

-----

-----

Catch(Exception e)

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

--------

If we are displying exception class object which gives two properties

(i) Name of Exception


(ii) Exception message

Example:

Try

Int x=10,y=0,z;

Z=x+y;

System.out.println(z);
}

Catch(exception e)

System.out.println(e);

o/p:

java.lang.Arithemetic Exception

\ by 0

Once the developer knows about exception the code should be rewritten with
known Exception class name

Note:Exception class can handle any type of exception so that it is highly


recommended to write a catch block

With Exception class object at the end of try,catch construction

Synatx:

Try

-----

------

Catch(ArithmeticException ae)]

--------

--------
}

Catch(NumberFormatException nfe)

-------

-------

PrintStackTrace():

It is a predefined method in throwable calss can be used to display 3 properties


of an exception

(i)Exception name

(ii)Exception message

(iii)Line number

Example:

Try

Int x=10,y=0,z;

Z=x/y;

System.out.println(e);

Catch( Exception e)

e.printstacktrace();

}
O/P:

Java.lang.ArithmeticException-Nmae of the Exception

/ by zero-message of an exception

At exception class.main(Exception.class.java.a)-line number

Even printstacktrace() is available in throwable class that can be called using of


its derived class object

getMessage():

It is a predefined method in throwable class can be used to know the Exception


message this method returns string value

Try

Int x=10;y=0,z;

Z=x/y;

System.out.print(z);

Catch(Exception e)

Ssyetm.out.println(e.getMessage());

O/P

/ by zero(Exception message)

Throws():

It is a keyword in java language used by the method to throw the exception to


its calling method
Throws keyword always followed by method signature

Syntax:

Returntype methodname(mp/np)throws exception class1,exception class 2

-----

-----

Throws keyword always throws the exception which is raised body part of the
method to its calling method and throws keyword can be followed by any
number of Exception classes

The main advantage of throws keyword is any exception is raised in any no bof
methods of one class (or) multiple classes can be handled by writing single try
catch block because of these length of the program can be reduced

Write a java program to illustrate throws keyword?

Class Demo1

Void f1() throws


ArrayIndexOutOfBoundsOfException,StringIndexOutOfBoundsException

String s=hello;

Char c=s.charAt(1);

Syatem.out.println(c=+c);

Int a[]=new int[5];

d[2]=134;
System.out.println(a[2]=+a[2]);

Void f2();

Int x=10,y=5,z;

Z=x/y;

Sop(z);

Class Demo2

Void f3(String s1,String s2)throws Exception

Int x=Integer.parseInt(s1);

Int y=Integer.parseInt(s2);

Int z=x+y;

Sop(z=+z);

Class ThrowsDemo

Public static void main(string args[])


{

Try

Demo1 d1=new Demo1();

Demo1 d2=new Demo2();

D1.f1();

D1.f2():

D2.f3();

Catch(StringIndexOutOfBoundsException e)

Sop(String value is out of range);

Catch(ArithmeticException ae)

Sop(denominator should not be zero);

Catch(NumberFormatException nfe)

Sop(please pass integer values only);

Catch(Exception e)
{

Sop(e);

In the above example if any error is generated in any method that will be
thrown to the related calling method aand that exception is handled by try catch
conctructor

If any method followed by throws keyword there is no necessity of using try


catch block with in the same method(but it is not mandatory)

User Defined Exception:

if any exception defined by the user then that exception is called as user defined
exception

User defined exceptions are used to raise the user defined exception which are
unable to raised by the JVM

Examples:

Negative age ,negative salary of an employee,accepting minimum number of


character and maximum number of character.

If any end user enter this salary in ve value jvm will never raise an exception
because any datatype can accepting both the types may +ve (or) negative at that
time as java developer we must create an exception class to handle these type of
exception.

Rules to create user defined exception:

Create a package with valid user name

Package package1,package2
Desine user defined class either by extending Exception class (or) runtime
Exception class

Public classname extends Exception

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

Create parameterized constructor by passing string value with in that class c

Classname(string var)

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

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

In the above syntax string variable can be used to hold the common Exception
message

From that parameterized constructor we must call super class constructor by


passing same string value

Classname(string var)

Super(var)

The main advantage with user defined exception class we can able to raise same
exception class multiple times in multiple programs of a specific application

Example :
Package p1

Public class A extends exception

A(string str)

Write a java program to handle over defined exception

Nage.java

Package a

Public class nage extends Exception

Public nage(string str)

Super(str);

AgeCheck.java

Package chk

Import na.Nage

Public void checkage(string s)throws Nage

Int age=Integer.parseInt(s[])

If(age<0)
{

Nage na=new Nage(invalid age);

Throw(na);

Else

Sop(invalid age);

Finalage.java

Import chk.agecheck;

Import na.Nage

Class FinalAge

Psvm(string args[])

Try

Agecheck ac=new AgeCheck();

Ac.Checkage(args[0]);

Catch(Nage a)

{
Sop(dont enter ve age);

O/p:

Javac d.Nage.java

Javac d.AgeCheck.java

Javac d Finalage.java

Java final age 20

Valid age

Java finalage-20

Dont enter ve value

Throw:

Throw is a keyword in a java language can be used to through a user defined


exception which is raised in the method body to its method signature

Sntax:

Throw(exceptionclass object)

Throw keyword must written with in method body if we are using throw keyword
then it is very mandatory throws keyword beside signature of the method

Syntax:

Returntype method name(lpr/np)throws exception class1,exception calss 2

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

Throw(exceptionclass object)

Q:

What is rethrowing of an exception ?

If one exception throwing to some location indirectly from different other location
called rethrowing of an exception

Example:

Throw keyword throws an exception to method signature and method is thowing


an exception to calling method by using throws keyword is rethrowing of an
exception

Polymorphism:

If any element is existing multiple times in different forms is known as


polymorphism (polymorphism represents many number of forms)

In java language polymorphism can be achived using methods

Definition:

With same method name is existing multiple times to performs multiple


opearations is known a polymorphism.polymorphism is mainly classified into two
types

(i) Dynamic polymorphism


(ii) Static polymorphism

Dynamic Polymorphism:
When ever method call with method body at run time is known as dynamic
polymorphism(or)

Runtime polymorphism

Ex:

Class

Void f1();

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

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

In java language any nonstatic method can be called using object reference for
object memory allocated at runtime so that binding method called and method
body will be done runtime only that means when ever we want to achive dynamic
polymorphism that must be done through non static methods .

In java language Dynamic polymorphism can be achived in two different ways

(i)overloading

(II)overriding

Overloading:

When ever same method name is existing multiple times with in the same class
either with different number of parameters ,diff type of parameter(or) with diff
order of parameters is known as overloading (or) method overriding

Syntax:

Class className
{

Returntype methodname()

------

------

Returntype methodname(datatype var2)

------

-----

Returntype methodname(datatype var1,datatype var2)

------

-----

Returntype methodname(datatype var2,datatype var1)

------

-----

Write a java program to handle method overloading

Class A
{

Void f1();

System.out.println(hello f1());

Void f1(int a)

System.out.println(hello f1(int a));

Void f1(float b);

System.out.println(hello f1(float b));

Void f1(char c)

System.out.println(hello f1(char c));

Class M

Public static void main(string args[])

A a=new A();
a.f1();

a.f1(2);

a.f1(2.3f);

a.f1(c);

o/p:

javac M.java

java M

hello f1()

Hello f1(int a)

Hello f1(float b)

Hello f1(char c)

Note:

The scope of overloading with in the class that means the same method can be
overloaded in same class but not in other classes

Overriding:

When the same Method name is existing in multiple times in both case and derived
classes with same signature (same no of parameters ,same type of parameters,same
order of parameters and same return type)is known as over riding

The scope of overriding is in both in base and derived classes

Syntax:

Class <classname>

{
Return type method name()

-------

------

Class <derived class> extends <base class>

Returntype method name()

------

------

If base class is derived in derived class the derived class method overrides the base
class method whenever both the method are existing with same name and same
signature .so that the derived class overriding method called when ever we are
accessing same method name with derived class object

Class A

Void f1()

System.out.println(this is f1() of A class);

}
}

Class B

Void f1()

System.out.println(this is f1() of b class);

Class over1

Public static void main(String []args)

B b=new B();

b.f1();

b.f1();

A a=new A();

a.f1();

a.f1();

o/p:

javac over1.java

javac over1
This is f1() of B class

This is f1() of B class

This is f1() of A class

This is f1() of A class

In the above example highest priority given to derived class overridden methods
whose accessing those properties with derived class object

We can access both base and derived class methods using the same reference as
shown in below

Class A2

Int x;

Float y;

Void show(int p,float q)

System.out.println(welcome to A 2 class);

X=p;

Y=q;

System.out.pritnln(welcome A2 class);

X=p;

Y=q;
System.out.prinln(x=+x);

System.out.prinln(y=+y);

Class B2 extends A2

Int a,b;

Void show(int p,int q)

System.out.println(a=+a);

System.out.println(b=+b);

Class Over2

Public static void main(string args[])

A oa;

oa=new A;

oa.show(43,12.0f);

oa=new B2();

oa.show(89,72.5f)

}
}

o/p:

welocome A 2 class

x=43;

y=12.0

this is the B2 class

a=89;

b=72.5f

Memory Allocation:

45
Null 1001 2001 12.9

1001

9
72.5
2001

When ever we we want to restrict overriding then very mandatory use the final
keyword before using overridden method

Syntax:

Final returntype methodname(lp/np)

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

Static polymorphism:

When ever method call binds with the method body at the time of compilation is
known as static polymorphism(or ) static Binding or compile time
polymorphism(or)early binding

In java language static polymorphism exihibited by using static methods.

Static polymorphism always can be achived only by overloading

Note:

Static methods can be overloaded but can not be overridden

Static rt methodname(lp/np)

{ method body

-----
classnamee.method name(var1,var2)

------

Biding at compile time Method call

Static methods can be overloaded similar to non static methods and its scope is
only with in the class

Syntax:

Class <class name>

Static returntype methodname()


{

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

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

Static return type methodname(datatype1.var)

-----

-----

Class A

Static void f1()

System.out.println(hello f1());

Static void f1(int a)

System.out.println(hello f1(int a));

Class Sa
{

Public Static void main(string args[])

A.f1();

A.f1(12);

Note:

Static methods base class cant be overridden non static methods of derived class

Note:

In overloading of either static (or) dynamic polymorphism of return type of a


method may or may not me same but the return type of overridden methods in
dynamic polymorphism should be same

STRING HANDLING:

in java language we are able to perform various operations on string values to


perform these operations some predefined methods are available in either String
(or) String Buffer class

String class:

It is a predefined class in java.lang package, can be used to defined the string


values these are immutable that means whose values canot be changed at
compile time of the program

Syntax:

String varname=value;

(or)

String Objectname=new string(value);


String Buffer class:

It is a predefined class in java.lang package can be used to handle various


operations strings these values are mutable that means these values can be changed
dynamically at the Execution time of program

StringBuffer objname=new StringBuffer(value);

String class methods:

Length():

Which can be used to find the length of the string

Ex:

String s1=hello

String s2=new String(student);

S1.length():----5(number of characters)

s.length():------7(number of characters)

charAt():

which can be used to findout specific character at given index value

s1.charAt(1):------------e

1001

H 0
E
L 1
L 2
o
3

4
To lowercase():

Which can be used to upper case string into lower case Stiring

S2.toLower();---------------Student

toUppercase():

which can be used to convert to lower case string into upper case

s1.uppercase();HELLO

concat():

which can be used to combined to two strings

s1.concat(s2):====HelloStudent

s2.concat(s1):=====studentHello

compareTo():

which can be used to compare two strings it compares ASCII values of characters
in string and returns 0 if both the string are equal otherwise it returns either
+ve(or) ve value (Difference ASCII value)

Syntax:

S1.compare(s2):

Int i=s1.compareTo(s2);

If(i==0)

System.out.println(strings are same);

Else
{

Sop(strings are different);

Compare To ignore case():

Which is also similar to compare To() but it is case insensitive method

Syntax:

S1.compareToIgnoreCase(s2);

Equals():

Which can be used to compare two strings are the same returns true otherwise
returns false (it is Boolean method)

Syntax:

S1.equals(s2);

It is case sensitive method

EqualsIgnoreCase():

It is similar to equals method but it is case insensitive

Syntax: s1.equalsIgnoreCase(s2);

What is the the difference between Equals and ==

Equals() method is always compare content of two strings where as ==


compares references

Ex: String s3=Hello;

String s4=s3; string s5=hello;

S3

1001
H 0
E
L 1
L 2
o
3

s4

1001

S5

1001

H 0
E
L 1
L 2
o
3

4
Startwith():

It is a Boolean method used to check whether the string value is start with any
sfecific substring (or) not

Ex: String s6=Hello Friend how are you;

S6.startwith(hello); true

EndWith():

It is a Boolean method can be used to check whether the given string is ends with
given substring or not

Ex:

S6.endswith(hello)======false

S6.endsWith(you)======true

Syntax:

S1.endswith(any string);

Start with (),endswith() these methods for searching operations in real time

indexOf():

which can be used to retrieve the index value of a stringh or character (always it
gives the index value of first occurrence of first occurrence of either character or
string )

String s6=hello friend how are you

S6.indexof(e);---1

S6.indexof(friend);---6

lastIndexOf():
which can be used to retrieve the index of va;lue of last index of any character
substring in the given string

s6.lastIndexof(e)----19

s6.lastIndexof(friend)----6

SubString():

which can be used to retrieve substring from the given string It can be used in 2
ways

(a)substring(indexvalue)

Which can be used to retrieve a substring starting from given index value to last
character of main string

(b)substring(startindex,endindex)

Which can be used to retrieve a substring from given string based on starting and
ending index values

String s6=Hello friend how are you

Ex:s6.Substring(13);===how are you

Ex:s6.substring(6);===friend

In realtime it is used to comparing only the some part of two string

Trim():

Which can be used to remove blank spaces before starting of string after ending of
string

Ex:

String s7==abcd;

S7.trim();==abcd

Split():
Which can be used to split a string into no of substring based on delimeter

Syntax:

Stringobject.Split(delimeter)

In the above syntax delimeter can be any special symbol

Ex:

String sp=Welcome to Hyderabad;

String a[]=sp.Split c();

For(i=o;i<a.length;i++)

Sop(a[i]);

o/p:

welcome

to

Hyderabad

In the above example string will be devided into no of substring based on space

Note:

More than one special symbols split at a time

Ex:split(.,:);

Because of above syntax the main string will be devided into n number of parts
when ever it founds either .(or),(or):

String Buffer class methods:


String buffer class is mutable that means that content can be changed at any where
in the program dynamically

Using Stringbuffer class we can we can able to perfom almost all operations on
the string which we have done using String class along with that some multiple
operations insertion deletion etc.

Insert():

Which can be used to insert a new string or character at a given index value this
method can be used in 2 ways

Insert (into pos string)used to insert string value

Imnmsert (int pos, char value) used to insert character value

Ex :

StringBuffer sb= new StringBuffer(this is java class);

Sb.insert(7,new)==This is a new java class

Delete():

Which can be used to delete specific substring form given string this can be uised
in 2 ways

(a)delete (index) == which will delete a substring from the given main string
starting from the given index value to the last character

(b) delete (starting index,ending index);

Which can be used to delete a substring from the main string based on starting and
ending index value

Ex:

Sb.delete(4)==this

Sb.delete(46);==this is java class

Delete charAt():
Which is used to delete a specific character at given index value

Syntax:

deletecharAt(index);

sb.deletecharAt(5);==this is java class

Replace():

Which can be used to replace new string with old string based on index values

Replace(startingindex,endingindex,string);

Ex:

Sb.replace(8,11,html) this is html class

Sb.replace(8,11,android); this is android class

Append():

Which can be used to add substring value to the given string at the end

Sb.append(notes): This is java class notes

toString():

which can be used to convert string buffer value into string value, that means it is
converting from mutable format to immutable format.

Multithreading:

In general computer operations can perform various types of operations and these
operations can be performed in two different types

Single tasking
Multi tasking

Single tasking:

Whenever only one operation performing at a time is known as single tasking.


The main disadvantage in single tasking is time consuming process in more
to computing multiple operations. Because of these performance of
computer is reducing, to over come this disadvantage we can go for multi
tasking.

Multi tasking:

When ever multiple operations are performing simultaneously is known as


multitasking the main advantage with multitasking, time consuming process will
be reduced to perform various operations so that performance of computer will be
increased.

Multi tasking is classified into following types.


Process based multi tasking.
Thread based multi tasking

Process based multi tasking

Whenever multitasking is achieved by executing multiple programs simultaneously


is known as Process based multi tasking.

Ex:- playing of audio file, playing of game are simultaneously executed then that
may be treated as process based multi tasking.

Thread based multi tasking

Whenever multiple threads are executed simultaneously (or) a multiple parts of a


programs are executed simultaneously is known Thread based multi tasking.

In java language multiple threads are executed simultaneously so that we can


say java is multi threaded programming language.
Thread is a flow of execution (or) flow of control and it occupies less
memory space. So that it can be treated as light-weight component.
Language threads are classified into 2 types.
Foreground thread:- if any thread executed in java program known
as foreground thread and if any thread is executing in the form of
methods in a java program that can be treated as foreground thread.
Background thread:- if any thread is executing in background of a
java program is known as background thread.
The main advantage with multi threading is time taken for executing
program is reduced so that performance of a program will be increased.

Life cycle methods of thread:-

Every thread in the java program contains following lifecycle.

runnin
new ready dead
g

waiting

New state:- if any thread is created in java program with no memory allocation is
known as new state of thread.

Ready state:- whenever sufficient memory space is allocated for the thread then it
comes under ready state. That means the thread is now ready to execute.

Running state:- whenever the thread is currently in execution process known as


running state.

Waiting state:- if any thread is in waiting process known as waiting state of thread.

The thread can grow from waiting state to either ready (or) running state
based on requirement.

Dead state:- if the thread is terminated (or) stopped permanently known as dead
state of thread
Note:- whenever the thread is in either new (or) dead state no memory is
available and its remaining other states sufficient memory is allocated.

Creation of thread:-

In java language threads can be created in two different ways

By extending thread class.


By implementing runnable interface

Rules to create a thread class:-

Create a user defined class and extends either thread class (or) implements
runnable interface
Override run() of thread class in the user defined thread class by writing a
separate body part.

Note :- The statements which are written in the run method can be controlled by
the user to achieve simultaneous execution.

Syntax:-

Class<userdefined class> extends Thread (or) implements Runnable

Public void run()

--

--

--

Note:- Whenever a thread class is created by overriding run() then that is in new
state.
> Thread class doesnt have any main().
> Create an object for user defined thread class and pass that object as an
argumentin the predefined thread class.

Syntax:-

<userdefined class> obj=new <userdefined class>();

Thread t=new Thread(obi);

Note: If an object is created for thread class it comes to ready state

Execute run method by calling start method using thread class object.

t.start();

for the above statement run() if user defined thread class will be executed.

Thread class properties:-

Thread class contains predefined data members, constructors and methods, used to
perform various operations on thread.

Data members:-

Following data members used to give the properties to the thread at the time of
execution.

Public static final int MINI-PRIORITY=1;

This represents minimum priority of thread.

Public static final int NORM-PRIORITY=5;

Public static final int MAX-PRIORITY=10;

The default priority for any thread is 5(normal priority)

Constructors:-

Thread class mainly contains following constructors.


1) Thread():-

This can be used to give a default name for predefined thread.

Syntax:-

Thread t=new Thread();

By default the thread name will be starts from thread().

2) Thread(String):-

Thread t=new Thread(string value);

This can be used to provide a user defined name to predefined thread.

3) Thread(object):-

This can be used to provide a default name for the user defined thread.

Ex:- class A extends Thread

--

--

A oa=new A();

Thread t=new Thread(oa);

Thread (obj , string):-

This can be used to provide user defined names for user defined threads.

Class A extends Thread

--

--
}

A oa=new A();

Thread t=new Thread (oa, first);

Methods of thread class:-

Public final string getName():-

This can be used to retrieve the name of current thread.

Ex:- thread t=new thread();

Sop(t.getName());

Public final void setName():-

This can be used to set a user defined name to the thread.

Thread t=new Thread();

t.setName(new);

public final int getPriority();

it is the predefined method can be used to get priority of current thread.

t.getPriority();

public final void setPriority();-

it can be used to set priority to the threads

Thread t1=new Thread();

Thread t2=new Thread();

T1.setpriority(7);

T2.setPriority(thread.MAX-PRIORITY);

In the above example 7 is the priority is given to thread1, 10 is the priority is


given to thread2, and it is not possible to give more than 10 as a priority of thread.
Public final Boolean isAlive():-

It is a Boolean method returns true whenever thread is in either ready, running (or)
waiting state. And returns false if the thread is in either new(or)dead state.

Ex:- Thread t=new Thread();

t.isAlive();

public void run():-

if we want to execute any set of statements simultaneously n no.of times then


those statements must be declared in side the run()

syntax:-

class A extends thread

Public void run()

--

--

--

--

Public final void start():-

Which can be used to convert a thread from ready state to running state.

Syntax:- t.start();

Public static final void sleep():-


This can be used to convert a thread from running state to waiting state

Thread.sleep(millise());

Ex:-

Public void run()

--

--

--

Thread.sleep(3000);

--

--

--

A oa=new A();

Thread t=new Thread(oa);

t.start();

in the above example write execution of thread t sleep method means that thread
into waiting state for 3 sec of time once that is completed automatically thread will
enter into running state.

Public final void suspend():-

Which can be used to covert running state to waiting state but until and unless
we are notifying which will never return back to any other state.

t.suspend();

public final void resume():-


which can be used to make a thread from waiting state to ready state.

Ex:- t.resume();

Public final void stop():-

Which can be used to a running state thread into dead state.

Syntax:-

t.stop();

Public static final thrfead currentThread():-

This can be used to give the currently executed thread details and which contains 3
values.

> Thread group name


> Thread name
> Priority

Ex:- public static void main(string args[])

--

--

Sop(thread.currentThread());

Join():- it us a predefined method can be used to join more than thread.

Thread t1=new Thread();

Thread t2=new Thread();

Thread t3=new Thread();

T1.start();

T2.start();
T3.start();

T1.join();

T2.join();

T3.join();

Write a java program to execute multiple threads simultaneously?

Class Demo extends Thread

Public void run()

Int a=10, b=20,c;

C=a+b;

Try

Thread.sleep(3000);

Catch(InterruptedException ie)

Sop(Thread was Interrupted);

Sop(c=+c);

Class MCS

{
Public static void main(string args[])

Demo d=new Demo();

Thread t1=new Thread(d);

Thread t2=new Thread(d);

T1.start();

T2.start();

o/p:- javac MCS.java

java MCS

c=30

c=30

write a java program to display a user defined ,sg with time gap?

Class Mthread extends Thread

Int I;

Public void run()

Try

For(i=1;i<=10;i++)

{
Thread.sleep(2000);

Sop(hello);

Catch(InterruptedException ie)

Sop(ie);

Class Mclass

Public static void main (string args[])

Mthread m=new Mthread();

Thread t1=new Thread(m);

T1.start();

Sop(t1.isAlive());

o/p: javac Mclass.java

java Mclass

true

hello
hello

Hello (10 times)

Write a java program to describe thread class properties

Import java.lang.*;

Class Venu

Thread t1=new Thread();

Sop(Thread.currentThread());

Sop(t1.getName());

Sop(t1.getPriority());

Try

T1.setPriority(12);

Sop(t1.getpriority());

Catch(exception e)

Sop(priority of thread should be with in 10 only);

Sop(Thread.MIN_PRIORITY);

Sop(Thread.NORM_PRIORITY);
Sop(Thread.MAX_PRIORITY);

o/p:- javac Venu.java

java Venu

Thread[main,5,main]

Thread-0

Java Thread

Priority of thread should be with in 10 only

10

Write a java program execute multiple threads simultaneously

Class Th extends Thread

Int I;

String s1;

Th(string str)

S1=str;

Public void run()

{
For(i=1;i<=10;i++)

Sop(S1+i);

Try

Thread.sleep(1500);

Catch(InterruptedException ie)

Sop(problem in thread execution);

Class Tdemo

Public static void main(String args[])

Th to1=new Th(student);

Thread t1=new Thread(to1);

T1.start();

Th to2=new Th(plz sit in chair);

Thread t2=new thread(to2);


T2.sart();

o/p:-

statement 1

plz sit in chair1

Student 10

Plz sit in chair 2

Runnable interface:-

It is an alternative approach to create user defined thread class, runnable is a


predefined interface in java.lang package. Whenever it is implemented in any class
that becomes thread class.

Syntax:-

Class <classname> implements Runnable

Public void run()

--

--

}
Run() is an abstract method of runnable interface and that should be
overridden whenever it is implementing in any class.
If we want to create a thread by extending predefined thread class at that
time it is not possible to inherit other user defined classes in the user defined
thread class. To overcome this problem sun micro system was given
runnable interface as an alternative mechanism to create our own thread
classes to start run() we must follow below steps.
a) Create object for user defined thread class.
<classname> obj=new <classname>();
b) Create object for thread class and watch user defined class object.
Thread t=new Thread(obj);
c) Execute run() by calling start method
t.start();

write a java program to illustrate thread class and runnable interface

class th1 extends Thread

Int a,b;

Void set(int x, int y)

A=x;

B=y;

Public void run()

Int s=a+b;

Sop(sum in th1=+s);

}
}

Class th2 implements Runnable

Int x,y;

Void set(int x, int y)

This.x=x;

This.y=y;

Public void run()

Int z=x-y;

Sop(diff in th2=+z);

Class Thread4

Public static void main (string args[])

Int x=integer.parseInt(args[0]);

Int y=integer.parseInt(args[1]);

Int a=integer.parseInt(args[2]);

Int b=integer.parseInt(args[3]);
Th1=t11=new Th1();

T11.set(x,y);

Th2 t22=new Th2();

T22.set(a,b);

Thrtead t1=new Thread(t11);

Thread t2=new Thread(t22);

T1.start();

Sop(status of t1=+t1.isAlive());

T2.start();

Sop(status of t2+t2.isAlive());

Try

T1.join();

T2.join();

Catch(InterruptedException e)

Sop(problem in thread execution);

Sop(status of t1=+t1.isAlive());

Sop(status of t2=t2.isAlive());

}
o/p:- javac Thread4.java

java Thread4 20 5 30 7

sum in th1=25

status of t1=true

status of t2=true

diff in th2=23

status of t1=false

status of t2=false

Thread synchronization:-

Whenever same object is utilized by multiple threads simultaneously some times


which leads to getting irreable results in the program, to overcome this problem we
must synchronize the threads.

Def:- The process of restricting of a thread from the utilization of an object if that
object is utilized by other known as synchronization (or)thread safe.

In java language threads can be synchronized in two different ways using


synchronized block using synchronized method
If any thread is made as synchronized then which does not allows other
thread if that object is using by other thread currently. Because of these we
may not get irreable results even multiple threads are running
simultaneously.

Write a java program to illustrate thread synchronization using synchronized


block?

Class Reserve extends Thread/implement Runnable

Int av1=I,wanted;

Reserve (int x)
{

Wanted=x;

Public void run()

Synchronized(this)

Sop(Available berths =+available);

If(available>=wanted)

String name=thread.currentThread().getName();

Sop(wanted+berths reserved for+name);

Try

Thread.sleep(2000);

Available=available-wanted;

Catch(InterruptedException e)

Sop(Exception in thread);

Else
{

Sop(sorry no berths);

Class MultiThreadDemo

Public static void main (string args[]);

Reserve obj=new Reserve(1);

Thread t1=new Thread(obj);

Thread t2=new Thread(obj);

T1.setName (first person);

T2.setName(second person);

T1.start();

T2.start();

o/p:- javac multiThreadDemo.java

java MultiThreadDemo

available berths=1

1 berth reserve for first person


Available berths=o

Sorry no berths

Synchronized():

It is an alternative approach to make set of statements are synchronized, what ever


the statements are written inside synchronized method those will be executed by
the single thread at a time

Syntax:

Synchronized returntype methodname(lp/np)

-----

----

w.a .j.p to achive thread sychronizationusing synchronized method

class Accoutnt

Private int bal=0;

Synchronized void deposit(int amt)

Bal=bal+amt;

Try

Thread.sleep(2000);

System.out.println(current bal=+bal);
}

Catch(Exception e)

System.out.println(e);

}
}
int getbal()

Return(bal);

Class Cust extends Thread

Account ac;

Cust(Account ac)

This.ac=ac;

Public void run()

Ac.deposit(1000);

}
Class Synchronise

Publioc static void main(string args[])

Account ac new Account();

Cust cu[]=new Cust[5];

For(int i=0;i<5;i++)

Cu[i]=new Cust(ac);

For(int i=0;i<=5;i++)

Cu[i].join();

Catch(Interrupted Exception ie)

System.out.println(problem in thread execution);

}
System.out.println(Total balance+ac.getBalance());

o/p1:
Without Synchronized keyword

Current bal=5000;

Current bal=5000;

Current bal=5000;

Current bal=5000;

Current bal=5000;

Total balance=25000

o/p1:

With Synchronized keyword

Current bal=1000;

Current bal=2000;

Current bal=3000;

Current bal=4000;

Current bal=5000;

Total balance=15000