Académique Documents
Professionnel Documents
Culture Documents
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.
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
(or)
i Predifined execptions
ii User defined exception
Predefined exceptions:
Predefined Exception
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.
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
checkedException
runtimeException
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
This is an Exception raised when ever thwe given class is not available at the
Specicfic Location.
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.
Which is an exception raised whenever the given index value of an array out of
range.
A[0]=15;
This is an exception occour when ever the string index value is out of range
s.charat(1)=e;
H
E
L
L
: out of bounds 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;
This is an exception raised when ever the string value is mismatched data type
Ex: class A
Int x=Integer.parseInt(args[1]);
Java a helloin the above example it is not possible to convert direct string into
integer type.
This is an exception raised whenever the excepted method is not available in the
given program.
Example:
Class A
Void f1()
-----
------
Javac A.java
This is an exception raised whenever the expected data member is not available at
given location.
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.
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.
Syntax:
Try
-----
------
------
------
---
--
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;
X=s.nextInt();
Y=s.nextInt();
Try
Z=x/y;
System.out.println(z);
Catch(ArithmeticException ae)
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.
10 5
10 0
Import java.util.*;
Class Mexp
Int x,y,z;
X=s.nextInt();
Y=s.nextInt();
try
Z=x/y;
System.out.println(z);
int I;
I=s.nextInt();
a[i]=200;
System.out.println(a[+i+]+a[i]);
}
Catch(ArithmeticException ae)
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.
Syntax:
try
------
------
Catch(ExceptionClassname obj)
------
------
try
------
------
Catch(ExceptionClassname obj)
------
------
------
------
Import java.util.*;
Class MtryExp
try
{
String s =hello;
int I;
I=s.nextInt();
char c =s.charAt();
System.out.println(c=+c);
Catch(StringIndexOutOFBoundsException se)
try
int i1;
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:
Syntax:
finally
-----
-----
Import java.util.*;
Class NfExp
Int x,y,z;
X=Integer.parseInt(args[1]);
y=Integer.parseInt(args[2]);
z=x+y;
System.outprintln(z);
Finally
System.out.println(hello world);
o/p:javac NFexp.java
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.
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)
------------
--------
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
Synatx:
Try
-----
------
Catch(ArithmeticException ae)]
--------
--------
}
Catch(NumberFormatException nfe)
-------
-------
PrintStackTrace():
(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:
/ by zero-message of an exception
getMessage():
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():
Syntax:
-----
-----
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
Class Demo1
String s=hello;
Char c=s.charAt(1);
Syatem.out.println(c=+c);
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
Int x=Integer.parseInt(s1);
Int y=Integer.parseInt(s2);
Int z=x+y;
Sop(z=+z);
Class ThrowsDemo
Try
D1.f1();
D1.f2():
D2.f3();
Catch(StringIndexOutOfBoundsException e)
Catch(ArithmeticException ae)
Catch(NumberFormatException nfe)
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 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:
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.
Package package1,package2
Desine user defined class either by extending Exception class (or) runtime
Exception class
--------------------
Classname(string var)
---------------
------------
In the above syntax string variable can be used to hold the common Exception
message
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
A(string str)
Nage.java
Package a
Super(str);
AgeCheck.java
Package chk
Import na.Nage
Int age=Integer.parseInt(s[])
If(age<0)
{
Throw(na);
Else
Sop(invalid age);
Finalage.java
Import chk.agecheck;
Import na.Nage
Class FinalAge
Psvm(string args[])
Try
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
Valid age
Java finalage-20
Throw:
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:
------
------
Throw(exceptionclass object)
Q:
If one exception throwing to some location indirectly from different other location
called rethrowing of an exception
Example:
Polymorphism:
Definition:
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 .
(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()
------
------
------
-----
------
-----
------
-----
Class A
{
Void f1();
System.out.println(hello f1());
Void f1(int a)
Void f1(char c)
Class M
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
Syntax:
Class <classname>
{
Return type 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()
}
}
Class B
Void f1()
Class over1
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
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;
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;
System.out.println(a=+a);
System.out.println(b=+b);
Class Over2
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
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:
------------
------------------
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
Note:
Static rt methodname(lp/np)
{ method body
-----
classnamee.method name(var1,var2)
------
Static methods can be overloaded similar to non static methods and its scope is
only with in the class
Syntax:
-------------
-------------
-----
-----
Class A
System.out.println(hello f1());
Class Sa
{
A.f1();
A.f1(12);
Note:
Static methods base class cant be overridden non static methods of derived class
Note:
STRING HANDLING:
String class:
Syntax:
String varname=value;
(or)
Length():
Ex:
String s1=hello
S1.length():----5(number of characters)
s.length():------7(number of characters)
charAt():
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():
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)
Else
{
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);
EqualsIgnoreCase():
Syntax: s1.equalsIgnoreCase(s2);
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
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 )
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
Ex:s6.substring(6);===friend
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)
Ex:
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:
Ex:split(.,:);
Because of above syntax the main string will be devided into n number of parts
when ever it founds either .(or),(or):
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
Ex :
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
Which can be used to delete a substring from the main string based on starting and
ending index value
Ex:
Sb.delete(4)==this
Delete charAt():
Which is used to delete a specific character at given index value
Syntax:
deletecharAt(index);
Replace():
Which can be used to replace new string with old string based on index values
Replace(startingindex,endingindex,string);
Ex:
Append():
Which can be used to add substring value to the given string at the end
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:
Multi tasking:
Ex:- playing of audio file, playing of game are simultaneously executed then that
may be treated as process based multi tasking.
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.
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:-
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:-
--
--
--
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:-
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 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.
Constructors:-
Syntax:-
2) Thread(String):-
3) Thread(object):-
This can be used to provide a default name for the user defined thread.
--
--
A oa=new A();
This can be used to provide user defined names for user defined threads.
--
--
}
A oa=new A();
Sop(t.getName());
t.setName(new);
t.getPriority();
T1.setpriority(7);
T2.setPriority(thread.MAX-PRIORITY);
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.
t.isAlive();
syntax:-
--
--
--
--
Which can be used to convert a thread from ready state to running state.
Syntax:- t.start();
Thread.sleep(millise());
Ex:-
--
--
--
Thread.sleep(3000);
--
--
--
A oa=new A();
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.
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();
Ex:- t.resume();
Syntax:-
t.stop();
This can be used to give the currently executed thread details and which contains 3
values.
--
--
Sop(thread.currentThread());
T1.start();
T2.start();
T3.start();
T1.join();
T2.join();
T3.join();
C=a+b;
Try
Thread.sleep(3000);
Catch(InterruptedException ie)
Sop(c=+c);
Class MCS
{
Public static void main(string args[])
T1.start();
T2.start();
java MCS
c=30
c=30
write a java program to display a user defined ,sg with time gap?
Int I;
Try
For(i=1;i<=10;i++)
{
Thread.sleep(2000);
Sop(hello);
Catch(InterruptedException ie)
Sop(ie);
Class Mclass
T1.start();
Sop(t1.isAlive());
java Mclass
true
hello
hello
Import java.lang.*;
Class Venu
Sop(Thread.currentThread());
Sop(t1.getName());
Sop(t1.getPriority());
Try
T1.setPriority(12);
Sop(t1.getpriority());
Catch(exception e)
Sop(Thread.MIN_PRIORITY);
Sop(Thread.NORM_PRIORITY);
Sop(Thread.MAX_PRIORITY);
java Venu
Thread[main,5,main]
Thread-0
Java Thread
10
Int I;
String s1;
Th(string str)
S1=str;
{
For(i=1;i<=10;i++)
Sop(S1+i);
Try
Thread.sleep(1500);
Catch(InterruptedException ie)
Class Tdemo
Th to1=new Th(student);
T1.start();
o/p:-
statement 1
Student 10
Runnable interface:-
Syntax:-
--
--
}
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();
Int a,b;
A=x;
B=y;
Int s=a+b;
Sop(sum in th1=+s);
}
}
Int x,y;
This.x=x;
This.y=y;
Int z=x-y;
Sop(diff in th2=+z);
Class Thread4
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);
T22.set(a,b);
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(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:-
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.
Int av1=I,wanted;
Reserve (int x)
{
Wanted=x;
Synchronized(this)
If(available>=wanted)
String name=thread.currentThread().getName();
Try
Thread.sleep(2000);
Available=available-wanted;
Catch(InterruptedException e)
Sop(Exception in thread);
Else
{
Sop(sorry no berths);
Class MultiThreadDemo
T2.setName(second person);
T1.start();
T2.start();
java MultiThreadDemo
available berths=1
Sorry no berths
Synchronized():
Syntax:
-----
----
class Accoutnt
Bal=bal+amt;
Try
Thread.sleep(2000);
System.out.println(current bal=+bal);
}
Catch(Exception e)
System.out.println(e);
}
}
int getbal()
Return(bal);
Account ac;
Cust(Account ac)
This.ac=ac;
Ac.deposit(1000);
}
Class Synchronise
For(int i=0;i<5;i++)
Cu[i]=new Cust(ac);
For(int i=0;i<=5;i++)
Cu[i].join();
}
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:
Current bal=1000;
Current bal=2000;
Current bal=3000;
Current bal=4000;
Current bal=5000;
Total balance=15000