Java Exception

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Introduction

Exception is an event that arises during the execution of the program, and it
terminates the program abnormally. It then displays system generated error
message.

Exception Handling:
Exception handling is the mechanism to handle the abnormal termination of
the program.
For example :ClassNotFoundException, NumberFormatException,
NullPointerException etc.

Need for Exception Handling:


A program rarely executes without any errors for the first time. Users may run
applications in unexpected ways. A program should be able to handle these
abnormal situations.
 Exception handling allows executing the code without making any changes to
the original code.
 It separates the error handling code from regular code.

Exception Hierarchy in Java:

Difference between error and exception

Error Exception
It cannot be caught. It can be handled by try and catch block.
Errors are by default unchecked Exception can be either checked or
type. unchecked type.
It is defined in java.lang.Error It is defined in java.lang.Exception
package. package.
Errors are generally caused by Exceptions are generally caused by
environment in which application is application itself.
running.

Dambal Sir (Sangola College,Sangola) 1


Example: StackOverflowError, Example: SQLException, IOException,
OutOfMemoryError etc. ClassCastException,
ArrayOutOfBoundException

Types of Exceptions

Java has two types of exceptions.


1. Checked exception
2. Unchecked exception

1. Checked Exceptions
 Checked exceptions are also known as compiled time exception, because such
exceptions occur at compile time.
 Java compiler checks if the program contains the checked exception handler
or not at the time of compilation.
 All these exceptions are subclass of exception class.
 Developer has overall control to handle them.
For example: SQLException, IOException, ClassNotFoundException etc.

Example : Sample program for checked exception

import java.io.File;
import java.io.PrintWriter;
public class Checked_Demo
{
public static void main(String args[])
{
File file=new File("E://abc.txt");
PrintWriter pw = new PrintWriter("file");
}
}

Output:
error: FileNotFoundException

2. Unchecked Exceptions
 Unchecked exceptions are also known as runtime exception.
 These include logic errors or improper use of API.
For example: ArrayIndexOutOfBoundException, NullPointerException,
ArithmeticException.

Example : Sample program for unchecked exception

class Uncheked_Demo
{
public static void main(String args[])
{
int a = 10;
int b = 0;
Dambal Sir (Sangola College,Sangola) 2
int c = a/b;
System.out.println(c);
}
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Built-in exceptions
Built-in exceptions are the exceptions which are available in Java libraries.
These exceptions are suitable to explain certain error situations. Below is the
list of important built-in exceptions in Java.
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic
operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the size of
the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is
not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing
, and it is interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object.
Null represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a
numeric format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either
negative than the size of the string
Examples of Built-in Exception:
Arithmetic exception
// Java program to demonstrate ArithmeticException
ClassArithmeticException_Demo
{ public static void main(String args[])
{ try
{

Dambal Sir (Sangola College,Sangola) 3


int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e)
{
System.out.println ("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0

NullPointer Exception
//Java program to demonstrate NullPointerException
ClassNullPointer_Demo
{ public static void main(String args[])
{ try
{
String a = null; //null value
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
}
 output:
NullPointerException..

StringIndexOutOfBound Exception
// Java program to demonstrate StringIndexOutOfBoundsException
ClassStringIndexOutOfBound_Demo
{ public static void main(String args[])
{ try
{
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("StringIndexOutOfBoundsException");
}
}
}

Output: StringIndexOutOfBoundsException

Dambal Sir (Sangola College,Sangola) 4


FileNotFound Exception
//Java program to demonstrate FileNotFoundException
Importjava.io.File;
Importjava.io.FileNotFoundException;
Importjava.io.FileReader;
classFile_notFound_Demo
{ public static void main(String args[])

{ try
{ // Following file does not exist
File file = new File("E://file.txt");
FileReaderfr = new FileReader(file);
}
catch (FileNotFoundException e)
{
System.out.println("File does not exist");
}
}}

Output:

File does not exist

NumberFormat Exception
// Java program to demonstrate NumberFormatException
ClassNumberFormat_Demo
{ public static void main(String args[])
{ try
{ // "akk" is not a number
Int num = Integer.parseInt ("akk") ;
System.out.println(num);
}
catch(NumberFormatException e)
{
System.out.println("Number format exception");
}
}
}

Output:

Number format exception

ArrayIndexOutOfBounds Exception
// Java program to demonstrate ArrayIndexOutOfBoundException
ClassArrayIndexOutOfBound_Demo
{ public static void main(String args[])
{ try
{ int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of size 5

Dambal Sir (Sangola College,Sangola) 5


}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println ("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds
There are five keywords used in Java for exception handling-
i. try
ii. catch
iii. throw
iv. throws
v. finally

The try block

The try block contains the code that might throw an exception. The try block
contains at least one catch block or finally block.

The catch block

A catch block must be declared after try block. It contains the error handling
code. A catch block executes if an exception generates in corresponding try
block.

Syntax

try
{
//code that cause exception;
}
catch(Exception_type e)
{
//exception handling code
}

Example : An examples to uses try and catch block in java

class TryCatchDemo
{
public static void main(String args[])
{
int a = 30, b = 3, c = 3;
int result1, result2;
try
{
Dambal Sir (Sangola College,Sangola) 6
result1 = a / (b - c);
}
catch(ArithmeticException ae)
{
System.out.println("Divided by zero: "+ae);
}
result2 = a / (b + c);
System.out.println("Result2 = "+result2);
}
}

Output :
Divided by zero: java.lang.ArithmeticException: / by zero
Result2 = 5

Example : A program to illustrate the uses of try and catch block

class ExceptionDemo
{
public static void main(String args[])
{
try
{
int arr[] = new int[5];
arr[2] = 5;
System.out.println("Access element two: " + arr[2]);
arr[7] = 10;
System.out.println("Access element seven: "+ arr[7]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown:" + e);
}
System.out.println("End of the block");
}
}

Output :
Access element two: 5
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
End of the block

Multiple catch blocks


If more than one exception is generated by the program then it uses multiple
catch blocks. A single try block can contain multiple catch blocks.
Syntax:
try
{
// code which generate exception
}
Dambal Sir (Sangola College,Sangola) 7
catch(Exception_type1 e1)
{
//exception handling code
}
catch(Exception_type2 e2)
{
//exception handling code
}

Example : A program illustrating multiple catch block using command


line argument

public class MultipleCatch


{
public static void main(String args[])
{
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a / b;
System.out.println("Result = "+c);
}
catch(ArithmeticException ae)
{
System.out.println("Enter second value except zero.");
}
catch (ArrayIndexOutOfBoundsException ai)
{
System.out.println("Enter at least two numbers.");
}
catch(NumberFormatException npe)
{
System.out.println("Enter only numeric value.");
}
}
}
Output:
10 5
Result = 2

10 0
Enter second value except zero.

5
Enter at least two numbers.

10 a
Enter only numeric value.

Dambal Sir (Sangola College,Sangola) 8


The finally block

 The code present in finally block will always be executed even if try block
generates some exception.
 Finally block must be followed by try or catch block.
 It is used to execute some important code.
 Finally block executes after try and catch block.
Syntax:
try
{
// code
}
catch(Exception_type1)
{
// catch block1
}
Catch(Exception_type2)
{
//catch block 2
}
finally
{
//finally block
//always execute
}

Example : A program to implement finally block

class FinallyTest
{
public static void main(String args[])
{
int arr[] = new int[5];
try
{
arr[7] = 10;
System.out.println("Seventh element value: " + arr[7]);
}
catch(ArrayIndexOutOfBoundsException ai)
{
System.out.println("Exception thrown : " + ai);
}
finally
{
arr[0] = 5;
System.out.println("First element value: " +arr[0]);
System.out.println("The finally statement is executed");
}
}
}

Dambal Sir (Sangola College,Sangola) 9


Output:
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
First element value: 5
The finally statement is executed

The throw keyword in Java

 The throw keyword in Java is used to explicitly throw our own exception.
 It can be used for both checked and unchecked exception.
Syntax:
throw new Throwable subclass;
Example : A program to illustrate throw keyword in java

public class ThrowTest


{
static void test()
{
try
{
throw new ArithmeticException("Not valid ");
}
catch(ArithmeticException ae)
{
System.out.println("Inside test() ");
throw ae;
}
}
public static void main(String args[])
{
try
{
test();
}
catch( ArithmeticException ae)
{
System.out.println("Inside main(): "+ae);
}
}
}
Output:
Inside test()
Inside main(): java.lang.ArithmeticException: Not valid

The throws keyword in Java

 The throws keyword is generally used for handling checked exception.


 When you do not want to handle a program by try and catch block, it
can be handled by throws.
 Without handling checked exceptions program can never be compiled.
 The throws keyword is always added after the method signature.

Dambal Sir (Sangola College,Sangola) 10


Example : A program to illustrate uses of throws keyword

public class ThrowsDemo


{ static void throwMethod1() throws NullPointerException
{ System.out.println ("Inside throwMethod1");
throw new NullPointerException ("Throws_Demo1");
}
static void throwMethod2() throws ArithmeticException
{
System.out.println("Inside throwsMethod2");
throw new ArithmeticException("Throws_Demo2");
}
public static void main(String args[])
{ try
{
throwMethod1();
}
catch (NullPointerException exp)
{
System.out.println ("Exception is: " +exp);
}
try
{
throwMethod2();
}
catch(ArithmeticException ae)
{
System.out.println("Exception is: "+ae);
}
}
}
Output:
Inside throwMethod1
Exception is: java.lang.NullPointerException: Throws_Demo1
Inside throwsMethod2
Exception is: java.lang.ArithmeticException: Throws_Demo2

Difference between throw and throws keyword in Java

Throw Throws
It is used to throw own It is used when program does not handle
exception. exception via try block.
It handles explicitly thrown It handles all exceptions generated by program.
exceptions.
Cannot throw multiple Declare multiple exception e.g.
exceptions. public void method() throws, IOException,
SQLException.
It is used within the method. It is used within method signature.
Dambal Sir (Sangola College,Sangola) 11
final

 final is a keyword.
 It is used to apply restriction on class, method and variables.
 final class cannot be inherited, final method cannot be overridden and final
variable cannot be changed.

finally

 finally is a block followed by try or catch block.


 finally block is executed whether exceptions are handled or not.
 We put clean up code in finally block.

finalize ()

 finalize is a method.
 This method is associated with garbage collection, just before collecting the
garbage by system.
 It is called automatically.

Creating Custom Exceptions:

 The exceptions that we create on our own are known as custom exception.
 These exceptions are created to generate a solution for anticipated errors as
per programmer’s need.
 A “Custom exception class” must be extended from “Exception class”.

Example : Program to create custom exception in Java

// CustomException.java

public class CustomException extends Exception


{
public CustomException(String msg)
{
super(msg);
}
}

// CustomDemo.java

public class CustomDemo


{
public static void main(String args[]) throws Exception
{
CustomDemo custom = new CustomDemo();
custom.display();
}
public void display() throws CustomException
{
Dambal Sir (Sangola College,Sangola) 12
for(int i=2;i<20;i=i+2)
{
System.out.println("i= "+i);
if(i==8)
{
throw new CustomException("My Exception Occurred");
}
}
}
}

Output:
i= 2
i= 4
i= 6
i= 8
Exception in thread "main" CustomException: My Exception Occurred
at CustomDemo.display(CustomDemo.java:11)
at CustomDemo.main(CustomDemo.java:4)

Multithreading

The process of executing multiple threads simultaneously is known


as multithreading.
 Multithreading means executing two parts of the same program concurrently.
 It is a part of multitasking.
 A program may contain more than one thread.
For Example: A browser can serve a web page while downloading a file. Each
of these actions is a thread.

Life Cycle of Thread

New State: Soon after the creation of a thread, it is said to be in the new state.
Dambal Sir (Sangola College,Sangola) 13
Runnable State: The life of a thread starts after invoking the start () method.
The start() method invokes the run () method.
Running State: When the thread is currently running, it is in the state of
running.
Wait State: When other threads are holding the resources, the current thread
is said to be in wait state
Dead State: When the thread has completed the execution of run () method, it
is said to be in dead state.

Creating Thread

There are two ways to create a thread in Java.


1. Extending the thread class.
2. Implementing runnable interface.

1. Extending Thread Class


Thread class has constructor and method to create and perform the operation
on class.
Program on using thread class

// MainThread.java

public class MyThread extends Thread


{
String message;
MyThread(String msg)
{
message=msg;
}
public void run()
{
for(int count=0;count<=5;count++)
{
System.out.println("Run method: " + message);
}
}
}
public class MainThread
{
public static void main(String[] args)
{
MyThread t1 = new MyThread("Run");
MyThread t2 = new MyThread("Thread");
t1.start();
t2.start();
}
}

Output:
Run method: Run
Dambal Sir (Sangola College,Sangola) 14
Run method: Run
Run method: Run
Run method: Run
Run method: Run
Run method: Run
Run method: Thread
Run method: Thread
Run method: Thread
Run method: Thread
Run method: Thread
Run method: Thread

2. Implementing Runnable Interface


Runnable interface is available in java.lang package. The purpose of Runnable
interface is to provide a set of rules common for objects to execute the
functionality while they are active.
Example : Sample program to implement runnable interface

class MyThread implements Runnable


{
String message;
MyThread(String msg)
{
message = msg;
}
public void run()
{
for(int count=0;count<=5;count++)
{
System.out.println("Run method: " + message);
}
}
}
public class MainMyThread
{
public static void main(String[] args)
{
MyThread dt1=new MyThread("Run");
MyThread dt2=new MyThread("Thread");
Thread t1 = new Thread(dt1);
Thread t2 = new Thread(dt2);
t1.start();
t2.start();
}
}

Output:
Run method: Thread
Run method: Run
Run method: Thread

Dambal Sir (Sangola College,Sangola) 15


Run method: Run
Run method: Thread
Run method: Run
Run method: Thread
Run method: Thread
Run method: Thread
Run method: Run
Run method: Run
Run method: Run

1) Java Thread Example by extending Thread class

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}

public static void main(String args[])


{
Multi t1=new Multi();
t1.start();
}
}

Output: thread is running...

2) Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}

public static void main(String args[])


{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output: thread is running...

Dambal Sir (Sangola College,Sangola) 16


Thread Methods in Java:

Following are the some important methods available in thread class.

Methods Description
public void start( This method invokes the run() method, which causes the
) thread to begin its execution.
public void run( ) Contains the actual functionality of a thread and is usually
invoked by start() method.
public static void Blocks currently running thread for at least certain
sleep (long millisecond.
millisec)
public static void Causes the current running thread to halt temporarily and
yield ( ) allow other threads to execute.
public static It returns the reference to the current running thread object.
Thread
currentThread ( )
public final void Changes the priority of the current thread. The minimum
setPriority (int priority number is 1 and the maximum priority number is
priority) 10.
public final void Allows one thread to wait for completion of another thread.
join (long
millisec)
public final Used to know whether a thread is live or not. It returns true
boolean isAlive ( ) if the thread is alive. A thread is said to be alive if it has
been started but has not yet died.
public void Interrupts the thread, causing it to continue execution if it
interrupt ( ) was blocked for some reason.

Thread Priorities:

Thread priorities is the integer number from 1 to 10 which helps to determine


the order in which threads are to be scheduled. It decides when to switch from
one running thread to another thread.

Priority range of MIN_PRIORITY is 1 and MAX_PRIORITY is 10. Default value


of NORMAL_PRIORITY is 5.
Example 1: Maximum Priority Thread
public class JavaSetPriorityExp1 extends Thread
{
public void run()
{
System.out.println("Priority of thread is: "+Thread.currentThread().getPriority());

}
Dambal Sir (Sangola College,Sangola) 17
public static void main(String args[])
{

JavaSetPriorityExp1 t1=new JavaSetPriorityExp1(); // creating one thread


t1.setPriority(Thread.MAX_PRIORITY); // print the max priority of this thread
t1.start(); // call the run() method

}
}

Example 2: Minimum Priority Thread


public class JavaSetPriorityExp2 extends Thread
{
public void run()
{
System.out.println("Priority of thread is: "+Thread.currentThread().getPriority());

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

JavaSetPriorityExp2 t1=new JavaSetPriorityExp2(); // creating one thread


t1.setPriority(Thread.MIN_PRIORITY); // print the min priority of this thread
t1.start(); // This will call the run() method
}
}
Example 3: Normal Priority Thread
public class JavaSetPriorityExp3 extends Thread
{
public void run()
{
System.out.println("Priority of thread is: "+Thread.currentThread().getPriority());

}
public static void main(String args[])
{
JavaSetPriorityExp3 t1=new JavaSetPriorityExp3(); // creating one thread
t1.setPriority(Thread.NORM_PRIORITY); //print the normal priority of thread
t1.start(); // starting the thread
}
}
Example 4: User define Priority Thread
public class JavaSetPriorityExp4 extends Thread
{
public void run()
{
System.out.println("running...");
}
public static void main(String args[])
{

Dambal Sir (Sangola College,Sangola) 18


JavaSetPriorityExp4 t1=new JavaSetPriorityExp4(); // creating thread
JavaSetPriorityExp4 t2=new JavaSetPriorityExp4();
t1.setPriority(4); // set the priority
t2.setPriority(7);

// print the user defined priority


System.out.println("Priority of thread t1 is: " + t1.getPriority());
System.out.println("Priority of thread t2 is: " + t2.getPriority());
t1.start(); // this will call the run() method

}
}

Output:

Priority of thread t1 is: 4


Priority of thread t2 is: 7
running...

// Java program to demonstrate getPriority() and setPriority()


import java.lang.*;
class ThreadDemo extends Thread
{
public void run()
{
System.out.println("Inside run method");
}

public static void main(String[]args)


{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();

System.out.println("t1 thread priority : " + t1.getPriority()); // Default 5


System.out.println("t2 thread priority : " + t2.getPriority()); // Default 5
System.out.println("t3 thread priority : " + t3.getPriority()); // Default 5

t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);

// t3.setPriority(21); will throw IllegalArgumentException


System.out.println("t1 thread priority : " + t1.getPriority());
System.out.println("t2 thread priority : " + t2.getPriority());
System.out.println("t3 thread priority : " + t3.getPriority());

// Main thread
System.out.print(Thread.currentThread().getName());

Dambal Sir (Sangola College,Sangola) 19


System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());

// Main thread priority is set to 10


Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());
}
}
Output:
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Main thread priority : 5
Main thread priority : 10

Synchronization in Java Thread:

What is Synchronization?
Synchronization is the process of allowing threads to execute one after another.
It provides the control to access multiple threads to shared resources.

Java supports multiple threads to be executed. Without synchronization, one


thread can modify a shared variable while another thread can update the same
shared variable, which can lead to significant error.

When a method is declared as synchronized, the threads hold the monitor for
that thread object. If any thread uses synchronized method then other threads
are blocked until that thread releases the monitor.

 Synchronization Block

It can be used to achieve synchronization on a specific resource of method.


Scope of the method is more than the synchronization block.

Syntax:
synchronized
{
// code
}
Example : Working of synchronization block

class SynchDemo
{
void printNumber(int n)
{
synchronized(this)
{
Dambal Sir (Sangola College,Sangola) 20
for(int i=1;i<=5;i++)
{
System.out.println(n+" * "+i+" = "+n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class MainThread1 extends Thread
{
SynchDemo t;
MainThread1(SynchDemo t)
{
this.t=t;
}
public void run()
{
t.printNumber(4);
}
}
class MainThread2 extends Thread
{
SynchDemo t;
MainThread2(SynchDemo t)
{
this.t=t;
}
public void run()
{
t.printNumber(10);
}
}
public class TestSynchronizedBlock
{
public static void main(String args[])
{
SynchDemo obj = new SynchDemo();
MainThread1 t1=new MainThread1(obj);
MainThread2 t2=new MainThread2(obj);
t1.start();
t2.start();
}
}

Dambal Sir (Sangola College,Sangola) 21


Output:
4*1=4
4*2=8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50

 Synchronization Method

If you declare any method as synchronized, it is known as synchronized


method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the
lock for that object and releases it when the thread completes its task.
//example of java synchronized method
class Table
{
synchronized void printTable(int n)//synchronized method
{ for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
Dambal Sir (Sangola College,Sangola) 22
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Inter Thread Communication:

Inter thread communication is used when an application has two or more


threads that exchange same information. Inter thread communication helps in
avoiding thread pooling.

Three methods used for thread communication are:


 wait ()
 notify ()
 notifyAll ()
1. wait (): It causes the current thread to wait until another thread invokes the
notify ( ) or notifyAll( ) method.

For example:
public final void wait () throws InterruptedException,
public final void wait (long timeout) InterruptedException

2. notify () : Wakes up the single thread waiting on the object monitor.

Syntax:
public final void notify ()

3. notifyAll () : Wakes up all threads waiting on the object monitor.

Syntax:
public final void notifyAll()
class Customer
{
int amount=10000;
Dambal Sir (Sangola College,Sangola) 23
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...");
}

synchronized void deposit(int amount)


{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

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

Dambal Sir (Sangola College,Sangola) 24


Java Thread start() method:

The start() method of thread class is used to begin the execution of thread. The
result of this method is two threads that are running concurrently: the current
thread (which returns from the call to the start method) and the other thread
(which executes its run method).

The start() method internally calls the run() method of Runnable interface to
execute the code specified in the run() method in a separate thread.

The start thread performs the following tasks:

o It stats a new thread


o The thread moves from New State to Runnable state.
o When the thread gets a chance to execute, its target run() method will
run.

Example 1: By Extending thread class

public class StartExp1 extends Thread


{
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
StartExp1 t1=new StartExp1();
// this will call run() method
t1.start();
}
}
Java Thread run() method:

The run() method of thread class is called if the thread was constructed using a
separate Runnable object otherwise this method does nothing and returns.
When the run() method calls, the code specified in the run() method is
executed. You can call the run() method multiple times.

The run() method can be called using the start() method or by calling the run()
method itself. But when you use run() method for calling itself, it creates
problems.

Example 1: call the run() method using the start() method

public class RunExp1 implements Runnable


{
Dambal Sir (Sangola College,Sangola) 25
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
RunExp1 r1=new RunExp1();
Thread t1 =new Thread(r1);
// this will call run() method
t1.start();
}
}
Java Thread resume() method:

The resume() method of thread class is only used with suspend() method. This
method is used to resume a thread which was suspended using suspend()
method. This method allows the suspended thread to start again.

Example

public class JavaResumeExp extends Thread


{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaResumeExp t1=new JavaResumeExp ();
JavaResumeExp t2=new JavaResumeExp ();
JavaResumeExp t3=new JavaResumeExp ();
// call run() method
t1.start();
t2.start();
t2.suspend(); // suspend t2 thread

Dambal Sir (Sangola College,Sangola) 26


// call run() method
t3.start();
t2.resume(); // resume t2 thread
}
}

Java Thread suspend() method:


The suspend() method of thread class puts the thread from running to waiting
state. This method is used if you want to stop the thread execution and start it
again when a certain event occurs. This method allows a thread to temporarily
cease execution. The suspended thread can be resumed using the resume()
method.
Syntax
public final void suspend()
Example
public class JavaSuspendExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
sleep(500);
// thread to sleep for 500 milliseconds
System.out.println(Thread.currentThread().getName());
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
JavaSuspendExp t1=new JavaSuspendExp (); // creating three threads
JavaSuspendExp t2=new JavaSuspendExp ();
JavaSuspendExp t3=new JavaSuspendExp ();

t1.start(); // call run() method


t2.start();
t2.suspend(); // suspend t2 thread
t3.start(); // call run() method

}
}
Output:
Thread-0
1
Dambal Sir (Sangola College,Sangola) 27
Thread-2
1
Thread-0
2
Thread-2
2
Thread-0
3
Thread-2
3
Thread-0
4
Thread-2
4

Networking in Java

Introduction

Networking is the concept of connecting multiple remote or local devices


together. Java program communicates over the network at application layer.
All the Java networking classes and interfaces use java.net package. These
classes and interfaces provide the functionality to develop system-independent
network communication.

The java.net package provides the functionality for two common


protocols:

TCP (Transmission Control Protocol)


TCP is a connection based protocol that provides a reliable flow of data between
two devices. This protocol provides the reliable connections between two
applications so that they can communicate easily. It is a connection based
protocol.

UDP (User Datagram Protocol)


UDP protocol sends independent packets of data, called datagram from one
computer to another with no guarantee of arrival. It is not connection based
protocol.

Networking Terminology

i) Request and Response


When an input data is sent to an application via network, it is called request.
The output data coming out from the application back to the client program is
called response.

ii) Protocol
A protocol is basically a set of rules and guidelines which provides the
instructions to send request and receive response over the network.
For example: TCP, UDP, SMTP, FTP etc.

Dambal Sir (Sangola College,Sangola) 28


iii) IP Address
IP Address stands for Internet protocol address. It is an identification number
that is assigned to a node of a computer in the network.
For example: 192.168.2.01
Range of the IP Address
0.0.0.0 to 255.255.255.255

iv) Port Number


The port number is an identification number of server software. The port
number is unique for different applications. It is a 32-bit positive integer
number having between ranges 0 to 65535.

v) Socket
Socket is a listener through which computer can receive requests and
responses. It is an endpoint of two way communication link. Every server or
programs runs on the different computers that has a socket and is bound to
the specific port number.

Java URL Class

URL stands for Uniform Resourse Locator. The URL provides the logically
understandable form of uniquely identifying the resource or address
information on the Internet.
The URL class provides a simple, concise API to access information over the
Internet.

URL Class Methods

Method Description
String Returns the authority part of the URL.
getAuthority()
int defaultPort() Returns the default port number of the protocol
associated with given URL.
String getFile() Returns the file name of the given URL.
String getHost() Returns the host name of the URL.
String getPath() Returns the complete path of the given URL.
int getPort() Returns the port number of the given URL. If it is not
applicable, it returns -1.
String getQuery() Returns the query part of the given URL.
String getProtocol() Returns the name of the protocol of the given URL.
Following program shows the different methods of URL class:

import java.net.*;
public class URLDemo
{
public static void main(String args[]) throws MalformedURLException
Dambal Sir (Sangola College,Sangola) 29
{
URL url = new URL("http://www.google.com/java.htm");
System.out.println("URL: " + url.toString());
System.out.println("Protocol: "+url.getProtocol());
System.out.println("path: " + url.getPath());
System.out.println("Port: "+url.getPort());
System.out.println("Host: "+url.getHost());
System.out.println("Authority: " + url.getAuthority());
System.out.println("File: "+url.getFile());
System.out.println("Query: "+url.getQuery());
System.out.println("HashCode: "+url.hashCode());
System.out.println("External form: "+url.toExternalForm());
}
}

Dambal Sir (Sangola College,Sangola) 30

You might also like