0% found this document useful (0 votes)
4 views20 pages

Java Servlets

The document discusses various types of errors in programming, categorizing them into compile-time and run-time errors, and explains exceptions in Java, including checked and unchecked exceptions. It also covers exception handling mechanisms, multi-catch statements, nested try statements, and the use of 'throw' and 'throws' keywords. Additionally, it describes thread creation, life cycle, priorities, synchronization, and the importance of managing concurrent execution in Java.

Uploaded by

soloh.2nd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Java Servlets

The document discusses various types of errors in programming, categorizing them into compile-time and run-time errors, and explains exceptions in Java, including checked and unchecked exceptions. It also covers exception handling mechanisms, multi-catch statements, nested try statements, and the use of 'throw' and 'throws' keywords. Additionally, it describes thread creation, life cycle, priorities, synchronization, and the importance of managing concurrent execution in Java.

Uploaded by

soloh.2nd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

CHAPTER – 5

5.1 Explain the types of errors

Error:

Errors are mistakes in syntax or Logic. An error may producean incorrectoutputor


terminates theexecution of theprogramabruptly oreven may causethesystem to crash.

Errors may broadly classified intotwocategories

1. Compile -timeerrors
2. Run – time errors

Compile – time errors:

All syntax errors will bedetected and displayed by thejava compilerand therefore these
errors are known as compile timeerrors. Whenever the compilerdisplaysan error,it will
not create the .class file.

Most of thecompiletimeerrors areduetotyping mistakes. Examples are

Missing semicolons,
Mismatch of brackets in classes and methods,
Misspelling of identifiersand keyboards,
Missing double quotes in strings,
Use of undeclared variables,etc.,
Example:
class compiletime
{
public static void main(String args[])
{
System.out.println( “compile timeerror:” ) //gives compiletime
error,missing semicolon
}
}
Run – time errors:
Someerrors aredetected by the java run timesystem atrun timeis known as run time
errors. When therun timeerrors generated produceincorrect resultorterminatethe
program.
Most common run timeerrors are
Dividing an integer by zero,
Accessing an element thatis out of bounds of an array,etc.,
Example:
Class runtime
{
Public static void mian(String args[])
{
inta=10,b=0;
intc=a/b; //gives run timeerror
System.out.println(c);
}
}
5.2 Define Exception and how to deal with it and Types of exceptions
Exception:
An exception is a abnormal condition arises in a sequence of codeatrun timeis known as
exception.
(Or)
Java exceptionis an object that describes exceptionalcondition thathas generated in a
piece of code.

Whenan exceptional condition arises,an objectrepresenting thatexception is created


and thrown in themethod that caused theerror. That method may choosetohandle the
exception itself,orpassit on. Eitherway atsome point,theexceptionis caughtand
processed. Exceptions can be generated by the java run timesystem,orthey canbe
manually generated by your code.
Java exceptionhandling is managed via fivekeywords
try,
catch,
throw,
throws
and finally.
Types of Java Exceptions

There are mainly two types of exceptions and according to Oracle there are three
Exceptions

1. Checked Exceptions
2. Unchecked Exceptions
3. Error

1. Checked Exceptions:
Theses exceptions are explicitly handled in thecode itself withthehelp of try-catch
blocks. Checked exceptionsareextended from the java. lang. Exception class.
Checked exceptions arechecked at compile-time.
ClassNotFoundException
InterruptedException
IllegalAccessException etc.,
2. Unchecked Excetions:
These exceptions are not essentially handled in theprogramcode,instead thejvm
handlessuch exceptions. Unchecked exceptions are extended from thejava.
Lang. RuntimeException class. Unchecked exceptions arenot checked at
compile-time,but they arechecked at runtime.
ArithmeticException
ArrayIndexOutOfBooundException
IndexOutOfBoundExceptions
NumberFormatExceptionetc.,
3. Error:
Error isirrecoverable.
Stack over flow is anexample of error.

5.3 Explain the general form of exception- handling block

General formof exception handling


try
{
Statements // generates an exception
}
catch(Exception-type e)
{
Statement//processes theexception
}
Try block can have oneormorestatements thatcould generatean exception. If any
one statementgenerates an exception,theremaining statementsin theblock are
skipped and execution jumps to the catch block thatis placed next to the try block.
Thecatch block toocanhaveoneor morestatements that are necessary to
processtheexception. Every try statement should be followed by at least one
catchstatement,otherwisecompiletime erroroccurs.
Example:
class Demo
{
public static void main(String args[])
{
try
{
int a=0,b=40,c;
c=b/a;
System.out.println("this will benotprinted");
}
catch(ArithmeticException e)
{
System.out.println("divideby Zero");
}
System.out.println("aftre catch block");
}
}

5.4 Explain the conceptof Multi – catch statements with example program

Atry block can be followed by one or morecatchblocks,Eachcatching a different typeof


exception. When an exception is thrown,each catch statement is inspected inorder,and
thefirstonewhosetypematches thatof the exception isexecuted. Afteronecatch
statementexecutes,the others are bypassed and executioncontinues after the try/catch
block.

General form:
try
{
Statements // generates an exception
}
catch(Exception-type e)
{
Statement//processes theexception
}
catch(Exception-type e)
{
Statement//processes theexception
}
catch(Exception-type e)
{
Statement//processes theexception
}
Example:

public class Arithmetic


{
public static void main(String args[])
{
try
{
int a[]={1,2,3};
int b=0;
int c=a[2]/b;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("exception");
}
catch(ArithmeticException e)
{
System.out.println("hi");
}

}
}
5.5 Explain Nested try statements
Thetry statement can benested thatis,a try statement can be insidetheblock of another
try. Each time a try statementis entered,thecontextof that exception is pushed on the
stack. If an inner try statement does not have a catch handlerfora particularexception,the
stack is unwound and thenext try statementscatch handlers areinspected for a match.
This continues until oneof thecatch statements succeedsoruntilall of thenested try
statementsareexhausted. If no catch statementmatches,then javarun – timesystem
will handletheexception.
General form:
try
{
Statement1;
Statement2;
try
{
Statement1;
Statement2;
}
catch(Exception e)
{

Statement1;
Statement2;
}
}
catch(Exception e)
{
Statement1;
Statement2;

Example:
class Nesttry
{
public static void main(String args[])
{
try
{
int a[]={1,2,3,4};
System.out.println(a[2]);
try
{
int x=a[2]/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmeticexception occurs");
}

}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("arrayindexoutoutofbound exception occurs");
}
System.out.println("end");
}
}

5.6 Explain throw and throws clauses

throw:

The throwkeyword throwtheexceptionexplicitly from a method ora block of code.

Thegeneral form is

throw Throwableinstance;

Here, Throwableinstancemustbean object of type Throwableor subclassof Throwable.

Therearetwoways you canobtain aThrowble object:

 Using a parameterintoa catch clause ,or


Ex: throw e;
 Creating onewith new operator
Ex: throw new NullPointerException( “demo” );

Example:

class Throw
{
static void fun()
{
try
{
thrownewNullPointerException("invalid useof null reference");
}
catch(NullPointerException e)
{
System.out.println("catch insidefun");
throwe;
}
}
public static void main(String args[])
{

try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("recaught:"+e);
}
}
}

throws:
the throws keyword is used in method signature to declare the exceptions that can occur
in the statements present in themethod.
General formis
Type method_name(parameter_list) throws exception_list
{
// body of method
}
Here, exception _listis a comma separated list of theexceptions that a method canthrow.
Example:
class Thows
{

static void fun() throwsArithmeticException


{

inta=10/0;
System.out.println("end");
}
public static void main(String args[])
{
try
{
fun();
}
catch(ArithmeticException e)
{
System.out.println("handled");
}
}
}
Throw throws

The'throw'keyword is used toexplicitly The'throws'keyword is used in themethod


throwan exception fromwithin a block of signaturetodeclaretheexceptions thata
code or a method. method can potentially throw.

The'throw'keyword can only throw a single We can declaremultipleexceptions using


exception at atime. throws keyword thatcan bethrown by the
method.

The'throw'keyword is followed by the The'throws'keyword is followed by the


instancevariable. names of the exception classes.

The'throw'keyword should beused within The'throws'keyword should beused within


thebody of a method. themethod signature.
Multi threaded Program:

Multithreaded program contains twoor moreparts that runs concurrently. Where each
part of suchprogram is called thread. Each thread has separatepathof execution.

or

Program contains multipleflow of controls is called multi threaded program

5.8 DefineThread and Life cycle of thread

Thread:

Thread is a lightweightprocess it has singleflow of control.

Life cycle of thread

In Java, a thread always exists in any oneof thefollowing states. Thesestates are:

New Born state:

Whenwe createthread object,then thethread is born and is said tobein new born state.
thethread is not yet scheduled for running. At this state,wecan doonly one of the
following

 Scheduleit for running using start( ) method


 Kill itusing stop( ) method

Runnable state:
In this statethethread is ready forexecution and is waiting fortheavailability of the
processor. Thatis,thethread has joined thequeueof threads thatarewaiting for
execution. If all threads haveequal priority, then they are given timeslots for execution in
firstcomefirstservemanner.

However,if wewant athread torelinquish controltoanotherthread using yield( ) method.

Running state:

Running means thattheprocessor has given its time to the thread for its execution. The
thread runs until it relinquishes controlon its own or itis pre-empted by higherpriority
thread.

 Arunning thread mayrelinquish itscontrol in oneof the following situations.


 Suspend thethread duetocertain reason using suspend( ) method. Revived by
using resume( ) method
 Thread has beenmade to sleep for a specified timeperiod using sleep( time )
method. Wheretime isin milliseconds. Thethread re-enters the runnable stateas
soon as this timeperiod is elapsed.
 Thread has beentold to wait until someevents occurs using wait( ) method. The
thread canbescheduled torun againusing notify( ) method.

Blocked state:

Thethreads arein blocked state when the thread is suspended, sleeping,orwaiting in


order to satisfy certain requirements. Itis a not runnable state.

Dead state:

Aftercompletion of execution thread enters intodead state

5.9 Discuss aboutthread Priorities


Thread priorities are used by thread scheduler to decide when each thread should
be allowed torun. Java assigns priority to eachthread. Threads of equal priority should get
equalaccess to the processoron first-comefirstservebasis.
Java permits us to set the priority of thread using setPriority( ) method as follows
Threadname.setPriority(intnum);
Here, int num is an integer value to which the thread priority is set. Thread class defines
Priority constants
MIN_PRIORITY =1
NORM_PRIORITY=5
MAX_PRIORITY=10
int num may assume one of these constants or any value between 1 and 10. The default
priority is NORM_PRIORITY.
Toobtainthecurrentthread priority by calling getPriority( ) method of Thread class.
Example:
class ThreadDemoextends Thread
{
String s;
ThreadDemo(String msg)
{
s=msg;
}
public void run()
{
System.out.println("Thread:"+s);
}
public static void main(String[] args)
{
ThreadDemot1 = new ThreadDemo("t1");
ThreadDemot2 = new ThreadDemo("t2");
ThreadDemot3 = new ThreadDemo("t3");
System.out.println("t1 thread priority :"+t1.getPriority());
System.out.println("t2 thread priority :"+t2.getPriority());
System.out.println("t3 thread priority :"+t3.getPriority());
t1.setPriority(t1.MAX_PRIORITY);
t2.setPriority(t2.MIN_PRIORITY);
t3.setPriority(t3.NORM_PRIORITY);
System.out.println("t1 thread priority : "+ t1.getPriority());
System.out.println("t2 thread priority : "+ t2.getPriority());
System.out.println("t3 thread priority : "+ t3.getPriority());
t1.start();
t2.start();
t3.start();

}
}

5.10 Explain the process of creating thread using Thread class and Runnable interface.
Create aThread by instantiating an object of typeThread. Therearetwo ways tocreatea
thread:
1. By extending Thread class
2. By implementing Runnableinterface.
1. By extending Thread class:
The first way to create a thread is to create a new class that extends Thread class,
and then create an object of that class. The extending class must override therun( )
method, which is the entry point for the new thread. It must also call start( ) method
tobegin execution of thenewthread.
Example:

class HelloThread extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
HelloThread t=new HelloThread( );
t.start( );
}
}
2. By implementing Runnable interface:
The another way to create a thread is to create a class that implements the
Runnable interface. This interface contain run( ) method and it is implemented in
theclass.
If you are implementing runnable interface in your class, then you need to explicitly
create a Thread class object and pass the Runnable interface implemented class
object as aparameterin its constructor.
Example:
class HelloThread implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
HelloThread r=new HelloThread( );
Thread t=new Thread(r);
t.start( );
}
}
5.11 Creation of multiple threads
When we need to perform several tasks at a time, we can create multiple threads in
a program.
Example:
class Aextends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("thread A value:" +i);
}
}
}
class B extends Thread
{
public void run()
{
for(int i=5;i>1;i--)
{
System.out.println("thread B value:"+i);
}
}
}
class MultiThread
{
public static void main(String args[])
{
At1=new A();
Bt2=newB();
t1.start();
t2.start();
}
}

5.12 Explain the concept of Synchronization


When two or more threads access the resource at the same time then produce erroneous
and unforeseen results. To overcomethis weuseSynchronization

Synchronization in Java is the capability to control multiple threads to access the same
resourceat the same time. Whichmeans thatit allows onlyonethread at a particular time
tocompletegiven task entirely.
Key to Synchronization is the concept of the monitor. A monitor is an object that is used as
a lock. Only one thread can own a monitor at a given time. When a thread acquires a lock
then enters the monitor. All other threads attempting to enter the locked monitor will be
suspended until thefirstthread exits the monitor.

Synchronizeyourcode using Synchronized keyword.

Example:

class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
}
}
}
}
class MyThread1 extends Thread
{
Tablet;
MyThread1(Tablet)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}

}
class MyThread2 extends Thread
{
Tablet;
MyThread2(Tablet)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class Syncronization
{
public static void main(String args[])
{
Tableobj= newTable();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

5.13 Explain Inter Thread communication


Inter thread communication can bedefined as exchange the message between two or
morethreads via thewait( ),notify( ) and notifyall( ) methods.

In theInter thread communication mechanism a thread paused running in thelocked


monitorand released controltoenteranotherthread in thesamemonitor and waits until it
invokes notify( ) method.

wait( ): causes current thread towaituntilanotherthread invokes notify( ) method.

notify( ): resumes thefirst thread thatwent into sleep mode.

notifyall( ): resumes allthethreads thatarein sleep mode.

Example:

class Circle
{
float radious=0.0f;
synchronized void output()
{
System.out.println("output method invoked for displaying area of circle:");
if(radious==0.0f)
{
System.out.println("waiting for inputradious");

try
{
wait();
}
catch(Exception e)
{
}
}
System.out.println("Area = "+3.14*radious*radious);
}
synchronized void input(floatr)
{
System.out.println("inputting radious:");
radious=r;
System.out.println("Radious valuereceived");
notify();
}
}
class Inter
{
public static void main(String args[])
{
Circlec=newCircle();
new Thread()
{
public void run()
{
c.output();
}
}.start();
new Thread()
{
public void run()
{
c.input(2.5f);
}
}.start();
}
}

5.14 Describe isAlive( ), join( ), suspend( ), resume( ) methods

isAlive( ):

This method is belongs to Thread class and it determines the thread is alive or not and
returns Boolean value. It returns true if thread is alive otherwise returns false.

Its general form is shown here:

final boolean isAlive( )

program:

class IsAlive extends Thread


{
public void run()
{

}
public static void main(String[] args)
{
IsAlive t1=new IsAlive();
IsAlive t2=new IsAlive();
System.out.println(t1.isAlive()); //returns false as thread is not yet
started
t1.start();
t2.start();
System.out.println(t2.isAlive());// returns true as thread is started
}
}
Join ( ):
Suspend( ) and resume( ) methods:
These methods are defined by Thread class. The suspend method is used to suspend
or pause the thread temporarily and revived when the resume( ) method is invoked.
Program:
class Mythread1 extends Thread
{
public void run()
{
for(i=1;i<=5;i++)
{
System.out.println(i);
}

}
}
class Mythread2 extends Thread
{
public void run()
{
for(i=5;i>=1;i--)
{
System.out.println(i);
}

}
}
class Suspend
{

public static void main(String args[])


{
Mythread1 t1=new Mythread1();
Mythreda2 t2=new Mythread2();
t1.start();
t2.start();
t1.suspend();
t1.resume();
}
}
5.15 Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is
acquired by another thread and second thread is waiting for an object lock that is
acquired by first thread. Here, both threads are waiting for each other to release the
lock, this situation is called deadlock.
Program:
class Deadlock
{
String s1="veera";
String s2="Nirmala";
Thread t1=new Thread()
{
public void run()
{
while(true)
{
synchronized(s1)
{
try
{

System.out.println(Thread.currentThread().getName()+"locked"+s1);
Thread.sleep(1000);
}
catch(Exception e)
{
}
synchronized(s2)
{

System.out.println(Thread.currentThread().getName()+"locked"+s2);
System.out.println(s1+s2);
}
}
}
}
};
Thread t2=new Thread()
{
public void run()
{
while(true)
{
synchronized(s2)
{

System.out.println(Thread.currentThread().getName()+"locked"+s2);
synchronized(s1)
{

System.out.println(Thread.currentThread().getName()+"locked"+s1);
System.out.println(s1+s2);
}
}
}
}
};
public static void main(String args[])
{
Deadlock d1=new Deadlock();
d1.t1.start();
d1.t2.start();
}
}

You might also like