Fundamentals
-------------------------------------------------------------------------------------------------------------------
DataTypes Identifiers Literals JavaKeyords
Variable Arrays Operators TypeCasting
FlowControl Coding Standards StaticImports mainMethod,args
Access specifiers var-argMethod AbstructClass GarbageCollection
InnerClass Interface Assertions
java.lang
-------------------------------------------------------------------------------------------------------------------
Class,Object Classes System String StringBuffer,StringBuilder
Cloneable,Comparable Wrapper Classes Math,Number Autoboxing,Autounboxing
Enum
OOPS
-------------------------------------------------------------------------------------------------------------------
class,object Encapsulation Abstraction Inheritance
Method Overloading Method Overridings Constructors Message Passing
Collections
-------------------------------------------------------------------------------------------------------------------
All List Classes All Set Classes All Map Classes Collections Class
Calendar,Date GregorianCalendar StringTokenizer Timer,TimerTask
Exceptions
-------------------------------------------------------------------------------------------------------------------
DefaultException Checked,UnChecked try,catch,finally throw , throws
Handler
Threads
-------------------------------------------------------------------------------------------------------------------
Thread Creation Thread Class Methods Synchronization wait,notify,notifyAll
Daemon Threads Thread group Thread Deadlock
java.io
-------------------------------------------------------------------------------------------------------------------
File All Reader Classes All Writer Classes InputStream Classes
OutputStream Classes Serialization
Tuesday, April 7, 2009
Monday, January 12, 2009
Threads
Multitasking:
- Executing several tasks simultaneously is the concept of Multitasking.
- The main objective of multitasking is to decrease response time of the system, so that the performance of the system will increase.
- Executing several tasks simultaneously where each task is a independent program.
- Example typing a java program in the Editor, playing MP3 player, Downloading a file from the internet
- All the tasks are independent of each other and executes simultaneously.
- This type of multitasking is useful at OS level.
- CGI fallows process based multitasking.
Thread Based Multitasking:-
- Executing several tasks simultaneously, where each task is a separate inependent part of the same program. That independent part is called the Thread.
- Servlets fallowThread Based MultiTasking.
- Java itself provide support for multithreading by introducing several library classes.
- We can use in games/animation programme.
- Creating a thread in two ways.
- By extending Thread
- By implementing Thread
- Methods used to prevent a thread from execution
- Synchronization
- InterThread communication (wait, notify, notifyAll)
Defining, Instantiating and starting Thread by extending Thread class:
class MyThread extends Thread
{
public void run()
{
System.out.println(“My job”);
}
}
- Here run method is the heart of thread where you have to define the job.
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start(); //starting a thread
System.out.println(“Main thread job”);
}
}
Ex:
class MyThread extends Thread
{
for(int i=0;i<10;i++) t="new" i="0;i<10;i++)" style="font-weight: bold;">1. Difference between t.start() & t.run()?
• If we call t.start(), it will create a new Thread and that thread is responsible for execution of run().
• If we call t.run(), mo new thread will create, the main thread only will execute run(), just like a normal method.
Thread class start():-
public void start()
{
1. Registering our thread with the thread scheduler then only thread scheduler allocate CPU and memory type of resources for this new thread also.
2. calls run()
}
public void start()
{
System.out.println(“start method”);// start method 1 time, main thread 10 times
}
public void start()
{
super.start();
System.out.println(“start method”);// start method child & main thread alternatively
}
class MyThread extends Thread
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
}
}
• Thread class run() has empty implementation that’s why we are getting no o/p.
Thread life cycle

{
public void run()
{
System.out.println(“run”);
}
}
class ThreadDemo
{
public static void main(String a[])
{
MyThread t= new MyThread();
Thread t1=new Thread(t);
t1.start();
// t1.run(); ----> It is just like a method no new thread will create
}
}
Ex:
class MyRunnable implemts Runnable
{
public void run()
{
for(int i=0;i<10;i++) r="new" t="new"> Target Runnable
for(int i=0;i<10;i++) style="font-weight: bold;">Thread class Constructors:
1. Thread();
2. Thread(Runnable r);
3. Thread(String name);
4. Thread(Runnable r, String name);
5. Thread(ThreadGroup g, String name);
6. Thread(ThreadGroup g, Runnable r);
7. Thread(ThreadGroup g, Runnable r, String name);
Ex:- // Test king
class MyThread extends Thread
{
public void run()
{
System.out.println(“run”);
}
}
class ThreadDemo
{
public static void main(String a[])
{
MyThread t= new MyThread();
Thread t1=new Thread(t);
t1.start();
// t1.run(); ----> It is just like a method no new thread will create
}
}
Setting & getting the name of a thread:
Thread class contain the fallowing methods for setting & getting the name of the Threads..
- public final String getName();
- public final void setName(String s);
• Thread class contains the fallowing methods for setting and getting priority of a thread.
- public final int getPriority();
- public final void setPriority(int i);
• Thread class contains the fallowing predefined priority constraints.
MAX-PRIORITY ---> 10
NORM-PRIORITY --->5 (default)
MIN-PRIORITY ---->10
• If you are trying to set the priority as greater than 10 or lessthan1, then we will get a RTE saying “Illegal Argument Exception”
class MyThread extends Thread
{}
class Sample
{
public static void main(String a[])
{
Thread.currentThread().setPriority(10);
System.out.println(Thread.currentThread().getPriority());
MyThread t= new MyThread();
System.out.println(t.getPriority());//10 10
}
}
• The default priority for the maintained is 5. But we are allowed to change the prority by using setPriority()
• The priority of any the thread is inherited from the parent thread.
• Thread scheduler uses these proroites to allocate CPU. The thread which is having highest priority will get executes first.
t.setPriority(10);
Yield() :
• We can prevent a thread from execution by using one of the fallowing methods.
1. yield()
2. join()
3. sleep()
• The thread which is executing yield() causes the current thread temperarly pause and allow other waiting threads of same or high priority to execute.
• If there is no waiting thread, the same thread will execute immediately.
• If all the remaining threads are having low priority, then the same thread once again will execute.
Method Signature:-
public static native yield();
MyThread t= new MyThread
• If the thread calls yield(), the thread going to ready state.
Ex:
Class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++) t =" new" i="0;i<10;i++);" style="font-weight: bold;">Join():
public final void join() throws InterruptedException
public final void join(long ms)throws InterruptedException
public final void join(long ms, int nanosec)throws InterruptedException
MyThread t= new MyThread
Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++) t="new" i="0;i<10;i++);" style="font-weight: bold;">sleep():-
• The thread which is executing sleep() will go to the sleep for the specified amount of time.
MethodSignature:
public static void sleep(long ms) throws InterruptedException
public static void sleep(long ms, int nanoseconds)throws InterruptedException
MyThread t= new MyThread
Ex:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++) t="new" style="font-weight: bold;">Ex: class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++) t="new" style="font-weight: bold;">Synchronization:
- The keyword synchronized can be apply only for methods and blocks. Ie., We can’t apply synchronized keyword for the classes and variables.
- If a method (or block) declared as the synchronized at a time only one thread is allowed to execute that synchronized area on any given object.
- Advantage: Prevent data corruption, achieve security.
- Limitation: Because of synchronized keyword 2 threads are not allowed to execute concurrently on any object, hence the waiting time of the threads will increase, which results in low performance of the system.
- A class can contain both synchronized and non synchronized methods.
- If a thread calls synchronized method on any object, first this thread got the lock, it is allowed to any synchronized method on that object.
- If a thread executing any synchronized method on the given object at that time no other thread is allowed to execute any synchronized method on that object.
- If a thread executing any synchronized method the remaining threads are allowed simultaneously to execute nay non synchronized method on that object.
- Every Object in java has a lock. At the time of synchronization only the lock concept will conme into the picture.
Ex:-
class Display
{
public void show(String name)
{
for(int i=0;i<10;i++) d="d;" name="name;" d="new" t1="new" t2="new" style="font-weight: bold;">Class Level lock:
- If you want to execute any static synchronized method, first the thread should required a class level lock.
- If a thread has class level lock, it is allowed to execute any stock synchronized method. During that time no other thread is allowed to execute any static synchronized method. But the remaining threads are allowed to execute any static non synchronized methods of the same class.
Constructors
Constructors:
The purpose of Constructor is to perform of our creted object. Whenever we are calling new operator for the creation of object, it calls constructor automatically to provide initialization for the object.
class Student
{
String name; int rno;
Student(String name, int rno) ----> Constructor
{
this.name=name;
this.rno=rno;
}
public static void main(String a[])
{
Student s=new Student(“xxx”,101);
Student s1=new Student(“yyy”,102);
-------
------
}
}
Rules Of Constructor :
1. Constructor concept is applicable for every class including abstract class also.
2. Interface doesn’t have Constructor’s concept.
3. The name of the const4ructor and the name of the class must be same.
4. The allowed modifiers for the constructors are public, private, protected, and default. If you are applying any other we will get a CTE saying “modifier xxx not allowed her”.
5. We can’t give return type for the constructor even void also.
If we will give return type for the constructor that thing as a method instead of constructor that thing as a method instead of constructor (so,there is no CTE). Ie., it is legal (but stupid) to have a method whose name same as classname.
Default Constructor:-
If the programmer is not writing any constructor, then only compiler will generate a default constructor.
Ie., either programmer written constructor or compiler generated must present in your class but not both at a time.
Prototype of default constructor:
a). Programmer written code:- class Test{}
Compiler generated code:-
class Test
{
Test()
{
Super();
}
` }
b) Programmer written code:- class Test{ Test(int i){ System.out.println(“constructor”);}}
Compiler generated code:- class Test{Test(int i){Super();System.out.println(“constructor”);}}
c). Programmer written code:-
class Test
{
Test(int i)
{
super();
System.out.println(“Hai”);
}
}
Compiler generated code:- no new code is going to generate.
d). Programmer written code:-
class Test
{
void Test()
{
System.out.println(“hello”);
}
}
Compiler generated code:-
class Test
{
void Test()
{
System.out.println(“hello”);
}
Test()
{
super();
}
}
e). Programmer written code:-
class Test
{
Test()
{
this(10);
S.o.p(“hai”);
}
Test(int i)
{
S.o.p(i);
}
}
Compiler generated code:-
class Test
{
Test()
{
this(10);
S.o.p(“hai”);
}
Test(int i)
{
super();
S.o.p(i);
}
}
1. Allowed only in Constructors.
2. Must be first statements.
3.Either super() or this, but not both.
8. Overloaded Constructors:
{
Test(int i){}
Test(){} ---->Overloaded Constructors
}
9. Constructors are not inherited and hence we are not allowed to override a constructor.
10. Recursive method invocation.
class Sample
{
public void m1()
{
M2();
}
public staticvoid main(String[] a)
{
Sample s= new Sample();
System.out.println(“hai”);
s.m1(); //RTE: StackOverflowError
}
}
This is a RunTime problem, never be a CTE..
Recursive Constructor invocation:
class Sample
{
Sample() // This is a compile time problem
{
this(10);
}
Sample(int i)
{
this(); // Invalid, CTE: recursive constructor invocation
}
public static void main(String a[])
{
System.out.println(“hai”);
}
}
11. Constructing the Child class constructors:
class P
{
P()
{ super(); }
}
class C extends P
{
C(){ super(); }
} //valid
---> class P
{
P(int i)
{
System.out.println(i);
}
}
class C extends P
{
C()
{
super(10); // valid (without super invalid)
}
}
12. class P
{
P() throws Exception ----> checked exception
{ }
}
class C extends P
{
C()
{ }
}
//throws Exception ,without this //CTE: Unchecked Exception , can’t handled using try – catch
But
class P
{
P() throws ArithmeticException ---> unchecked
{}
class C extends P
{
C(){} ----> valid
}
}
The purpose of Constructor is to perform of our creted object. Whenever we are calling new operator for the creation of object, it calls constructor automatically to provide initialization for the object.
class Student
{
String name; int rno;
Student(String name, int rno) ----> Constructor
{
this.name=name;
this.rno=rno;
}
public static void main(String a[])
{
Student s=new Student(“xxx”,101);
Student s1=new Student(“yyy”,102);
-------
------
}
}
Rules Of Constructor :
1. Constructor concept is applicable for every class including abstract class also.
2. Interface doesn’t have Constructor’s concept.
3. The name of the const4ructor and the name of the class must be same.
4. The allowed modifiers for the constructors are public, private, protected, and default. If you are applying any other we will get a CTE saying “modifier xxx not allowed her”.
5. We can’t give return type for the constructor even void also.
If we will give return type for the constructor that thing as a method instead of constructor that thing as a method instead of constructor (so,there is no CTE). Ie., it is legal (but stupid) to have a method whose name same as classname.
Default Constructor:-
If the programmer is not writing any constructor, then only compiler will generate a default constructor.
Ie., either programmer written constructor or compiler generated must present in your class but not both at a time.
Prototype of default constructor:
a). Programmer written code:- class Test{}
Compiler generated code:-
class Test
{
Test()
{
Super();
}
` }
- The default constructor is always no argument constructor.
- The access modifier of the default constructor is sane as access modifier of the class (public & default only).
- The default constructor contains only one statement which is ‘no arg call to super class Constructor ‘ (super();)
b) Programmer written code:- class Test{ Test(int i){ System.out.println(“constructor”);}}
Compiler generated code:- class Test{Test(int i){Super();System.out.println(“constructor”);}}
c). Programmer written code:-
class Test
{
Test(int i)
{
super();
System.out.println(“Hai”);
}
}
Compiler generated code:- no new code is going to generate.
d). Programmer written code:-
class Test
{
void Test()
{
System.out.println(“hello”);
}
}
Compiler generated code:-
class Test
{
void Test()
{
System.out.println(“hello”);
}
Test()
{
super();
}
}
e). Programmer written code:-
class Test
{
Test()
{
this(10);
S.o.p(“hai”);
}
Test(int i)
{
S.o.p(i);
}
}
Compiler generated code:-
class Test
{
Test()
{
this(10);
S.o.p(“hai”);
}
Test(int i)
{
super();
S.o.p(i);
}
}
- The first line inside a constructor must be a call to super class constructor ( by using super();) or a call to overload constructor of the same class. (by using ‘this’ keyword).
- If you are not writing the first line as either ‘super()’ or ‘this’ then compiler will always keep a no arg call to super class constructor (super();).
1. Allowed only in Constructors.
2. Must be first statements.
3.Either super() or this, but not both.
- We can invoke another constructor from constructor from a method violation leads to CTE. i.e, super() or this must be used inside the constructor only not anywhere else.
8. Overloaded Constructors:
- We are allowed to keep more than one constructor inside a class , which are considered as overloaded constructors. We can’t override the constructors, because they belong to the same class.
{
Test(int i){}
Test(){} ---->Overloaded Constructors
}
9. Constructors are not inherited and hence we are not allowed to override a constructor.
10. Recursive method invocation.
class Sample
{
public void m1()
{
M2();
}
public staticvoid main(String[] a)
{
Sample s= new Sample();
System.out.println(“hai”);
s.m1(); //RTE: StackOverflowError
}
}
This is a RunTime problem, never be a CTE..
Recursive Constructor invocation:
class Sample
{
Sample() // This is a compile time problem
{
this(10);
}
Sample(int i)
{
this(); // Invalid, CTE: recursive constructor invocation
}
public static void main(String a[])
{
System.out.println(“hai”);
}
}
11. Constructing the Child class constructors:
class P
{
P()
{ super(); }
}
class C extends P
{
C(){ super(); }
} //valid
---> class P
{
P(int i)
{
System.out.println(i);
}
}
class C extends P
{
C()
{
super(10); // valid (without super invalid)
}
}
12. class P
{
P() throws Exception ----> checked exception
{ }
}
class C extends P
{
C()
{ }
}
//throws Exception ,without this //CTE: Unchecked Exception , can’t handled using try – catch
But
class P
{
P() throws ArithmeticException ---> unchecked
{}
class C extends P
{
C(){} ----> valid
}
}
- If we are writing any constructor in our class it is recommended to place default constructor also. Otherwise we should take care while writing the constructor child case.
- If the parent class constructor throws some Checked Exception, while writing child class constructors we should take care.
exceptions
java Exceptions:
• An Exception is an abnormal and unexpected and also unwanted event that disturbs the normal flow of the program.
Ex: FileNotFoundException
ArithmaticException etc..
Default Exception Handling Mechanism in JAVA:
class Sample
{
public static void main(String a[])
{
doStuff();
}
public static void doStuff()
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
System.out.println(10/0);
}
}
Output: hai
RTE: Exception in thread “main” Java.Lang.Arithematic Exception: /by zero
At Sample . doMoreStuff(Sample.java)
At Sample . doStuff(Sample.java:9)
At sample . main(Sample. java :5)
• If an exception is raised inside any method is r3esponsible for the creation of exception object. (here doMoreStuff() is responsible )
• The Exception object must contain the fallowing information.
1. Name of the Exception(Java.Lang.ArithematicException)
2. Description of the Exception (/ by zero)
3. The position at which the exception raised. (stack trace).
• Now the method handover that exception object to the JVM. JVM will come with that exception object and it will check, is there any exception object and it will check is there any exception handler inside that method abnormally and removes the corresponding entry from the stack.
• Now the method handover that exception object to the JVM. JVM will come with that exception object and it will check, is that any exception handler inside that method. If there is no exception handler then JVM blindly terminate that method abnormally and removes the corresponding entry from the stack.
• JVM will check for the caller(doStuff()) containing any exception handling code. If the caller also doesn’t contain any exception handling code, then JVM simply terminate that method also and remove the corresponding entry from the stack.
• This process will continue, until main() method. If the main() also doesn’t have any exception handling code then JVM terminates main() abnormally and handover the responsibility of the exception handling to default exception handler.
• Now Default Exception handler print the exception information to the end user
Checked vs Unchecked Exceptions :
• The Exceptions which are checked by the compiler for smooth execution of program at Runtime are called checked Exceptions.
• The Exceptions which are unable to check by the compiler are called Unchecked Exceptions.
• Runtime Exception and its child classes: Error and its child classes are Unchecked Exceptions. While the remaining all are Unchecked Exceptions.
Partially Checked vs Fully Checked :
A Checked Exception is said to be Fully Checked Exception if and only if all its child classes are also checked. Otherwise it is Partially Checked Exception.
Ex: IOException is Fully Checked Exception
Exception is Partially Checked
Throwable is Partially Checked
We can handle exceptions by using the fallowing keywords.
1). try 2). catch 3). Finally
4). throw 5). throws
try
{
//Risky code
}
catch(XException e)
{
//Define the handler
}
Ex:
try
{
System.out.println(10/0);
}
catch(ArithematicException e)
{
System.out.println(“caught”);
System.out.println(10/2);
}
System.out.println(“hello”);
output:
caught
5
hello
try
{
Statement 1;
Stmt 2;
Stmt 3;
}
catch(XException e){ Statement 4; }
stmt5;
Case 1:- If there is no Exception ->1,2,3,5 are executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block found then 1 fallowed 4,5 are executes. So, normal termination.
Case 3:- If an Exception is raised at stmt2, but the corresponding catch block not found. Then stmt1 fallowed by abnormal termination.
Case 4:- If an Exception raised at stmt2 and the corresponding catch block found; but while executing catch block raises another Execution then stmt1 fallowed by abnormal termination.
Methods For Displaying Error Information :
The class Throwable contains the fallowing methods for displaying Error information.
1. printStackTrace():
Name of the Exception: Description of Exception Stack trace.
catch(ArithmaticException e)
{
e.printStackTrace();
}
System.out.println(“hai..”);
output:
java.lang.ArithmaticException: /by zero at sample.main(Sample.java)
Hai
2. public String toString():
Name of the Exception: Description of Exception
catch(ArithmaticException e)
{
System.out.println(e.toString());
}
System.out.println(“hai..”);
output:
java.lang.ArithmaticException: /by zero
Hai
3. public String getMessage():
Description of Exception
catch(ArithmaticException e)
{
System.out.println(e.getMessage());
}
System.out.println(“hai..”);
output: /by zero
hai
Try with Multiple catch blocks:
• The way of handling the exception is varied from exception to exception, hence it is a good programming practice to keep separate catch block for every exception.
try
{
System.out.println(10/0);
}
catch(ArithmeticException e) //child
{
//code
}
catch(Exception e) //parent
{
//code
}
Valid since child --> parent
try
{
System.out.println(10/0);
}
catch(Exception e) //parent
{
//code
}
catch(ArithmeticException e) //child
{
//code
}
InValid since parent ----> child
compile time error(CTE) : Exception has already been caught by catch (ArithmeticException e)
• If multiple catch blocks are defined for the try statement, the order of the catch blocks is important. We should take the catch blocks from child to parent, violation leads to CTE saying “Exception” has already been caught”.
Control Flow in try with multiple catch blocks:
try
{
Statement 1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
catch(YException e1)
{
Stmt 5;
}
Stmt6;
Case 1:- If there is no Exception ->1,2,3,6 is executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block(Y Exception e1) is matches then 1,5,6 are executes. So, normal termination.
Case 3:- If an Exception is raised at stmt2, but the corresponding catch block not found. Then stmt1 fallowed by abnormal termination.
Control Flow in Nested try catch :
try
{
Statement 1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
}
catch(XException e)
{
Stmt7;
}
Stmt8;
}
catch(YException e)
{
Stmt9;
}
Stmt10;
Case 1:- If there is no Exception ->1, 2, and 3,4,5,6,8,10 is executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block is matches then 1,9,10 are executes. So, normal termination.
Case 3:- If an Exception raised at stmt2 and the corresponding catch block not found. 1 fallowed by abnormal termination.
Case 4:- If an Exception raised at stmt5 and the corresponding catch block is matches then 1,2,3,4,7,10 and Normal Termination.
Case 5:- If an Exception raised at stmt5 and the corresponding catch block is not matched but outer catch block has matched 1,2,3,4,9,10 and Normal Termination.
Case 6:- An Exception raised at stmt2 and the corresponding catch block has matched but while executing that catch block another exception raised then fallowed by abnormal termination.
Case 7:- An Exception raised at stmt8 and the corresponding catch block has matched then 1,2,3,9,10 fallowed by Normal Termination. If the catch block has not matched abnormal termination.
finally block:
try
{
System.out.println(10/0);
}
catch(AE e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“catch”);
}
• The cleanup code, we have to keep inside finally block because irrespective of exception occurred or not occurred or handled or not handled, the finally block will always execute.
Q: Difference between final, finally and finalize?
• It is highly recommended to keep cleanup code inside finally block instead of finalize().
• The finally block will always execute except the place where the JVM got shutdown. We can shutdown the JVM by calling /using System.exit(0).
Ex:
try
{
System.out.println(“hai”);
}
catch( NULL pointer exception e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“finally”);
}
output:
hai
finally
Q). 1. try{} catch(X e){} -->valid
2. try{}catch(X e){}finally{} -->valid
3. try{}finally{}catch(X e){} --> invalid
4. try{}finally{} -->valid
Ie., try --> catch --> finally is the only order.
Only try{} --->invalid,
Only catch{} ----> invalid
Only finally{} ---->invalid
Note: try without catch & catch with out try invalid
Ex:
catch(..){}
finally{}
CTE: catch with out try
Control Flow in try, catch, finally block :
try
{
Stmt1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
finally
{
Stmt 5;
}
Stmt 6;
Case 1:- If there is no exception then 1,2,3,5,6 and normal termination.
Case 2:- If an exception raised at stmt2 and the corresponding catch block found 1,4,5,6 and normal termination.
Case 3:- If an exception raised at stmt2 and the corresponding catch block not matched 1,5 and abnormal termination.
Control Floe in the Nested try, catch, finally blocks:
try
{
Stmt1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
catch(XException e)
{
Stmt 7;
}
finally
{
Stmt 8;
}
Stmt 9;
}
catch(YException e)
{
Stmt 10;
}
finally
{
Stmt 11;
}
Stmt 12;
Case 1: If there is no exception 1,2,3,4,5,6,8,9,11,12 and normal termination.
Case 2: If an exception raised at stmt 2 and the corresponding catch block found then 1,10,11,12 and normal termination.
Case 3: If an exception raised at stmt2 and the corresponding catch block has not matched then 1,11 and abnormal termination.
Case 4: If an exception raised at stmt5 and the corresponding catch block has matched then 1,2,3,4,7,8,9,11,12 and normal termination.
Case 5: If an exception raised at stmt5 and the corresponding catch block has not matched but the outer catch has matched then 1,2,3,4,8,10,11,12 and normal termination.
Case 6: If an exception raised at stmt5 but the inner and outer catch blocks are not matched then 1,2,3,4,8,11 and abnormal termination.
‘Throw’ keyword:
public static void main(String a[])
{
try
{
Throw new AithmeticException()
}
}
By using ‘throw ‘ keyword, over created customized exception objects are handed over to JVM.
Ex:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any stmt, violation leads to CTE saying “unreachable statement”.
Ex:
class Sample
{
static ArithmeticException e;
public static void main(String[] a)
{
throw e; //invalid
}
}
output: NullPointerException
‘e’(is in instance area) is not pointing “ArithmeticException’ here.
static ArithmeticException e=new ArithmeticException();
Ex:
class Sample
{
public static void main(String a[])
{
Throw new Exception(); //invalid
}
}//CTE: “Unreported Exception Java.lang.Exception must be caught” or declared to be thrown.
• Inside a program if there is any chance of throwing a checked exception explicitly or implicitly we have to handle that checked exception by using try - catch or we have to delegate the responsibility or exception handling to the caller. Violation leads to CTE saying Unreported Exception xxx; must be caught or declared to be thrown.
“throws” Keyword :
Ex:
class Sample
{
public static void main(String a[])throws InteruptedException
{
doStuff();
}
public static void doStuff()throws IE
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
Thread.sleep(1000);
}
}
without ‘throws’ CTE: Unreported Exception java.lang.interuptedException ; must be caught or declared to be thrown. To avoid CTE another way in using try ---> catch block.
Ex:
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(ArithmaticException e){}-->no CTE
}
}
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(IOException e){} --->CTE (fullychecked exception)
}
}
CTE: exception java.io.IOException is never thrown in the body of the corresponding try statement.
We can ‘throws’ keyword for delegating the responsibility of the Exception handling to the caller.
If we are keeping the catch block for fully checked exception there should may be a chance of raising exception in the corresponding try block otherwise CTE saying XXXException is never thrown in the body of corresponding try statement.
Case 1: try
{
System.out.println(“hai”);
}
catch(ArithematicException e) //valid no CTE
{ //unchecked exception }
Case 2: try
{
System.out.println(“hai”);
}
catch(Exception e) //valid no CTE
{ //Partially checked exception }
Case 3: try
{
System.out.println(“hello”);
}
catch(IOException e) //invalid CTE
{ // fully checked exception }
Customized Exceptions :
Based on the programming required sometimes we have to design our own Customized Exceptions.
Ex: Insufficient funds Exception
too young Exception
too old Exception
class TooYoungException extends RunTimeException
{
TooYoungException(String s)
{
super(s);
}
Class Sample
{
public static void main(String a[])
{
Int i=Integer.parseInt(arg[0]);
If(i>85)
throw new TooYoungException(“please wait some more time, you eill get married”);
else if(i<10)
throw new TooYoungException(“ur age is already crossed”);
else
throw new TooYoungException(“very soon you will get match”);
}
}
CommonExceptions and Errors:
Exceptions or errors may be thrown by either JVM(JVM Exceptions) or thrown explicitly by application developers or API programmers(programmatic exception).
1. NULLPOINTER EXCEPTION:
Class Sample
{
Static int[] a;
Static String name;
public static void main(String a[])
{
System.out.println(a.length);
}
}
System.out.println(a[o]); // null pointer exception (NPE)
System.out.println(name.length); //NPE
This is child class of RuntimeException. It is unchecked exception.
This is thrown by JVM when attempting to acess an object with a reference variable whose current value is null.
Ie., on null if we are applying any operation we will get NullPointerException.
2. STACK OVERFLOW ERROR:-
• This is child class of virtual machine error.
• It is unchecked
Throwable ----> Error ---> VMError ---> StackOverFlowError
class Sample
{
public static void m1()
{
m1();
}
public static void main(String a[]){ m1(); } // stack overflow error
}
StackOverflow error is thrown by JVM when a method recurses too deeply.
class Sample
{
Sample() { new Sample(); }
public static void main(String a[]) { Sample s= new Sample(); }//Exception in main thread stack overflow error
}
3. ARRAY INDEXOUTOF BOUNDS EXCEPTION:
• This is a child class of IndexOutOfBoundsExcption.
Throwable ---> Exception ---> RunTimeException ----> IndexOutOfBoundsException---> ArrayIndexOutOfBoundsException, StingIndexOutOfBoundsException
• It is an unchecked exception thrown by JVM when we are accessing an array element with
Invalid index.
Ex:
class Sample
{
public static void main(String a[])
{
Int[] a=new int[6];
System.out.println(a[5]); //0
System.out.println(a[7]); //RTE: ArrayIndexOutOfException
System.out.println(a[-2]); //----do----
System.out.println(a[-2.5]); //CTE: PLP req: int found:double
}
}
4. CLASS CAST EXCEPTION:
Class Sample
{
public static void main(String a[]))
{
String s=”anu”;
Object o=(Object)s;
String s1=(String)O;
System.out.println(“hai”);
}
}
• It is the child class of RTE
• It is unchecked exception, thrown by JVM when attempting to cast a reference variable to a type the fails to cast a reference variable to a type the faith the IS- A test.
----> Object o=new Object();
String s=(String)o; // Class Cast Exception
----> StringBuffer s1= (StringBuffer)s;
5. NOCLASS DEF FOUND ERROR:
6. EXCEPTION IN INITIALIZER ERROR:
class Sample
{
Static String s;
String s1=new String(s);
public static void main(String a[])
{
System.out.println(“hai”);
}
}//Exception in initializer error caused by java.lang.NullPointerException.
Thrown by the JVM to indicate that an exception is occur during initialization of static variable or initialization block.
7. ILLEGAL ARGUMENT EXCEPTION:
class Sample
{
p s v m(String a[])
{
Thread.currentThread().setPriority(15);
}
}//CTE: Illegal Argument exception
8. NumberFormatException:
Integer i=new Integer(“10”);//valid
Integer i=new Integer(“ten”);//invalid
CTE: NumberFormateException
int i=Integer.parseInt(arg[0]);
In commandline if we give “10” is valid. But “ten” is invalid.
It is the direct child class of illegal argument exception and thrown programmatically to indicate the application has attempted to convert a string to the number, but the string doesn’t have appropriate format.
9. IllegalStateException:
It extends RTE and indicates that a method has been invoked at an illegal or inappropriate time.
Ex: PrintWriter out=res.getWriter();
Out.println(…);
Out.close();
Out.println(“…”); ---> this is not appropriate time to call print() on out object and hence throws IllegalStateException.
10. Assertion Error:
It is the child class of error throws programatically when assert statement when Assert statement fails.
Summarization:
Exception or error --------------------- thrown by
1. NullPointerException ------------------ JVM
2. StackOverFlowErrorException --------------- JVM
3. ArrayIndexOutOfBoundsException ------------- JVM
4. ClassCastException ------------------------- JVM
5. NoClassDefFoundError -------------------- JVM
6. ExceptionInIntializerError -------------------- JVM
thrown by programmatically by programmer API developer:
7. IllegealArgumentException
8. NumberFormatException
9. IllegalStateException
10. Assertion Error
• An Exception is an abnormal and unexpected and also unwanted event that disturbs the normal flow of the program.
Ex: FileNotFoundException
ArithmaticException etc..
Default Exception Handling Mechanism in JAVA:
class Sample
{
public static void main(String a[])
{
doStuff();
}
public static void doStuff()
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
System.out.println(10/0);
}
}
Output: hai
RTE: Exception in thread “main” Java.Lang.Arithematic Exception: /by zero
At Sample . doMoreStuff(Sample.java)
At Sample . doStuff(Sample.java:9)
At sample . main(Sample. java :5)
• If an exception is raised inside any method is r3esponsible for the creation of exception object. (here doMoreStuff() is responsible )
• The Exception object must contain the fallowing information.
1. Name of the Exception(Java.Lang.ArithematicException)
2. Description of the Exception (/ by zero)
3. The position at which the exception raised. (stack trace).
• Now the method handover that exception object to the JVM. JVM will come with that exception object and it will check, is there any exception object and it will check is there any exception handler inside that method abnormally and removes the corresponding entry from the stack.
• Now the method handover that exception object to the JVM. JVM will come with that exception object and it will check, is that any exception handler inside that method. If there is no exception handler then JVM blindly terminate that method abnormally and removes the corresponding entry from the stack.
• JVM will check for the caller(doStuff()) containing any exception handling code. If the caller also doesn’t contain any exception handling code, then JVM simply terminate that method also and remove the corresponding entry from the stack.
• This process will continue, until main() method. If the main() also doesn’t have any exception handling code then JVM terminates main() abnormally and handover the responsibility of the exception handling to default exception handler.
• Now Default Exception handler print the exception information to the end user
Checked vs Unchecked Exceptions :
• The Exceptions which are checked by the compiler for smooth execution of program at Runtime are called checked Exceptions.
• The Exceptions which are unable to check by the compiler are called Unchecked Exceptions.
• Runtime Exception and its child classes: Error and its child classes are Unchecked Exceptions. While the remaining all are Unchecked Exceptions.
Partially Checked vs Fully Checked :
A Checked Exception is said to be Fully Checked Exception if and only if all its child classes are also checked. Otherwise it is Partially Checked Exception.
Ex: IOException is Fully Checked Exception
Exception is Partially Checked
Throwable is Partially Checked
We can handle exceptions by using the fallowing keywords.
1). try 2). catch 3). Finally
4). throw 5). throws
try
{
//Risky code
}
catch(XException e)
{
//Define the handler
}
Ex:
try
{
System.out.println(10/0);
}
catch(ArithematicException e)
{
System.out.println(“caught”);
System.out.println(10/2);
}
System.out.println(“hello”);
output:
caught
5
hello
try
{
Statement 1;
Stmt 2;
Stmt 3;
}
catch(XException e){ Statement 4; }
stmt5;
Case 1:- If there is no Exception ->1,2,3,5 are executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block found then 1 fallowed 4,5 are executes. So, normal termination.
Case 3:- If an Exception is raised at stmt2, but the corresponding catch block not found. Then stmt1 fallowed by abnormal termination.
Case 4:- If an Exception raised at stmt2 and the corresponding catch block found; but while executing catch block raises another Execution then stmt1 fallowed by abnormal termination.
Methods For Displaying Error Information :
The class Throwable contains the fallowing methods for displaying Error information.
1. printStackTrace():
Name of the Exception: Description of Exception Stack trace.
catch(ArithmaticException e)
{
e.printStackTrace();
}
System.out.println(“hai..”);
output:
java.lang.ArithmaticException: /by zero at sample.main(Sample.java)
Hai
2. public String toString():
Name of the Exception: Description of Exception
catch(ArithmaticException e)
{
System.out.println(e.toString());
}
System.out.println(“hai..”);
output:
java.lang.ArithmaticException: /by zero
Hai
3. public String getMessage():
Description of Exception
catch(ArithmaticException e)
{
System.out.println(e.getMessage());
}
System.out.println(“hai..”);
output: /by zero
hai
Try with Multiple catch blocks:
• The way of handling the exception is varied from exception to exception, hence it is a good programming practice to keep separate catch block for every exception.
try
{
System.out.println(10/0);
}
catch(ArithmeticException e) //child
{
//code
}
catch(Exception e) //parent
{
//code
}
Valid since child --> parent
try
{
System.out.println(10/0);
}
catch(Exception e) //parent
{
//code
}
catch(ArithmeticException e) //child
{
//code
}
InValid since parent ----> child
compile time error(CTE) : Exception has already been caught by catch (ArithmeticException e)
• If multiple catch blocks are defined for the try statement, the order of the catch blocks is important. We should take the catch blocks from child to parent, violation leads to CTE saying “Exception” has already been caught”.
Control Flow in try with multiple catch blocks:
try
{
Statement 1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
catch(YException e1)
{
Stmt 5;
}
Stmt6;
Case 1:- If there is no Exception ->1,2,3,6 is executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block(Y Exception e1) is matches then 1,5,6 are executes. So, normal termination.
Case 3:- If an Exception is raised at stmt2, but the corresponding catch block not found. Then stmt1 fallowed by abnormal termination.
Control Flow in Nested try catch :
try
{
Statement 1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
}
catch(XException e)
{
Stmt7;
}
Stmt8;
}
catch(YException e)
{
Stmt9;
}
Stmt10;
Case 1:- If there is no Exception ->1, 2, and 3,4,5,6,8,10 is executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block is matches then 1,9,10 are executes. So, normal termination.
Case 3:- If an Exception raised at stmt2 and the corresponding catch block not found. 1 fallowed by abnormal termination.
Case 4:- If an Exception raised at stmt5 and the corresponding catch block is matches then 1,2,3,4,7,10 and Normal Termination.
Case 5:- If an Exception raised at stmt5 and the corresponding catch block is not matched but outer catch block has matched 1,2,3,4,9,10 and Normal Termination.
Case 6:- An Exception raised at stmt2 and the corresponding catch block has matched but while executing that catch block another exception raised then fallowed by abnormal termination.
Case 7:- An Exception raised at stmt8 and the corresponding catch block has matched then 1,2,3,9,10 fallowed by Normal Termination. If the catch block has not matched abnormal termination.
finally block:
try
{
System.out.println(10/0);
}
catch(AE e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“catch”);
}
• The cleanup code, we have to keep inside finally block because irrespective of exception occurred or not occurred or handled or not handled, the finally block will always execute.
Q: Difference between final, finally and finalize?
• It is highly recommended to keep cleanup code inside finally block instead of finalize().
• The finally block will always execute except the place where the JVM got shutdown. We can shutdown the JVM by calling /using System.exit(0).
Ex:
try
{
System.out.println(“hai”);
}
catch( NULL pointer exception e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“finally”);
}
output:
hai
finally
Q). 1. try{} catch(X e){} -->valid
2. try{}catch(X e){}finally{} -->valid
3. try{}finally{}catch(X e){} --> invalid
4. try{}finally{} -->valid
Ie., try --> catch --> finally is the only order.
Only try{} --->invalid,
Only catch{} ----> invalid
Only finally{} ---->invalid
Note: try without catch & catch with out try invalid
Ex:
catch(..){}
finally{}
CTE: catch with out try
Control Flow in try, catch, finally block :
try
{
Stmt1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
finally
{
Stmt 5;
}
Stmt 6;
Case 1:- If there is no exception then 1,2,3,5,6 and normal termination.
Case 2:- If an exception raised at stmt2 and the corresponding catch block found 1,4,5,6 and normal termination.
Case 3:- If an exception raised at stmt2 and the corresponding catch block not matched 1,5 and abnormal termination.
Control Floe in the Nested try, catch, finally blocks:
try
{
Stmt1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
catch(XException e)
{
Stmt 7;
}
finally
{
Stmt 8;
}
Stmt 9;
}
catch(YException e)
{
Stmt 10;
}
finally
{
Stmt 11;
}
Stmt 12;
Case 1: If there is no exception 1,2,3,4,5,6,8,9,11,12 and normal termination.
Case 2: If an exception raised at stmt 2 and the corresponding catch block found then 1,10,11,12 and normal termination.
Case 3: If an exception raised at stmt2 and the corresponding catch block has not matched then 1,11 and abnormal termination.
Case 4: If an exception raised at stmt5 and the corresponding catch block has matched then 1,2,3,4,7,8,9,11,12 and normal termination.
Case 5: If an exception raised at stmt5 and the corresponding catch block has not matched but the outer catch has matched then 1,2,3,4,8,10,11,12 and normal termination.
Case 6: If an exception raised at stmt5 but the inner and outer catch blocks are not matched then 1,2,3,4,8,11 and abnormal termination.
‘Throw’ keyword:
public static void main(String a[])
{
try
{
Throw new AithmeticException()
}
}
By using ‘throw ‘ keyword, over created customized exception objects are handed over to JVM.
Ex:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any stmt, violation leads to CTE saying “unreachable statement”.
Ex:
class Sample
{
static ArithmeticException e;
public static void main(String[] a)
{
throw e; //invalid
}
}
output: NullPointerException
‘e’(is in instance area) is not pointing “ArithmeticException’ here.
static ArithmeticException e=new ArithmeticException();
Ex:
class Sample
{
public static void main(String a[])
{
Throw new Exception(); //invalid
}
}//CTE: “Unreported Exception Java.lang.Exception must be caught” or declared to be thrown.
• Inside a program if there is any chance of throwing a checked exception explicitly or implicitly we have to handle that checked exception by using try - catch or we have to delegate the responsibility or exception handling to the caller. Violation leads to CTE saying Unreported Exception xxx; must be caught or declared to be thrown.
“throws” Keyword :
Ex:
class Sample
{
public static void main(String a[])throws InteruptedException
{
doStuff();
}
public static void doStuff()throws IE
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
Thread.sleep(1000);
}
}
without ‘throws’ CTE: Unreported Exception java.lang.interuptedException ; must be caught or declared to be thrown. To avoid CTE another way in using try ---> catch block.
Ex:
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(ArithmaticException e){}-->no CTE
}
}
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(IOException e){} --->CTE (fullychecked exception)
}
}
CTE: exception java.io.IOException is never thrown in the body of the corresponding try statement.
We can ‘throws’ keyword for delegating the responsibility of the Exception handling to the caller.
If we are keeping the catch block for fully checked exception there should may be a chance of raising exception in the corresponding try block otherwise CTE saying XXXException is never thrown in the body of corresponding try statement.
Case 1: try
{
System.out.println(“hai”);
}
catch(ArithematicException e) //valid no CTE
{ //unchecked exception }
Case 2: try
{
System.out.println(“hai”);
}
catch(Exception e) //valid no CTE
{ //Partially checked exception }
Case 3: try
{
System.out.println(“hello”);
}
catch(IOException e) //invalid CTE
{ // fully checked exception }
Customized Exceptions :
Based on the programming required sometimes we have to design our own Customized Exceptions.
Ex: Insufficient funds Exception
too young Exception
too old Exception
class TooYoungException extends RunTimeException
{
TooYoungException(String s)
{
super(s);
}
Class Sample
{
public static void main(String a[])
{
Int i=Integer.parseInt(arg[0]);
If(i>85)
throw new TooYoungException(“please wait some more time, you eill get married”);
else if(i<10)
throw new TooYoungException(“ur age is already crossed”);
else
throw new TooYoungException(“very soon you will get match”);
}
}
CommonExceptions and Errors:
Exceptions or errors may be thrown by either JVM(JVM Exceptions) or thrown explicitly by application developers or API programmers(programmatic exception).
1. NULLPOINTER EXCEPTION:
Class Sample
{
Static int[] a;
Static String name;
public static void main(String a[])
{
System.out.println(a.length);
}
}
System.out.println(a[o]); // null pointer exception (NPE)
System.out.println(name.length); //NPE
This is child class of RuntimeException. It is unchecked exception.
This is thrown by JVM when attempting to acess an object with a reference variable whose current value is null.
Ie., on null if we are applying any operation we will get NullPointerException.
2. STACK OVERFLOW ERROR:-
• This is child class of virtual machine error.
• It is unchecked
Throwable ----> Error ---> VMError ---> StackOverFlowError
class Sample
{
public static void m1()
{
m1();
}
public static void main(String a[]){ m1(); } // stack overflow error
}
StackOverflow error is thrown by JVM when a method recurses too deeply.
class Sample
{
Sample() { new Sample(); }
public static void main(String a[]) { Sample s= new Sample(); }//Exception in main thread stack overflow error
}
3. ARRAY INDEXOUTOF BOUNDS EXCEPTION:
• This is a child class of IndexOutOfBoundsExcption.
Throwable ---> Exception ---> RunTimeException ----> IndexOutOfBoundsException---> ArrayIndexOutOfBoundsException, StingIndexOutOfBoundsException
• It is an unchecked exception thrown by JVM when we are accessing an array element with
Invalid index.
Ex:
class Sample
{
public static void main(String a[])
{
Int[] a=new int[6];
System.out.println(a[5]); //0
System.out.println(a[7]); //RTE: ArrayIndexOutOfException
System.out.println(a[-2]); //----do----
System.out.println(a[-2.5]); //CTE: PLP req: int found:double
}
}
4. CLASS CAST EXCEPTION:
Class Sample
{
public static void main(String a[]))
{
String s=”anu”;
Object o=(Object)s;
String s1=(String)O;
System.out.println(“hai”);
}
}
• It is the child class of RTE
• It is unchecked exception, thrown by JVM when attempting to cast a reference variable to a type the fails to cast a reference variable to a type the faith the IS- A test.
----> Object o=new Object();
String s=(String)o; // Class Cast Exception
----> StringBuffer s1= (StringBuffer)s;
5. NOCLASS DEF FOUND ERROR:
- It is the child class of error and it is unchecked one and unreachable.
- It is thrown by JVM. If the JVM or class loader tries to load the definition of the class and no definition of the class could be found.
6. EXCEPTION IN INITIALIZER ERROR:
class Sample
{
Static String s;
String s1=new String(s);
public static void main(String a[])
{
System.out.println(“hai”);
}
}//Exception in initializer error caused by java.lang.NullPointerException.
Thrown by the JVM to indicate that an exception is occur during initialization of static variable or initialization block.
7. ILLEGAL ARGUMENT EXCEPTION:
- It extends RTE and unchecked.
- Thrown by aPI developer to indicate that a method has been passed an illegal or inappropriate argument.
class Sample
{
p s v m(String a[])
{
Thread.currentThread().setPriority(15);
}
}//CTE: Illegal Argument exception
8. NumberFormatException:
Integer i=new Integer(“10”);//valid
Integer i=new Integer(“ten”);//invalid
CTE: NumberFormateException
int i=Integer.parseInt(arg[0]);
In commandline if we give “10” is valid. But “ten” is invalid.
It is the direct child class of illegal argument exception and thrown programmatically to indicate the application has attempted to convert a string to the number, but the string doesn’t have appropriate format.
9. IllegalStateException:
It extends RTE and indicates that a method has been invoked at an illegal or inappropriate time.
Ex: PrintWriter out=res.getWriter();
Out.println(…);
Out.close();
Out.println(“…”); ---> this is not appropriate time to call print() on out object and hence throws IllegalStateException.
10. Assertion Error:
It is the child class of error throws programatically when assert statement when Assert statement fails.
Summarization:
Exception or error --------------------- thrown by
1. NullPointerException ------------------ JVM
2. StackOverFlowErrorException --------------- JVM
3. ArrayIndexOutOfBoundsException ------------- JVM
4. ClassCastException ------------------------- JVM
5. NoClassDefFoundError -------------------- JVM
6. ExceptionInIntializerError -------------------- JVM
thrown by programmatically by programmer API developer:
7. IllegealArgumentException
8. NumberFormatException
9. IllegalStateException
10. Assertion Error
method overriding
Overriding:
If you don’t want parent class implementation for any method we can override in the child class based on our child class requirement. This concept is called Overriding.
While overriding we have to fallow rules:
1. In the overriding, the method names and arg’s must be same.
Ie. In the case of the overriding the signatures of the methods must be same
Until 1.4 version, the return types must be same. But from 1.5 version onwards covariant return types are also allowed.
Ex:1
class p { public Number getNumber(){} }
class c extends P{ public Number getNumber(){} }
(or)
class C extends P
{
public Byte/short/integer getNumber(){}
}
· For Number class Byte/short/integer is covariant return types or classes.
· Hence in case of overriding as the return type we can keep child class objects also.
Ex:2:
import java.io.*;
class P
{
public object m1(){ return new object; }
}
class C extends P
{
public Object m1(){ return new Object; }
}
class C extends P
{
public String m1(){ return “durga”; }
}//in 1.4 CTE saying m1() in C cannot override found:string, req:object: in 1.5 ver no CTE
2. final methods can’t be overridden.
3. private methods never participate in the in the overriding because these methods are not visible in the child classes.
4. While overriding decreasing access specifier is not allowed. Violation leads to CTE.
class P { public int m1(){} }
class C extends P { public int m1(){} }
Parent class ---------------------------------------- Child class
public ---------------------------------------- public
protected ---------------------------------------- protected, public
default ---------------------------------------- default, protected ,public
private ---------------------------------------- private, default, protected, public
* While implementing any interface method, we should declare that method as public in the implemented class.(by default implements interface method is public and abstract)
* An abstract method can be overridden as abstract. The child of the original child class is responsible for the implementation.
class P{ public void m1(){ } }//non abstract
abstract class C extends P{ public abstract m1(); }//valid abstract
5. While overriding the size of the CheckedException should mot increase(ie.,new checked exceptions are not allowed) There is no rule for UnCheckedExceptions.
Ex 1: Base or parent class
public void m1()throws IOException
Ex 2: Derived or child class
public void m1()throws FileNotfoundException//valid
public void m1()throws Exception -->CTE
public void m1()throws RunTimeException//valid
* We can override a synchronized method to non-synchronized and vice versa
* We can override native to native to non native and vice versa.
* We can override a non-final method to final method.
* We can’t override a static method to non static and a non-static method to static violation leads to CTE .
In the case of overriding:
• While overriding method has to execute will be decided by JVM based on the Run Time Object. Hence Overriding is an example of “dynamic polymorphism” or “LateBinding” (Dynamic Method dispatch).
• If the parent’s class reference can be used to hold child class object by using that reference we are allowed to call only parent class methods. Child class specific methods are not allowed to call by using parent class reference.
Method Hiding:-
This is exactly same as overriding except both parent & child class methods must be declared as static. In the method hiding the method resolution take care by compiler only based on the reference type.
Ex:
class P
{
static int x=10;
int y=20;
}
class C extends P
{
static int x=100;
int y=200;
}
class Sample
{
public static void main(String[] a)
{
P p=new C();
S.o.p(p.x+”,”+p.y);//10,20
C c=new C();
S.o.p(c.x+”,”+c.y);//100,200
P p1=new P();
S.o.p(p1.x+”,”+p1.y);//10,20
}
}
Variable hiding or shadowing:-
We can’t override in the child class. But if define exactly same variable in child class.
Variable resolutions take care by compiler only based on the reference type.
If you don’t want parent class implementation for any method we can override in the child class based on our child class requirement. This concept is called Overriding.
While overriding we have to fallow rules:
1. In the overriding, the method names and arg’s must be same.
Ie. In the case of the overriding the signatures of the methods must be same
Until 1.4 version, the return types must be same. But from 1.5 version onwards covariant return types are also allowed.
Ex:1
class p { public Number getNumber(){} }
class c extends P{ public Number getNumber(){} }
(or)
class C extends P
{
public Byte/short/integer getNumber(){}
}
· For Number class Byte/short/integer is covariant return types or classes.
· Hence in case of overriding as the return type we can keep child class objects also.
Ex:2:
import java.io.*;
class P
{
public object m1(){ return new object; }
}
class C extends P
{
public Object m1(){ return new Object; }
}
class C extends P
{
public String m1(){ return “durga”; }
}//in 1.4 CTE saying m1() in C cannot override found:string, req:object: in 1.5 ver no CTE
2. final methods can’t be overridden.
3. private methods never participate in the in the overriding because these methods are not visible in the child classes.
4. While overriding decreasing access specifier is not allowed. Violation leads to CTE.
class P { public int m1(){} }
class C extends P { public int m1(){} }
Parent class ---------------------------------------- Child class
public ---------------------------------------- public
protected ---------------------------------------- protected, public
default ---------------------------------------- default, protected ,public
private ---------------------------------------- private, default, protected, public
* While implementing any interface method, we should declare that method as public in the implemented class.(by default implements interface method is public and abstract)
* An abstract method can be overridden as abstract. The child of the original child class is responsible for the implementation.
class P{ public void m1(){ } }//non abstract
abstract class C extends P{ public abstract m1(); }//valid abstract
5. While overriding the size of the CheckedException should mot increase(ie.,new checked exceptions are not allowed) There is no rule for UnCheckedExceptions.
Ex 1: Base or parent class
public void m1()throws IOException
Ex 2: Derived or child class
public void m1()throws FileNotfoundException//valid
public void m1()throws Exception -->CTE
public void m1()throws RunTimeException//valid
* We can override a synchronized method to non-synchronized and vice versa
* We can override native to native to non native and vice versa.
* We can override a non-final method to final method.
* We can’t override a static method to non static and a non-static method to static violation leads to CTE .
In the case of overriding:
• While overriding method has to execute will be decided by JVM based on the Run Time Object. Hence Overriding is an example of “dynamic polymorphism” or “LateBinding” (Dynamic Method dispatch).
• If the parent’s class reference can be used to hold child class object by using that reference we are allowed to call only parent class methods. Child class specific methods are not allowed to call by using parent class reference.
Method Hiding:-
This is exactly same as overriding except both parent & child class methods must be declared as static. In the method hiding the method resolution take care by compiler only based on the reference type.
Ex:
class P
{
static int x=10;
int y=20;
}
class C extends P
{
static int x=100;
int y=200;
}
class Sample
{
public static void main(String[] a)
{
P p=new C();
S.o.p(p.x+”,”+p.y);//10,20
C c=new C();
S.o.p(c.x+”,”+c.y);//100,200
P p1=new P();
S.o.p(p1.x+”,”+p1.y);//10,20
}
}
Variable hiding or shadowing:-
We can’t override in the child class. But if define exactly same variable in child class.
Variable resolutions take care by compiler only based on the reference type.
method overloading
Method Overloading :
• Two methods having the same name are not allowed in the case of C-language, for every data type even though the functionality in the same; we should maintain different method names. It increases the complexity of the programming. But in java, two methods having the same name is allowed irrespective of parameters. We can maintain the same method name for similar type of functionality. It implifies the programming. Such types of methods are called Overloaded methods.
• Two methods are said to be overloaded if and only of they have the same method name, but different parameter list(at least order).
• The signatures of the two overloaded methods must be different.
Ex:
public void m1(){}
private int m1(int i){}
• Here m1() & m1(int i) are overloaded. We never consider return type, access modifier and throws class in overloading.
Ex:
class Sample
{
public void m1()
{
System.out.println(“no arg”);
}
public int m1(int i)
{
System.out.println(“ int arg”);
}
public void m1(double d)
{
System.out.println(“ double arg”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1();
s.m1(10);
s.m1(10.5);
}
}
• In the case of overloading which overloaded method must be executed is decided method must be executed is decided by compiler only based on reference type.
• Ie., Overloaded method resolution is the duty of compiler only. Hence Overloading is the best
ex. of static polymorphism and some times also known as Early Binding.
s.m1(10L);//double arg
s.m1(‘a’);//int arg
i.e., Automatic Promotion in Overloading:
• If we are calling a method m1() by passing char as arg on the sample reference then the compiler will check in the Sample class for m1(), which can take char as the arg.
• If it finds that method, it will execute at runtime.If there is no such method the compile promotes that char arg to the int arg and checks for m1(int) method.
• If there is no such method, the compiler will check for m1(long), fallowed by m1(float),fallowed by m1(double). Still if the compiler won’t find any such method then only compiler will raised CTE saying ‘cannot resolve the symbol m1(char)’.
CASE 1:
class Sample
{
public void m1(int i,float f)
{
S.o.p(“int,float”);
}
public void m1(int i,float f)
{
S.o.p(“float,int”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1(10,10.0f);//int,float
s.m1(10.0f,10);//float,int
s.m1(10,10);//invalid-> CTE:reference m1 is ambiguous
}
}
CASE 2:
class Sample
{
public void m1(String s){ S.o.p(“String version”); }
public void m1(Object o){ S.o.p(“Object version”); }
public void m1(double d){ S.o.p(“double version”); }
public void m1(Double o){ S.o.p(“ version”); }
public static void main(String a[])
{
Sample s=new Sample();
s.m1(“viswan”);// String version
s.m1(new Object());// Object version
s.m1(null);// String version
}
}
If there is Double (wrapper class) then CTE: reference to m1 is ambiguous.
CASE 3:
class Sample
{
public void m1(Animal a){ S.o.p(“Animal version”); }
public void m1(Monkey m){ S.o.p(“Monkey version”); }
public static void main(String a[])
{
Animal a =new Animal();
s.m1(a);// Animal version
Monkey m =new Monkey();
s.m1(m);// Monkey version
Animal a1 =new Monkey l();
s.m1(a1);// Animal version
}
}
In the case of overloading the method resolution performed by the compiler is based on the reference type.
• Two methods having the same name are not allowed in the case of C-language, for every data type even though the functionality in the same; we should maintain different method names. It increases the complexity of the programming. But in java, two methods having the same name is allowed irrespective of parameters. We can maintain the same method name for similar type of functionality. It implifies the programming. Such types of methods are called Overloaded methods.
• Two methods are said to be overloaded if and only of they have the same method name, but different parameter list(at least order).
• The signatures of the two overloaded methods must be different.
Ex:
public void m1(){}
private int m1(int i){}
• Here m1() & m1(int i) are overloaded. We never consider return type, access modifier and throws class in overloading.
Ex:
class Sample
{
public void m1()
{
System.out.println(“no arg”);
}
public int m1(int i)
{
System.out.println(“ int arg”);
}
public void m1(double d)
{
System.out.println(“ double arg”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1();
s.m1(10);
s.m1(10.5);
}
}
• In the case of overloading which overloaded method must be executed is decided method must be executed is decided by compiler only based on reference type.
• Ie., Overloaded method resolution is the duty of compiler only. Hence Overloading is the best
ex. of static polymorphism and some times also known as Early Binding.
s.m1(10L);//double arg
s.m1(‘a’);//int arg
i.e., Automatic Promotion in Overloading:
• If we are calling a method m1() by passing char as arg on the sample reference then the compiler will check in the Sample class for m1(), which can take char as the arg.
• If it finds that method, it will execute at runtime.If there is no such method the compile promotes that char arg to the int arg and checks for m1(int) method.
• If there is no such method, the compiler will check for m1(long), fallowed by m1(float),fallowed by m1(double). Still if the compiler won’t find any such method then only compiler will raised CTE saying ‘cannot resolve the symbol m1(char)’.
CASE 1:
class Sample
{
public void m1(int i,float f)
{
S.o.p(“int,float”);
}
public void m1(int i,float f)
{
S.o.p(“float,int”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1(10,10.0f);//int,float
s.m1(10.0f,10);//float,int
s.m1(10,10);//invalid-> CTE:reference m1 is ambiguous
}
}
CASE 2:
class Sample
{
public void m1(String s){ S.o.p(“String version”); }
public void m1(Object o){ S.o.p(“Object version”); }
public void m1(double d){ S.o.p(“double version”); }
public void m1(Double o){ S.o.p(“ version”); }
public static void main(String a[])
{
Sample s=new Sample();
s.m1(“viswan”);// String version
s.m1(new Object());// Object version
s.m1(null);// String version
}
}
If there is Double (wrapper class) then CTE: reference to m1 is ambiguous.
CASE 3:
class Sample
{
public void m1(Animal a){ S.o.p(“Animal version”); }
public void m1(Monkey m){ S.o.p(“Monkey version”); }
public static void main(String a[])
{
Animal a =new Animal();
s.m1(a);// Animal version
Monkey m =new Monkey();
s.m1(m);// Monkey version
Animal a1 =new Monkey l();
s.m1(a1);// Animal version
}
}
In the case of overloading the method resolution performed by the compiler is based on the reference type.
Thursday, January 8, 2009
Subscribe to:
Posts (Atom)