Java Exception Handling
Java Exception Handling
Java Exception Handling
Suchita Arora
Handling
Exception & I/O Handling
2
WHAT IS AN EXCEPTION?
3
PROCESS IN JAVA WHEN ERRORS HAPPEN
4
WHY USING EXCEPTIONS?
5
Exceptions -Checked and Unchecked and Error
Types of Exceptions:- As per sun micro systems standards The Exceptions are divided
into three types
Checked Exception
Unchecked Exception
Error
The Exceptions which are checked by the compiler at compilation time for the proper
execution of the program at runtime is called CheckedExceptions. Ex:-
IOException,SQLException etc…
6
UnCheckedException
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.(out of range)
InputMismatchException If we are giving input is not matched for storing
input.
ClassCastException If the conversion is Invalid.
IllegalArgumentException Illegal argument used to invoke a method
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric
format.
7
• checkedException:-
• The Exceptions which are checked by the compiler at compilation time for the
proper execution of the program at runtime is called CheckedExceptions. Ex:-
IOException,SQLException etc……….
8
Some of the checked exceptions in the java language:-
Exception Description
ClassNotFoundException If the loaded class is not available
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract
class or interface
InterruptedException One thread has been interrupted by another
thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException If the requested method is not available.
9
Error
• Error:- Errors are caused by lack of system resources . these are non
recoverable. Ex:- StackOverFlowError,OutOfMemoryError
10
hierarchy of Java exception classes:
11
Note
Note:-
1) RuntimeException and its child classes and Error and its child
classes are Unchecked remaining all are checkedExceptions.
2) Root class for all Exception hierarchy is Throweable class.
1) try
2) catch
3) finally
4) Throw
5) throws
12
• Exception handling by using Try –catch block:-
• 1) In java language we are handling the exceptions By using try and catch blocks. try block
contains risky code of the program and catch block contains handling code of the program.
• 2) Catch block code is a alternative code for Exceptional code. If the exception is raised the
alternative code is executed fine then rest of the code is executed normally.
•
• Syntax:- try
• {
• Code to run [break;]
• } Catch(ExceptionName reference_variable)
• {
• Code to run if an exception is raised
• }
•
13
Before try and catch:-The program goes to abnormal termination .
class Test
{
public static void main(String[] args)
{
System.out.println(“hardware");
System.out.println("software");
System.out.println(10/0);
System.out.println("solutions");
}
}
14
Try catch block
1) If we are taking try-catch the program goes to normal termination. Because the
risky code we are taking inside the try block and handling code we are taking
inside the catch block.
2) 2) If the exception is raised in the try block the corresponding catch block is
executed.
3) If the corresponding catch block is not there program goes to abnormal
termination.
15
Ex 1:-
• Exception raised in try block the JVM will search for corresponding catch block if the catch block is
matched, corresponding catch block will be executed and rest of the code is executed normally.
class Test
{ public static void main(String[] args)
{
System.out.println("program starts");
try {
int[] a={10,20};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
} catch(ArrayIndexOutOfBoundsException ae)
{ System.out.println("we are getting exception");
}
System.out.println("rest of the code");
}
}
16
• Ex 2:-
• Exception raised in try block the JVM will search for corresponding catch block if the catch block is matched,
corresponding catch block will be executed and rest of the code is executed normally. If the catch block is not
matched the program is terminated abnormally.
class Test
{
public static void main(String[] args)
{ System.out.println("program starts");
try { int[] a={10,20};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]); }
catch(ArithmeticException ae)
{
System.out.println("we are getting exception");
} System.out.println("rest of the code");
}
}
17
Ex 3:- if there is no exception in try block the catch blocks won’t be executed.
Class Test
{ public static void main(String[] args)
{ System.out.println("program starts");
try { System.out.println(“hello");
System.out.println("how r u");
} catch(ArithmeticException ae)
{ System.out.println("we are getting exception");
} System.out.println("rest of the code");
}
}
18
Ex 4:- independent try blocks are not allowed in java language.(compilation error)
class Test
{ public static void main(String[] args)
{ System.out.println("program starts");
try
{ int a=10/0; }
System.out.println("rest of the code is avilable");
}
}
19
Ex 5:-
In between try and catch independent statements are not allowed. If we are
providing independent statements the compiler will raise compilation error.
class Test { public static void main(String[] args)
{ System.out.println("program starts");
try
{ int a=10/0; }
System.out.println(“in between try and catch”);
catch(ArithmeticException e)
{ int a=10/5;
System.out.println(a);
} System.out.println("rest of the code is avilable"); } }
20
Ex 6 The way of handling the exception is varied from exception to the exception so it is recommended to
provide try with number of catch blocks.
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("provide the division value");
int n=s.nextInt();
try { System.out.println(10/n);
String str=null;
System.out.println("u r name is :"+str);
System.out.println("u r name length is--->"+str.length());
} catch (ArithmeticException ae)
{ System.out.println("good boy zero not allowed geting Exception"+ae); }
catch (NullPointerException ne)
{ System.out.println("good girl getting Exception"+ne);
} System.out.println("rest of the code"); } }
21
Ex:-7 import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("provide the division value");
int n=s.nextInt();
try { System.out.println(10/n);
String str=null;
System.out.println("u r name is :"+str);
System.out.println("u r name length is--->"+str.length()); }
22
Ex 8:-in java class if we are declaring multiple catch blocks at that situation the catch block order should be child
to parent shouldn’t be parent to the child.
(No compilation error)
Child-parent
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("provide the division val");
int n=s.nextInt();
try {
System.out.println(10/n);
String str=null;
System.out.println("u r name is :"+str);
System.out.println("u r name length is-->"+str.length());
} catch (ArithmeticException ae)
{ System.out.println("Exception"+ae); }
catch (Exception ne)
{ System.out.println("Exception"+ne); } System.out.println("rest of the code"); }}
23
Ex 9:- The exception raised in catch block it is always abnormal termination.
class Test { public static void main(String[] args)
{ System.out.println("program starts");
try { int a=10/0; }
catch(ArithmeticException e)
{ int a=10/0;
System.out.println(a);
}
System.out.println("rest of the code is avilable"); } }
24
• Finally block:-
1) finally is a block it is always executed irrespective of try and catch.
2) Finally contains clean-up code.
3) It is not possible to write finally alone . we must take try-catch-finally otherwise
take the tryfinally these two are the possibilities. If we are taking any other we are
getting compilation error saying finally without try block .
Syntax:- try { risky code; }
catch (Exception obj) { handling code; }
finally { free code; }
25
Ex :- Exception raised in try block and corresponding catch block is matched then
rest of the code is executed normally.
class Test {
public static void main(String[] args)
{ try { System.out.println(“hello");
System.out.println(10/0);
} catch (ArithmeticException ae)
{ System.out.println("u r getting ae:"+ae); }
finally
{ System.out.println("finally block is always executed");
} System.out.println("rest of the code"); } }
26
Ex:- class Test
{ public static void main(String[] args)
{ try
{ System.out.println(“hello");
System.out.println(10/0); }
catch (NullPointerException ne)
{ System.out.println("u r getting ne"+ne);
}
finally
{ System.out.println("finally block is always executed"); }
System.out.println("rest of the code");
//this line not executed } }
Output:- hello Finally block is always executed Exception in Thread “main”
:java.lang.ArithmeticException: / by zero
27
The only one situation the finally block is wont be executed:- In your program whenever we are
using System.exit(0) the JVM is shut downing hence the rest of the code won’t be executed .
Ex:- class Test
{ public static void main(String[] args)
{ try { System.out.println(“hello");
System.exit(0);------>line 1
System.out.println(10/0); }
catch (ArithmeticException ae)
{ System.out.println("u r getting ae"+ae);
System.exit(0);------>line 2
} finally
{ System.out.println("finally block is always executed");
} System.out.println("rest of the code");
} } Note:- if we are commenting line 2 Output :- hello
Note :- if we are commenting line 1 Output:- hello U r getting ae: ArithmeticException :/by zero
28
Throw:-
1) The main purpose of the throw keyword is to creation of Exception object
explicitly either for predefined or user defined .
2) 2) Throw keyword works like a try block. The difference is try block is
automatically find the situation and creates a Exception object implicitly.
Whereas throw keyword creates a Exception object explicitly
Ex:- class Test
{ public static void main(String[] args)
{ try { System.out.println(10/0);
catch (ArithmeticException ae)
{ System.out.println("we are getting Exception "+ae);
} }}
Output:- we are getting Exception ArtithmeticException: / by zero
29
Note :- In the above program the main method is responsible to create a exception
object. So the main method is creating exception object implicitly. The programmer
is not responsible person to creates a exception object.
class Test { public static void main(String[] args)
{
throw new ArithmeticException("we are getting Exception / by zero man");
}}
30
Ex:- import java.util.*;
class Test {
static void validate(int age)
{ if (age<18)
{ throw new ArithmeticException("not elgible for vote");
}
else
{ System.out.println("welcome to the voteing");
} }
public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int n=s.nextInt();
validate(n);
System.out.println(“rest of the code”);
}
}
31
Throws :-
1) Throw keyword is used to create exception object explicitly. But the main
purpose of the throws keyword is bypassing the generated exception from
present method to caller method.
2) 2) Throw keyword is used in the method body. But throws keyword we have to
use in the method declaration.
3) 3) It is possible to throws any number of exceptions at a time based on the
programmer requirement.
32
By using try-catch blocks:-
Ex:- import java.io.*; class Student
{ void studentDetails()
{ try
{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter student name");
String sname=br.readLine();
System.out.println(“u r name is:”+sname); }
catch(IOException e) { System.out.println("we are getting Exception"+e);
} }
public static void main(String[] args)
{ Student s1=new Student();
s1.studentDetails(); } }
33
By using throws keyword:-
34
There are two types of exceptions present in the java language
1) Predefined Exceptions.
2) 2) User defined Exceptions.
Predefined Exception:- Predefined classes comes along with the software based on
your requirement we have to create a objects. Ex:-
ArithmeticException,IOException,NullPointerException…………..etc
User defined Exceptions:- Based on the user requirement user can creates a
Exception is called user defined Exception.
Ex:InvaliedAgeException,BombBlastException………..etc
35
To create user defined Exceptions:-
1) To create user defined exception we have to take an user defined class that is a
sub class to the RuntimeException(for creation of unchecked Exceptions) .
2) To create user defined exception we have to take user defined class that is
subclass to the Exception(for creation of checked Exceptions)
3) Each and every Exception contains two constructors
a) default constructor
b) parameterized constructor
36
for the creation of UncheckedException
Default constructor approach
Class InvaliedAgeException extends RuntimeException {
37
For the creation of checkedException:-
Note:- For these type of user defined Exceptions we have to handle the Exception
otherwise we are getting compilation error . Hence try-catch [or] throws keyword is
required for the handling of Exceptions
38
Ex:-preparation of custom checked exceptions:-
//userdefined Exception class preparation
public class InvaliedAgeException extends Exception
{ InvaliedAgeException(String str)
{
super(str);
}
}
39
class Test
{ static void validate(int age) throws InvaliedAgeException
{ if (age<18)
{
throw new InvaliedAgeException("not elgible for vote");
}
else
{ System.out.println("welcome to the voteing");
} }
public static void main(String[] args) throws InvaliedAgeException
{ Scanner s=new Scanner(System.in);
System.out.println("please enter age");
int age=s.nextInt(); validate(age); } }
40
Ex:-preparation of custom unchecked exceptions:-
public class InvaliedAgeException extends RuntimeException
{ InvaliedAgeException(String str)
{ super(str);
}
}
import java.util.*;
class Test { static void validate(int age)
{ if (age<18)
{ throw new InvaliedAgeException("not elgible for vote"); }
else { System.out.println("welcome to the voteing"); } }
public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("please enter age");
int age=s.nextInt();
validate(age); } }
41
Different types of exceptions:-
ArrayIndexOutOfBoundsException:- whenever we are calling array with out of
range at that moment we are getting ArrayIndexOutOfBoundsException.
Ex:- class Test { public static void main(String[] args)
{
try { int[] a={10,20,30};
System.out.println(a[0]);//10 System.out.println(a[1]);//20
System.out.println(a[2]);//30
System.out.println(a[3]);//ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException ae)
{ System.out.println("boss u r geting ArrayIndexOutOfBoundsException");
System.out.println("check u r code once"); } } }
42
NumberFormatException:- At the time of converting String value into the integer
value we are getting NumberFormatException.
Ex:- class Test
{ public static void main(String[] args)
{ try { String str="123";
int a=Integer.parseInt(str);
System.out.println(a);//conversion(string - int) is good
String str1="abc"; int b=Integer.parseInt(str1);
System.out.println(b);//NumberFormatException } catch (NumberFormatException
ae) { System.out.println("boss u r geting NumberFormatException");
System.out.println("check once u r code");
} }}
43
NullPointerException:- If we are having ‘null’ in any variable in that variable we are
performing any operation we are getting NummpointerException.
Ex:- class Test
{ public static void main(String[] args)
{ try { String str=“hello";
System.out.println(str.length());/4
String str1=null;
System.out.println(str1.length());//NullPointerException
44
ArithmeticException:- Whenever we are performing / by zero operation we are
getting ArithmeticException.
Ex:- class Test
{ public static void main(String[] args)
{ try
{ int a=10/2;
System.out.println(a);//5
int b=10/0;
System.out.println(b);//ArithmeticExceptiom
} catch (ArithmeticException ne)
{ System.out.println("boss u r geting ArithmeticException");
System.out.println("check once u r code"); } } }
45
IllegalArgumentException:-
Thread priority range is 1-10
1--- low priority
10- high priority
If we are giving priority out of range then we are getting
IllegalArgumentException. Ex:- class Test
{ public static void main(String[] args)
{ Thread t=new Thread();
t.setPriority(11);//IllegalArgumentException } }
46
IllegalThreadStateException:- Whenever we are trying to restart the already start
thread then we are getting IllegalThreadStateException
. Ex:- class Test {
public static void main(String[] args) {
Thread t=new Thread();
t.start();
t.start();//IllegalThreadStateException } }
47
StringIndexOutOfBoundsException:- Whenever we are trying to perform String
based operations with out of range condition then we will get
StringIndexOutOfBoundsException.
Ex:- class Test {
public static void main(String[] args)
{
String str=“hello";
System.out.println(str.charAt(3));//l
System.out.println(str.charAt(13));//
StringIndexOutOfBoundsException }}
48
NegativeArraySizeException:- If we are giving array size in negative values then we
are getting NegativeArraySizeException.
Ex:- class Test { public static void main(String[] args)
{ int[] a1=new int[100];
System.out.println(a1.length);//100
int[] a=new int[-9];
System.out.println(a.length);//NegativeArraySizeException
}}
49
InputMismatchException:
- import java.util.*;
- class Test { public static void main(String[] args)
- { Scanner s=new Scanner(System.in);
- System.out.println("enter first number"); int a=s.nextInt();
System.out.println("enter second number"); int b=s.nextInt();
System.out.println(a+b); } };
50
Different types of Errors:-
StackOverflowError:- Whenever we are calling method recursively then we are
getting StackOverflowError.
Ex:- class Test
{
void m1() {
m2();
System.out.println("this is class”);
}
void m2() { m1();
System.out.println(“sec b"); }
public static void main(String[] args)
{ Test t=new Test(); t.m1(); } }
51
OutOfMemoryError:- If we are creating objects greater than the heap memory then
we are getting OutOfMemoryError.
Ex:- class Test
{ public static void main(String[] args)
{ int[] a=new int[100000000];//OutOfMemoryError
}}
NoClassDefFoundError:- Whatever the class if we want to execute if the class is not
available at runtime we are getting NoClassDefFoundError.
Ex:- class Hello
{ public static void main(String[] args)
{ System.out.println(“Hello"); } }
Output:- javac Test.java Java Test
52
java 7 features:-
multi-catch:- the multi-catch feature is allows two or more exceptions to be caught
by the same catch clause.
import java.util.*;
class Test {
public static void main(String[] args)
{ int a[]=new int[3];
Scanner s=new Scanner(System.in);
System.out.println("enter n value");
int n=s.nextInt();
try { System.out.println(10/n);
for (int i=0;i<a.length;i++ )
{ System.out.println("enter "+i+" value");
a[i]=s.nextInt(); }
System.out.println(a[7]);
} catch (ArithmeticException|ArrayIndexOutOfBoundsException e)
{ System.out.println(e); }
System.out.println("program is ended"); } };
53
How to define Own Exceptions?
54
Multithreading
What is Thread?
• Thread: single sequential flow of control within a
program
• Single-threaded program can handle one task at any
time.
• Multitasking allows single processor to run several
concurrent threads.
55
Advantages of Multithreading
56
Thread Concept
Thread 1
Thread 2
Thread 3
Thread 1
Thread 2
Thread 3
57
Single threaded model:-
class Test {
public static void main(String[] args)
{ System.out.println("Hello World!");
System.out.println("hi");
System.out.println("hello Jaipur"); } }
• In the above program only one thread is available is called main thread to know
the name of the thread we have to execute the following code.
58
class Test
{ public static void main(String[] args)
{
System.out.println("Hello World!");
Thread t=Thread.currentThread();
System.out.println("currrent thread information is : "+t);//[main,5,main]
System.out.println("currrent thread priority is : "+t.getPriority());//5
System.out.println("currrent thread name is : "+t.getName());
}
}
59
There are two different ways to create a thread isavilable
1) Create class that extending standered java.lang.Thread Class
2) Create class that Implementing java.lang.Runnable interface
Step 1:- Creates a class that is extend by Thread classes and override the run() method
class MyThread extends Thread {
public void run() {
System.out.println("business logic of the thread");
System.out.println("body of the thread");
}
}
Step 2:- Create a Thread object MyThread t=new MyThread();
60
Step 3:- Starts the execution of a thread. t.start();
In this approach take one user defined class class that is extending Thread class .
Ex:-
class MyThread extends Thread
{
public void run()
{ System.out.println(“hi");
System.out.println("body of the thread");
}}
class ThreadDemo {
public static void main(String[] args)
{ MyThread t=new MyThread();
t.start(); } }
61
Note :- 1) Whenever we are calling t.start() method the JVM search for the start()
in the MyThread class but the start() method is not present in the MyThread class
so JVM goes to parent class called Thread class and search for the start() method.
2) In the Thread class start() method is available hence JVM is executing start()
method.
3) Whenever the thread class start() that start() is responsible person to call run()
method.
4) Finally the run() automatically executed whenever we are calling start() method.
5) Whenever we are giving a chance to the Thread class start() method then only a
new thread will be created.
62
Thread States
A thread can be in one of five states: New, Runnable, Running, Blocked/Waiting, or
Finished.
63
Life cycle stages are:-
1) New
2) Ready /Runnable
3) Running state
4) Blocked / waiting / non-running mode
5) Dead
state New :- MyThread t=new MyThread();
Running state:- If thread scheduler allocates CPU for particular thread. Thread goes to running state
The Thread is running state means the run() is executed.
Blocked State:- If the running thread got interrupted of goes to sleeping state at that moment it goes to the
blocked state.
Dead State:- If the business logic of the project is completed means run() over thread goes dead state.
64
Second approach to create thread implementing Runnable interface:-
Step 1:- Creates a class that implements Runnable interface. class MyClass
extends Runnable { public void run() { System.out.println("Rattaiah from
durgasoft"); System.out.println("body of the thread"); } };
65
class MyThread implements Runnable
{
public void run()
{ System.out.println(“rum method");
System.out.println("body of the thread");
}}
class ThreadDemo
{ public static void main(String[] args)
{ MyClasss obj=new MyClass();
Thread t=new Thread(obj);
t.start();
}}
66
Step 1:- the Class MyClass implements the Runnable interface and overriding run()
method and contains the logic associates with the body of the thread.
Step 2:- Creates the object of implementation class this is not like a first
mechanism.
Step 3 :- Creates a generic thread object then pass the MyClass reference variable
as a parameter to that object.
Step 4:- As a result of third step 3 a thread object is created in order to execute
this thread method we need to class start() method. Then new thread is executed.
67
We are having two approaches:-
First approach:-
1) By extending the thread class, the derived class itself is a thread object and it gains
full control over the thread life cycle.
2) Another important point is that when extending the Thread class, the sub class
cannot extend any other base classes because Java allows only single inheritance.
Note:-if the program needs a full control over the thread life cycle, then extending the
Thread class is a good choice.
Second approach:-
1) Implementing the Runnable interface does not give developers any control over the
thread itself, as it simply defines the unit of work that will be executed in a thread.
2) By implementing the Runnable interface, the class can still extend other base classes
if necessary.
Note:-if the program needs more flexibility of extending other base classes,
implementing the Runnable interface would be preferable
68
Internal Implementation of multiThreading:-
Runnable-----abstract method
Thread--------empty implementation run() method
Mythread---based on our requirement we are providing implementation
(overriding run() method)
interface Runnable {
public abstract void run();
}
class Thread implements Runnable
{ public void run() { } };
class MyThread extends Thread
{ public void run() {
for (int i=0;i<5 ;i++ ) {
}
69
Note :-
If we are overriding start() method then JVM is executes override start() method at
this situation we are not giving chance to the thread class start() hence n new
thread will be created only one thread is available the name of that thread is main
thread.
class MyThread extends Thread
{ Public void start() { System.out.println(“override start method”);
}}
class ThreadDemo { public static void main(String[] args)
{ MyThread t=new MyThread();
t.start();
for (int i=0;i<5 ;i++ ) { System.out.println("main thread"); }}
70
• Particular task is performed by the number of threads:-
• 1) Particular task is performed by the number of threads here number of
threads(t1,t2,t3) are executing same method (functionality).
• 2) In the above scenario for each and every thread one stack is created. Each
and every method called by particular Thread the every entry stored in the
particular thread stack.
•
• Here Four Stacks are created
• Main -----------stack1
• t1---------------stack2
• t2--------------stack3
• t3-------------stack4
71
• class MyThread extends Thread
• { public void run()
• { System.out.println(“class V");
• }}
• class ThreadDemo
• { public static void main(String[] args)
• { MyThread t1=new MyThread();
• MyThread t2=new MyThread();
• MyThread t3=new MyThread();
• t1.start();
• t2.start();
• t3.start(); }}
72
• Getting and setting names of Thread:-
• 1) Every Thread in java has some name if may be default name provided by the jvm
or customized name provided by the programmer. The fallowing methods are useful
to set and get the name of a Thread.
•
• a. Public final String getName() b. Public final void setName(String name)
73
Thread Priorities:- 1. Every Thread in java has some property. It may be default priority provided be
the JVM or customized priority provided by the programmer.
2. The valid range of thread priorities is 1 – 10. Where one is lowest priority and 10 is highest
priority.
3. The default priority of main thread is 5. The priority of child thread is inherited from the parent.
4. Thread defines the following constants to represent some standard priorities.
5. Thread Scheduler will use priorities while allocating processor the thread which is having highest
priority will get chance first and the thread which is having low priority.
6. If two threads having the same priority then we can’t expect exact execution order it depends
upon Thread Scheduler.
7. The thread which is having low priority has to wait until completion of high priority threads.
8. Three constant values for the thread priority.
74
Thread class defines the following methods to get and set priority of a Thread.
75
class FirstThread extends Thread
{
public void run()
{
System.out.println("Enter into thread First");
System.out.println("thread First is started");
for (int i=0;i<10 ;i++ )
{
System.out.println(“First");
}
System.out.println("thread First is ended");
} };
76
class SecondThread extends Thread
{
public void run()
{
System.out.println("Enter into thread Second");
System.out.println("thread second is started");
for (int i=0;i<10 ;i++ )
{
System.out.println(“Second");
}
System.out.println("thread second is ended");
} };
77
class ThirdThread extends Thread
{
public void run()
{
System.out.println("Enter into thread Third");
System.out.println("thread third is started");
for (int i=0;i<10 ;i++ )
{
System.out.println(“Third");
}
System.out.println("thread Third is ended");
} };
78
class ThreadDemo
{ public static void main(String[] args) {
FirstThread thread1=new FirstThread();
SecondThread thread2=new SecondThread();
ThirdThread thread3=new ThirdThread();
thread1.setPriority(Thread.MAX_PRIORITY);
System.out.println(thread1.getPriority());
Thread2.setPriority(Thread.MIN_PRIORITY);
System.out.println(thread2.getPriority());
Thread3.setPriority(thread2.getPriority()+1);
System.out.println(thread3.getPriority());
System.out.println("starting of FirstThread");
79
thread1.start();
80
Some of the thread class methods:-
Sleep():- The sleep() method causes the current thread to sleep for a specified
amount of time in milliseconds.
81
• Ex:- class Test
• { public static void main(String[] args)
• { try { for (int i=0;i<10 ;i++)
• { System.out.println(“wait");
• Thread.sleep(5*1000);//5 seconds
• Thread.sleep(5*60*1000);// 5 minits
• } }
• catch (InterruptedException ie)
• { System.out.println("the thread is got innterupted"); } } }
82
If a Thread wants to wait until completing some other thread then we should go for
join() method.
83
class MyThread extends Thread
{ public void run()
{ for (int i=0;i<5;i++ )
{ try{ System.out.println(“hi");
Thread.sleep(3*1000);}
catch(InterruptedException iee)
{ System.out.println("gettting innterupted exctpion");
} } }}
84
class ThreadDemo
public static void main(String[] args)
{ MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start(); try
{ t1.join();
}
catch (InterruptedException ie)
{ System.out.println("interrupted Exception");
} t2.start(); } };
85
isAlive():- used to check whether the thread is live or not.
Public Boolean isAlive()
86
Inter process communication
wait
• Object wait methods has three variance, one which waits indefinitely for any
other thread to call notify or notifyAll method on the object to wake up the
current thread. Other two variances puts the current thread in wait for specific
amount of time before they wake up.
notify
• notify method wakes up only one thread waiting on the object and that thread
starts execution. So if there are multiple threads waiting for an object, this
method will wake up only one of them. The choice of the thread to wake
depends on the OS implementation of thread management.
notifyAll
• notifyAll method wakes up all the threads waiting on the object, although which
one will process first depends on the OS implementation.
87
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
88
synchronized void deposit(int amount){
System.out.println("going to deposit...");
89
• class Test{
• public static void main(String args[]){
• final Customer c=new Customer();
• new Thread(){
• public void run(){c.withdraw(15000);}
• }.start();
• new Thread(){
• public void run(){c.deposit(10000);}
• }.start();
•
• }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
90
Java.io is a package which contains number of classes by using that classes we are
able to send the data from one place to another place.
In java language we are transferring the data in the form of two ways:-
Byte format
Character format
Stream/channel:-
It is acting as medium by using steam or channel we are able to send particular
data from one place to the another place
Streams are two types:-
• Byte oriented streams.(supports byte formatted data to transfer)
• Character oriented stream.(supports character formatted data to transfer)
91
Byte oriented streams:-
Java.io.FileInputStream
To read the data from the destination file to the java application we have to use
FileInputSream class.
To read the data from the .txt file we have to read() method.
Java.io.FileOutputStream:-
To write the data to the destination file we have to use the FileOutputStream.
To write the data to the destination file we have to use write() method.
92
93
• Byte Streams
• programs use byte streams to perform input and output of 8-bit bytes. All byte
stream classes are descended from InputStream and OutputStream.
• There are many byte stream classes. To demonstrate how byte streams work,
we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream.
Other kinds of byte streams are used in much the same way; they differ mainly
in the way they are constructed.
94
• Character Streams
• The Java platform stores character values using Unicode conventions. Character
stream I/O automatically translates this internal format to and from the local
character set. In Western locales, the local character set is usually an 8-bit
superset of ASCII.
• For most applications, I/O with character streams is no more complicated than
I/O with byte streams. Input and output done with stream classes automatically
translates to and from the local character set. A program that uses character
streams in place of byte streams automatically adapts to the local character set
and is ready for internationalization — all without extra effort by the
programmer.
• If internationalization isn't a priority, you can simply use the character stream
classes without paying much attention to character set issues. Later, if
internationalization becomes a priority, your program can be adapted without
extensive recoding.
95
• Character streams are often "wrappers" for byte streams. The character stream
uses the byte stream to perform the physical I/O, while the character stream
handles translation between characters and bytes. FileReader, for example,
uses FileInputStream, while FileWriter uses FileOutputStream.
• There are two general-purpose byte-to-character "bridge"
streams: InputStreamReader and OutputStreamWriter. Use them to create
character streams when there are no prepackaged character stream classes that
meet your needs.
96
• Line-Oriented I/O
• Character I/O usually occurs in bigger units than single characters. One common
unit is the line: a string of characters with a line terminator at the end. A line
terminator can be a carriage-return/line-feed sequence ("\r\n"), a single
carriage-return ("\r"), or a single line-feed ("\n"). Supporting all possible line
terminators allows programs to read text files created on any of the widely used
operating systems.
97
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class CopyLines
{
public static void main(String[] args) throws IOException
{ BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
98
while ((l = inputStream.readLine()) != null)
{
outputStream.println(l);
} } finally
{
if (inputStream != null)
{
inputStream.close();
}
if (outputStream != null)
{
outputStream.close();
}}}}
99
• Buffered Streams
• Most of the examples we've seen so far use unbuffered I/O. This means each read or
write request is handled directly by the underlying OS. This can make a program
much less efficient, since each such request often triggers disk access, network
activity, or some other operation that is relatively expensive.
• To reduce this kind of overhead, the Java platform implements buffered I/O streams.
Buffered input streams read data from a memory area known as a buffer; the native
input API is called only when the buffer is empty. Similarly, buffered output streams
write data to a buffer, and the native output API is called only when the buffer is full.
• A program can convert an unbuffered stream into a buffered stream using the
wrapping idiom we've used several times now, where the unbuffered stream object is
passed to the constructor for a buffered stream class. Here's how you might modify
the constructor invocations in the CopyCharacters example to use buffered I/O:
• inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream =
new BufferedWriter(new FileWriter("characteroutput.txt"));
• There are four buffered stream classes used to wrap unbuffered
streams: BufferedInputStream and BufferedOutputStream create buffered byte
streams, while BufferedReader and BufferedWriter create buffered character streams.
10
0
• Data Streams
• Data streams support binary I/O of primitive data type values
(boolean, char, byte, short, int, long, float, and double) as well as String values.
All data streams implement either the DataInput interface or
theDataOutput interface. This section focuses on the most widely-used
implementations of these interfaces, DataInputStream and DataOutputStream.
• The DataStreams example demonstrates data streams by writing out a set of
data records, and then reading them in again. Each record consists of three
values related to an item on an invoice, as shown in the following table:
10
1
public class Student {
private String name;
private boolean gender; // true is male, false is female
private int age;
private float grade;
public Student() {
}
10
2
public String getName() {
return this.name;
}
10
3
public void setAge(int age) {
this.age = age;
}
10
4
import java.util.*;
import java.io.*;
public class StudentRecordReader {
DataInputStream dataInput;
try {
while (true) {
String name = dataInput.readUTF();
boolean gender = dataInput.readBoolean();
int age = dataInput.readInt();
10
5
float grade = dataInput.readFloat();
dataInput.close();
return listStudent;
}
10
6
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please provide input file");
System.exit(0);
}
try {
StudentRecordReader reader = new StudentRecordReader(inputFile);
10
7
for (Student student : listStudent) {
System.out.print(student.getName() + "\t");
System.out.print(student.getGender() + "\t");
System.out.print(student.getAge() + "\t");
System.out.println(student.getGrade());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
10
8
import java.util.*;
import java.io.*;
public class StudentRecordWriter {
DataOutputStream dataOutput;
10
9
public void save() throws IOException {
dataOutput.close();
}
11
0
try {
StudentRecordWriter writer = new StudentRecordWriter(outputFile);
writer.save();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
11
1
Socket programming
The term network programming refers to writing programs that execute across
multiple devices (computers), in which the devices are all connected to each other
using a network.
• The java.net package provides support for the two common network protocols −
• TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
• UDP − UDP stands for User Datagram Protocol, a connection-less protocol that
allows for packets of data to be transmitted between applications.
• Socket Programming
• Sockets provide the communication mechanism between two computers using
TCP. A client program creates a socket on its end of the communication and
attempts to connect that socket to a server.
11
2
The java.net.Socket class represents a socket, and the java.net.ServerSocket class
provides a mechanism for the server program to listen for clients and establish
connections with them.
• The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
• The server invokes the accept() method of the ServerSocket class. This method
waits until a client connects to the server on the given port.
• After the server is waiting, a client instantiates a Socket object, specifying the
server name and the port number to connect to.
• The constructor of the Socket class attempts to connect the client to the
specified server and the port number. If communication is established, the client
now has a Socket object capable of communicating with the server.
• On the server side, the accept() method returns a reference to a new socket on
the server that is connected to the client's socket.
11
3
After the connections are established, communication can occur using I/O streams.
Each socket has both an OutputStream and an InputStream. The client's
OutputStream is connected to the server's InputStream, and the client's
InputStream is connected to the server's OutputStream.
11
4
Java Socket Programming
11
5
TCP Client/Server Interaction
Client
1. Create a TCP socket
2. Communicate
3. Close the connection
Server
1. Create a TCP socket
2. Repeatedly:
• Accept new connection
• Communicate
11
6
Socket Communication
11
7
Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.
• Socket class
• A socket is simply an endpoint for communications between the machines. The
Socket class can be used to create a socket.
• Important methods
Method Description
1) public InputStream returns the InputStream
getInputStream() attached with this socket.
2) public OutputStream returns the OutputStream
getOutputStream() attached with this socket.
3) public synchronized void closes this socket
close()
11
8
• ServerSocket class
• The ServerSocket class can be used to create a server socket. This object is
used to establish communication with the clients.
Important methods
Method Description
1) public Socket accept() returns the socket and
establish a connection between
server and client.
2) public synchronized void closes the server socket.
close()
11
9
Socket Programming with UDP
• UDP
• Connectionless and unreliable service.
• There isn’t an initial handshaking phase.
• Doesn’t have a pipe.
• transmitted data may be received out of order, or lost
12
0
• import java.io.*;
• import java.net.*;
• public class MyServer {
• public static void main(String[] args){
• try{
• ServerSocket ss=new ServerSocket(6666);
• Socket s=ss.accept();//establishes connection
• DataInputStream dis=new DataInputStream(s.getInputStream());
• String str=(String)dis.readUTF();
• System.out.println("message= "+str);
• ss.close();
• }catch(Exception e){System.out.println(e);}
• }
• }
12
1
• import java.io.*;
• import java.net.*;
• public class MyClient {
• public static void main(String[] args) {
• try{
• Socket s=new Socket("localhost",6666);
• DataOutputStream dout=new DataOutputStream(s.getOutputStream());
• dout.writeUTF("Hello Server");
• dout.flush();
• dout.close();
• s.close();
• }catch(Exception e){System.out.println(e);}
• }
• }
12
2
import java.io.*;
import java.net.*;
class UDPServer
{ public static void main(String args[]) throws Exception
{ DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{ DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket); String sentence = new String(
receivePacket.getData());
12
3
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
12
4
import java.io.*;
import java.net.*;
class UDPClient
{ public static void main(String args[]) throws Exception
{ BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
12
5
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close(); } }
12
6
Socket Function Calls
12
7