Unit-Iii Java-1
Unit-Iii Java-1
Compile time errors: These are syntactical errors found in the code, due to
which a program fails to compile for example, forgetting a semicolon(;) at the
end of a java statement or writing a statement without proper syntax will result
in compile time error.
Run Time errors: All logical errors are called runtime errors (or) these are the
errors happen at runtime because of inefficiency of computer system. All run
time errors are detected by JVM.
Checked Exceptions: The Exceptions that are checked at compile time by the
java compiler are called checked exceptions
Ex: No such method Exception
Class not found exception
Unchecked Exceptions: The Exceptions that are checked by the JVM at run
time are called Unchecked Exceptions.
Ex: ArithmeticException.
ArrayIndexOutOfBoundsException.
TerminationModel
In termination model the code after the point at which exception occurs (throw
point) will not be executed. That means execution is terminated at that point at
which exception occurs.
The termination Model works as follows:
1. The exception is thrown
2. Try block has expired.
3. Flow of control proceeds, it is transferred to the nearest exception handler
that can handle the type of exception encountered.
4. Program control does not return to throw point.
Resumptive Model:
The resumptive model is a model in which exception handler will try to clean
up the environment caused from exception and will try to restart the exception.
import java.util.*;
public class UncaughtExceptionExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
}
When we execute the above code, it produce the following output for the value
a = 10 and b = 0.
Using try and catch:
Step 1. The programmer should observe the statements in his program where
there may be a possibility of exceptions such statements should be written
inside a try block.
Syntax:
try{
Statements;
}
Step 2.The programmer should write the catch block where he should display
the exception details to the user.This helps the user to understand that there is
some error in the program.The programmer should also display amessage
regarding what can be done to avoid this error.
Syntax:
catch(Exceptionclass ref)
{
Statements;
}
Example:
Import java.lang.*;
class Simple
{
public static void main(String args[])
{
try{
int data=50/0;
System.out.println(“data is”+data);
}catch(ArithmeticException e)
{
System.out.println(“divide by zero error”);
}
System.out.println("rest of the code...");
}
}
Output:
divide by zero error
rest of the code...
Multiple catch Blocks:
In some cases more than one exception could be raised by a single piece
of code .To handle this type of situation you can specify two or more catch
statements. Each catching a different type of exception.
Syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
Example:
class multexce
{
public static void main(String[] args)
{
int a=0;
try
{
int b=42/a;
int c[]={1};
c[50]=99;
}
catch (ArithmeticException e)
{
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae);
}
}
}
Nested try statements
A try block is placed inside the block of another try block is termed as
nested try block statements
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Example:
import java.lang.*;
class NTDemo
{
public static void main(String[] args)
{
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c;
try
{
c=a/b;
System.out.println("result is"+c);
}
catch (ArithmeticException e)
{
System.out.println("Divide by zero error");
}
}
catch (NumberFormatException e)
{
System.out.println("Incorrect type of data");
}
}
}
Output:
C:\>javac NTDemo.java
C:\>java NTDemo 10 0
Divide by zero error
C:\>java NTDemo 10 b
Incorrect type of data
Finally
The finally block is a block that is always executed. It is mainly used to perform
some important tasks such as closing connection, stream etc.
Syntax:
try {
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
finally
{
//The finally block always executes.
}
Example:
class Simple
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println(“welcome to exception handling");
}
System.out.println("rest of the code...");
}
}
Throw/Creating own exception sub classes.
Syntax is:
throw throwableInstance;
Example:
import java.lang.*;
class myown extends Exception
{
myown(int bal)
{
System.out.println("insufficient balanace"+bal);
}
}
class userexceDemo
{
public static void main(String args[])
{
try
{
int bal=400;
if(bal<500) throw new myown(bal);
else
System.out.println("transaction is allowed");
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
}
}
Output:
C:\NCM>javac userexceDemo.java
C:\NCM>java userexceDemo
insufficient balanace400
Exception occured: myown
Throws
If a method does not handle a checked exception, the method must
declare it using the throws keyword.
Example:
import java.lang.*;
import java.io.*;
class ThrowsDemo
{
public static void main(String args[]) throws Exception
{
int a,b,c;
BufferedReader br=new BufferedReader(newInputStreamReader(System.in));
System.out.println("Enter a value");
a=Integer.parseInt(br.readLine());
System.out.println("Enter b value");
b=Integer.parseInt(br.readLine());
c=a/b;
System.out.println("Division is"+c);
}
}
Output:
C:\NCM>javac ThrowsDemo.java
C:\NCM>java ThrowsDemo
Enter a value
30
Enter b value
6
Division is5
Built in Exceptions are the exceptions which are available in Java. These
Exceptions are suitable to explain error situations. Important built in
exceptions are.
Multitasking
Multitasking is the feature that allows the computer to run two or more
programs concurrently.
Types of multitasking
Process-based
Thread-based
Process-based
A process is a program in execution. Process based multitasking is the
feature that allows your computer to run two or more programs concurrently.
For ex process based multitasking enables you to run the java compiler at the
same time that you are using a text editor. In process based multitasking, a
program is the smallest unit of code that can be dispatched by the scheduler
Thread based
In a thread based multitasking environment, the thread is the smallest
unit of dispatchable code. This means that a single program can perform two or
more tasks simultaneously. For instance, a text editor can format text at the
same time that it is printing, as long as these two actions are being performed
by two separate threads. Thus process based multitasking deals with the big-
picture, and thread based multitasking handles the details.
Differences between thread-based multitasking and process-based
multitasking
Multithreading Multiprocessing
1.Thread is a fundamental unit of 1.Programor process is a fundamental
multithreading unit of multiprocessing environment.
2.Multiple parts of a single program 2.Multiple programs get executed in
gets executed in multithreading multiprocessing environment.
environment.
3.During multithreading the processor 3.During multiprocessing the
switches between multiple threads of processor switches between multiple
the program programs or processors.
4.It is cost effective because CPU can 4.It is expensive because when a
be shared among multiple threads at a particular process uses CPU other
time. processes has to wait.
5.It is high efficient 5.It is less efficient in comparison with
multithreading.
6.It helps in developing efficient 6.It helps in developing efficient
application programs operating system programs.
2.The thread remains in this state until the threads start method is called. This
causes the thread to enter the ready state
3.The highest priority ready thread enters the running state when the system
assigns a processor to the thread i.e., the thread begins executing.
4.When running thread calls wait the thread enters into a waiting state for the
particular object on which wait was called. Every thread in the waiting state for
a given object becomes ready on a call to notify all by another thread
associated with the object.
5.When a sleep method is called in a running thread that thread enters into the
suspended (sleep) state. A sleeping thread becomes ready after the designated
sleep time expires. A sleeping thread cannot use a processor even if one is
available.
6.A thread enters the dead state when its run() method complete or terminates
for any reason.
7.One common way for running thread to enter the blocked state is when the
thread issues an input or output waits for completes. A blocked thread can’t
use processors even if one is available.
Thread Constructors
Thread()
Thread(String ThreadName)
Thread(Runnable obj)
Thread( Runnable obj,String Name)
Thread(ThreadGroup tg,String ThreadName)
Thread Methods
String getNames() : it obtain the names of the Thread
void setName (String str): it sets the name of the thread.
int getPriority(): it obtains the priority of the thread.
void setPriority(): it sets the priority of the thread.
boolean is Alive(): Determines if a thread is still running or not
void sleep(long milliseconds) Suspend a thread for a period of time
void start(): Start a thread by calling its run method
void run(): It defines the code that constitutes the new thread. Whenever the
start() method executes it automatically call of run() method
void join(): this method waits until the thread on which it is called terminates
Thread currentThread(): it returns a reference to the currently executing
Thread.
void yield(): A thread can call the yield method to give other threads a chance to
execute.
ThreadGroup getThreadGroup(): It returns the name of the thread group which
contains currently running thread.
Main Thread
When a java program starts up,one thread begins running immediately.This
one is main thread,which is created by virtual machine.it is executed in the
program for first time.It must be the last thread to finish execution.
Creating Threads
Step1:create a class that extends thread class or implements runnable
interface.
Ex: class MyThread extends Thread
Step2: Write public void run() method with body.
Step3:create an object to the class and attach a thread to it.
Ex: MyThread m=new MyThread();
Thraed t=new Thread(m);
Step4:start the thread by using start() method
t.start();
Example:
import java.lang.*;
class MyThread extends Thread
{
public void run()
{
System.out.println("Welcome to VAAGESWARI");
}
}
class ThreadEx1
{
public static void main(String args[] )
{
MyThread m = new MyThread();
Thread t=new Thread(m);
t.start();
}
}
Output: Welcome to VAAGESWARI
2. Implementing the runnable interface
Example:
import java.lang.*;
class MyThread implements Runnable
{
public void run()
{
System.out.println("welcome to VAAGESWARI");
}
}
class ThreadEx2
{
public static void main(String args[] )
{
MyThread m = new MyThread();
Thread t=new Thread(m);
t.start();
}
}
Output: Welcome to VAAGESWARI
Example 2:
import java.lang.*;
class MyThread implements Runnable
{
public void run()
{
add();
sub();
}
void add()
{
int a,b,c;
a=10;b=20;
c=a+b;
System.out.println("sum is"+c);
}
void sub()
{
int a,b,c;
a=34;b=23;
c=a-b;
System.out.println("sub value is"+c);
}
}
class ThreadEx3
{
public static void main(String args[] )
{
MyThread m = new MyThread();
Thread t=new Thread(m);
t.start();
}
}
Output:
C:\>javac ThreadEx3.java
C:\>java ThreadEx3
sum is30
sub value is11
Thread Priorities:
When the threads are created and started, a thread scheduler program in JVM
will load them into memory and execute them. This scheduler will allot more
JVM time to those threads which are having higher priorities. Priorities are
represented by a number between 1 and 10. In most cases, thread scheduler
schedules the threads according to their priority (known as preemptive
scheduling).
The three priority constants defined in Thread class are:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY
is 1 and the value of MAX_PRIORITY is 10.
Example:
import java.lang.*;
class MyThread1 extends Thread
{
public void run()
{
add();
}
void add()
{
int a,b,c;
a=10;b=20;
c=a+b;
System.out.println("sum is"+c);
}
}
class MyThread2 extends Thread
{
public void run()
{
sub();
}
void sub()
{
int a,b,c;
a=10;b=20;
c=a-b;
System.out.println("sub is"+c);
}
}
class MyThread3 extends Thread
{
public void run()
{
mul();
}
void mul()
{
int a,b,c;
a=10;b=20;
c=a*b;
System.out.println("mul is"+c);
}
}
class ThreadPDemo
{
public static void main(String args[] )
{
MyThread1 m1 = new MyThread1();
Thread t1=new Thread(m1);
MyThread2 m2 = new MyThread2();
Thread t2=new Thread(m2);
MyThread3 m3 = new MyThread3();
Thread t3=new Thread(m3);
t1.setPriority(2);
t2.setPriority(1);
t3.setPriority(3);
t1.start();
t2.start();
t3.start();
}
}
Output:
C:\>java ThreadPDemo
sub is-10
sum is30
mul is200
Synchronizing Threads:
When a thread is already acting on an object, preventing any other thread from
acting on the same object is called “Thread Synchronization or thread safe. The
object on which the threads are synchronized is called synchronized object.
Thread synchronization is recommended when multiple threads are used on
the same object.
Class Table
{
void printTable(int n)//method not synchronized
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
Inter-thread communication
Cooperation (Inter-thread communication) is a mechanism in which a thread is
paused running in its critical section and another thread is allowed to enter (or
lock) in the same critical section to be executed.
wait()
notify()
notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread
invokes
the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
Method
public final void wait()throws InterruptedException: waits until object is
notified.
public final void wait(long timeout)throws InterruptedException:waits for the
specified amount of time.
3) notifyAll() method Wakes up all threads that are waiting on this object's
monitor.
Syntax:
public final void notifyAll()
import java.lang.*;
class Q
{
int n;
boolean busy=false;
synchronized int get()
{
if(!busy)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
busy=false;
notify();
return n;
}
synchronized void put(int n1)
{
if(busy)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
n=n1;
busy=true;
System.out.println("Put:"+n);
notify();
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
System.out.println("Press Control-c to stop");
}
}
Output: