You are on page 1of 41

OOPS USING JAVA UNIT-2

UNIT-2

EXCEPTION HANDLING
In our daily life we will be committing so many mistakes. Similarly in the process of developing a software a
programmer will also perform many mistakes. In computer terminology those mistakes are called as BUGS or
ERRORS. The process of removing these errors in known as DEBUGGING.

Types of errors :

1. Compile-time errors
2. Run-time errors
3. Logical errors

Compile-time errors :

Consider the following code

class demo
{
public static void main(String args[])
{
System.out.println("this is my first java program")
}
}
When we run this code it generates an error since semi-colon is missing after the statement :
System.out.println("this is my first java program")

Such errors are known as SYNTAX ERRORS and are caught when a program is compiled. These compile time errors
are found by java compiler i.e., javac

Logical errors :
Consider the following code. It is written to calculate the salary of employee after getting 15% hike added to his
basic salary.
class demo
{
public static void main(String args[])
{
double salary = 5000;
salary = salary * (15/100);
System.out.println("after incrementing salary = "+ salary);
}
}

For the above program expected result is : 5750 that is :-


5000 + (5000 * (15/100)) = 5750

But when the above code is executed the output will be : 750

1
OOPS USING JAVA UNIT-2

This is because :
The statement that was written to calculate the salary is wrong. That is , it written as :
salary = salary * (15/100);
but it must be written as : salary = salary + (salary * (15/100));

such errors are not caught by java compiler (javac) or JVM. Finding out those errors is the responsibility of the
programmer only.
Note : by comparing the output of a program with the manually calculated result the programmer can find the
presence of a logical error.

Run-time error :
A run- time error is called as exception.
An exception is an event that occurs during the execution of a program that disrupts the normal flow of
instructions.
Exceptions are detected by JVM at run-time.
Consider the following code :
class demo
{
public static void main()
{
System.out.println("this is my first java program");
}
}
The above code can be compiled but we cannot execute(run) the code. Since when ever we run the code using
statement java demo it generated error since JVM can’t find main() method with String args[] in the above code.
So it generates an error.

Can’t we call compile-time error as compile-time exception ?


 The reason for this is that an exception is something thrown during execution of a program. Java has a
specific type for this, the Exception class.At compile time, your code is not executing, so it cannot throw
an exception. Indeed, it is proper execution of the compiler to find errors in your code - certainly not an
exception case.
 Exception is something more of an unexpected flow that can be handled. Compile time error is more like
invalid code..so code doesn't even compile.. Hence term "error" since it denotes more serious problem
which has to be fixed.

All exceptions occur at run-time only. But some exceptions are detected at run-time and some are detected at
compile-time.
The exceptions that are checked at compilation-time by java compiler are called as CHECKED EXCEPTIONS and
that are checked by JVM are called as UNCHECKED EXCEPTIONS.

Unchecked exceptions and errors are considered as unrecoverable and the programmer cannot do anything when
they occur.

2
OOPS USING JAVA UNIT-2

The programmer can write a java program with unchecked exceptions and errors and can compile the program. He
can see their effect only when he runs the program. So java compiler allows him to write a java program without
handling the unchecked exception and errors.

In case of checked exceptions the programmer should either handle them or throw them without handling them.
He cannot simply ignore them as java compiler would remind him of those errors.

Consider the following statement :


public static void main(String args[]) throws IOException

here, IOException is an example for checked exception. So we threw it out of main() without handling it. This is
done by throws clause written after main(). We can also handle it using try and catch blocks. Suppose we are not
even throwing and handling then the java compiler will raise an error.

The point is that an exception occurs only at run-time. But a checked exception, whether we handle it or not it is
detected at compilation time.
So exception can be defined as run-time error that can be handled by programmer.
That is in case of exception the programmer can do something to avoid it. But in case of error programmer cannot
do anything and hence if error occurs it causes some damage.

All exceptions are declared as classes in java. Of course everything is a class in java. Even the errors are also
represented as classes. All these classes are descendants of a super class called as throwable.

Exceptions can be handled by using the following mechanisms:-


1. try
2. catch
3. throw
4. throws
5. finally

3
OOPS USING JAVA UNIT-2

try block :-
 The programmer should observe the statements in his program where there may be a possibility of
exceptions. Such statements should be written inside try block.
 A try block looks as follows :-
try
{
Statements;
}
 Try block first finds the error with in code limit and then throws it to catch block.
 Each and every try block should have a minimum of one catch block.
 The greatness of try block is that even if some exception arises inside it, the program will not be
terminated. When JVM understands that there is an exception it stores the exception details in an
exception stack and then jumps into catch block.

Catch block:-

 Catch block catches the error thrown by try block and then prints them.
 Catch block specifies the type of error.
 A catch block looks as follows :-
catch (ExceptionClass reference)
{
Statements;
}
 The reference variable above is automatically adjusted to refer the exception stack where the details of
the exception are available and those details can be displayed using the statement
System.out.println(reference); and also by using printStackTrace() method of throwable class which
fetches the details of exception from the exception stack.

Finally block:-

 After writing try and catch blocks the programmer should ensure that clean up operations like closing the
files and terminating the threads. The programmer should write this code in the finally block.
 Statements in finally block are executed irrespective whether there is an exception or not in the program.
 The finally block looks as follows :-
finally
{
Statements;
}
 This ensures that all the opened files are properly closed and all the running threads are properly
terminated. So the data in the files will not be corrupted and the user in on safe side.

Note: Performing the above tasks is called as “exception handling”. Remember in exception handling the
programmer is not preventing the exception, as in many cases it is not possible. But the programmer is
avoiding any damage that may happen to user data.
Types of exceptions:
4
OOPS USING JAVA UNIT-2

Exception class Meaning


ArithmeticException Thrown when an exceptional condition has
occurred in an arithmetic exception
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been
accessed an illegal index. The index is either
negative or greater that equal to the size of array.
ClassNotFoundException This exception is raised when we try to access a
class whose definition is not found
FileNotFoundException This exception is raised when we can’t access or
open a file.
InterruptedException Thrown when a thread is waiting,sleeping or
doing some processing and is interrupted.
NoSuchFieldException Thrown when a clas does not contain the field or
the variable that is specified.
NoSuchMethodException Thrown when a method is not able to access.
NullPointerException It is raised when referring to the members of a
null objects. Null represents nothing.
NumberFormatException It is raised when a method could not convert a
string into numeric format.
RuntimeException It represents any exception which occurs during
runtime.
StringIndexOutOfBoundsException Thrown by string class methods to indicate that
an index is either negative or greater than the size
of string.

PROGRAM-1: Program to demonstrate exception handling

class exceptiondemo
{
public static void main(String[] args)
{
try
{
System.out.println("open files");
int n = args.length;
System.out.println(" n = "+ n);
int a = 45/n;
System.out.println("a = "+a);
}

catch(ArithmeticException ae)
{
ae.printStackTrace();
System.out.println(ae);
System.out.println("please enter data while running the program");

5
OOPS USING JAVA UNIT-2

finally
{
System.out.println("close files");
}
}
}

PROGRAM-2: Program to handle multiple exceptions

class exceptiondemo1
{
public static void main(String[] args)
{
try
{
System.out.println("open files");
int n = args.length;
System.out.println(" n = "+ n);
int a = 45/n;
System.out.println("a = "+a);
int b[] = { 10,20,30};
b[50]=100;
}
catch(ArithmeticException ae)
{
System.out.println(ae);
System.out.println("please enter data while running the program");
}

catch(ArrayIndexOutOfBoundsException aie)
{
aie.printStackTrace();
System.out.println("please see that array index is with in the range");
}

finally
{
System.out.println("close files");
}
}
}

Output :

6
OOPS USING JAVA UNIT-2

In the above program, there is provision for two exceptions -


ArithmeticException & ArrayIndexOutOfBoundsException

These exceptions are handled with the help of two catch blocks. In the above output, when values are not
passed while running the program one exception had occurred that is ArithmeticException and when we
are passing some values another exception is raising that is,
ArrayIndexOutOfBoundsException. This means even if there is scope for multiple exceptions, only one
exception at a time will occur.

throw clause : The throw keyword is used to throw exceptions.

Syntax : throw exception;

Where the exception must be evaluated to an instance of Throwable class or it may subclasses. The throw
statement in commonly used for user defined exceptions.

Program to demonstrate throw clause

class throwtest
{
static void test(Object o)
{
System.out.println(o.toString());
}
static void mythrow()
{
try

7
OOPS USING JAVA UNIT-2

{
throw new NullPointerException("this is done");
}
catch( NullPointerException e)
{
System.out.println("inside my throw");
throw e;
}
}
public static void main(String[] args)
{
try
{
test(null);
}
catch(NullPointerException e)
{
mythrow();
}
}
}

Output :

throws clause :

8
OOPS USING JAVA UNIT-2

 Even if the programmer is not handling runtime exceptions, the java compiler will not give any error
related to runtime exceptions.
 But the rule is that the programmer should handle checked exceptions.
 In case the programmer does not want to handle the checked exceptions, he should throw them out using
throws clause.
 Otherwise, there will be an error raised by java compiler.

Program to demonstrate throws keyword

import java.io.*;
class sample
{
String name;
void accept() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter name");
name = br.readLine();
}
void display()
{
System.out.println("name = "+name);
}
}

class exceptiondemo2
{
public static void main(String[] args) throws IOException
{
sample s = new sample();
s.accept();
s.display();
}
}
Output :

If throws IOException is not written after main() and accept() then :-

9
OOPS USING JAVA UNIT-2

If throws IOException is not written after main() then :-

USER-DEFINNED EXCEPTIONS

Program to create user-defined exceptions


class OwnException extends Exception
{
OwnException(String msg)
{
super(msg);
}
}
class MyException
{
public static void main(String a[])
{
int marks=Integer.parseInt(a[0]);
try
{
if(marks<0 || marks>100)
{
throw new OwnException("Marks should be in b/w 0 to 100");
}
else
System.out.println("entered marks are"+marks);

10
OOPS USING JAVA UNIT-2

}
catch(OwnException e)
{
System.out.println(e.getMessage());
}
}
}
Output :

MULTITHREADING
11
OOPS USING JAVA UNIT-2

Introduction to Threads:
All programmers are familiar with writing sequential programs. We must have written a program that displays
“hello world” or sorting programs or printing the prime series etc.,,,,
These kind of programs are called as sequential programs. That is each has:-
 A beginning
 An execution sequence and
 An end.
At any given time during the run-time of the program there is a single point of execution.

 A thread sometimes called as an execution context or light weight process- is a single sequential flow of
control within a program.
 Threads are use to isolate tasks.
 Each thread is a sequential flow of control within the same program (browser).

Definition of Thread:
A thread is a single sequential flow of control within a program.

THREAD
PROGRAM

TWO
THREADS

PROGRAM

The above figure shows the concept of multithreading.


 A thread itself is not a program.

12
OOPS USING JAVA UNIT-2

 A thread cannot run on its own. It runs with in a program.


 A program can be divided into a number of packets of code(segments)—each representing a thread
having its own separate flow of control. That is, a thread can’t exist by itself. It is always a part of a
program.

 In a java program, if we write a group of statements then these statements are executed by JVM one-by-
one. This execution is called a thread, because JVM uses a thread to execute these statements. Thus,
thread represents a separate path of execution of a group of statements.

USES / APPLICATIONS OF THREADS:

 Used to create games and animation.


 Used in server-client programs to serve the needs of multiple clients on a network or internet. That is,
on internet a server machine has to cater the needs of thousands of clients at a time. For this purpose
if we use threads in server, they can do various jobs at a time. Thus they can handle several clients.

THE Thread CLASS:

 Thread class is a concrete class.


 The class java.lang.Thread class is used to create and control threads.
 To create a thread a new instance ( object ) has to be created for this class.
 But thread will start running immediately after it is created. For that, we have to call start( ) method.
It is done as: Thread . start( )
 When Thread.start( ) is called the thread begins executing in the run() method of the target class.
 A new thread always starts running the public void run( ) method of a class .

Creating threads :

There are 2 ways of creating a thread:


1. Extend Thread class
2. Implement Runnable interface

 Extend thread class: with this technique the new class inherits from the class Thread. The thread can start
running in the run() method of a class.
 Implement Runnable interface: this technique is probably more common than extending the Thread
class. It is not required to define a new class to run the thread.

Difference between MULTI-TAKSING & MULTI-THREADING:


In multitasking we will performing various different tasks concurrently that are different from each other.

13
OOPS USING JAVA UNIT-2

For example: while sitting before a computer we can perform the following tasks at a time:

1. Download a video clip


2. Check the mails
3. Chat with friends
4. Play a song in media player etc.,,,

All the above mentioned 4 tasks are different from each other. But still we can perform them at a time. This is
nothing but multitasking. That is the processor is allocated for every one of them. This mechanism is also
known as PROCESS-BASED MULTI-TASKING.

Where as in multi-threading, we will be performing different tasks concurrently that are related to one other.

For example: suppose if we are playing a video game say a bike-race game. Then while playing the game we can
be able to see the following activities on the screen:

1. Actor will be moving on the bike


2. Score will be increasing or decreasing
3. Back ground will be changing as level progresses
4. Level of the game will be increasing after a certain limit
5. An indicator will be there to show how much distance the actor has travelled. Etc.,
All the above activities or tasks are being performed at a time and they are related to one particular
application that is bike race video game. This is nothing but THREAD-BASED MULTI-TASKING.

Now all the above 5 activities are threads.

Representation of a multi-threading will be:

Main thread

_______________
_______________
_________

Thread A Thread B Thread C

__________ __________ __________


__________ __________ __________
__________ __________ __________
______ ______ ______

 The objective of multitasking is to utilize the idle time of the CPU. Think of the CPU as the engine of your
car. Your engine keeps running regardless of whether the car is moving. Your objective is to keep your car
moving as much as possible so you can get the most miles from a gallon of gas. An idling engine wastes
gas.

14
OOPS USING JAVA UNIT-2

 The same concept applies to the CPU in your computer. You want your CPU cycles to be processing
instructions and data rather than waiting for something to process. A CPU cycle is somewhat similar to
your engine running.
 It may be hard to believe, but the CPU idles more than it processes in many desktop computers. Let’s say
that you are using a word processor to write a document. For the most part, the CPU is idle until you
enter a character from the keyboard or move the mouse. Multitasking is designed to use the fraction of a
second between strokes to process instructions from either another program or from a different part of
the same program.
 Making efficient use of the CPU may not be too critical for applications running on a desktop computer
because most of us rarely need to run concurrent programs or run parts of the same program at the same
time. However, programs that run in a networked environment, such as those that process transactions
from many computers, need to make a CPU’s idle time productive.

LIFE CYCLE OF A THREAD

New thread Newborn

stop
start

stop Dead
Active Running Runnable
Thread Killed Thread
yield

Suspend Resume
notify stop
sleep wait

Idle Thread Blocked

(not Runnable)

New born state:

We created a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled
for running.

15
OOPS USING JAVA UNIT-2

 Schedule it for running using start() method.


 Kill it using stop() method

Runnable state:

 The runnable state means that the thread is ready for execution and is waiting for the availability of the
processor. That is, the thread has joined the queue of threads that are waiting for execution. If all threads
have equal priority, then they are given time slots for execution in round robin, first-come, first-serve
manner.
 If we want a thread to relinquish control to another thread of equal priority before its turn comes, we can
do so by using the yield() method.

Running state:

Running means that the processor has given its time to the thread for its execution. The thread runs until it
relinquishes control on its own or it is preempted by a higher priority thread.
 Suspend () method:
A suspended thread can be revived by using the resume () method. This approach is useful when we want to
suspend a thread for some time due to certain reason, but do not want to kill it.
 Sleep() method:
We can put a thread to sleep for a specified time period using the method sleep (time) where time is in
milliseconds. This means that the thread is out of the queue during this time period.the thread re-enters the
runnable state as soon as this time period is elapsed.
 Notify () method:
It has been told to wait until some event occurs. This is done using the wait () method. The thread can be
scheduled to run again using the notify () method.

Blocked state:

 A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended, sleeping , or waiting in order
to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore
fully qualified to run again.

Dead state:
 Every thread has a life cycle. A running thread ends its life when is has completed executing its run()
method. We can kill it by sending the stop message to it at any state thus causing a premature death to it.
A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable”
(blocked) condition.

Write a program to find the thread used by JVM to execute the statements

class currentthread
{
public static void main(String[] args)

16
OOPS USING JAVA UNIT-2

{
System.out.println("let us find the current thread");
Thread t = Thread.currentThread();
System.out.println("current thread = "+ t);
System.out.println("it's name = "+ t.getName());
}
}

Output:

 In the above program, currentThread() is static method in Thread class. So it is being called with class
name. Then this method gave an object ‘t’ of thread class. When it is displayed its contents are displayed
as : Thread[main,5,main]
 Here Thread indicates that ‘t’ is a Thread class object.
 First main indicates the name of thread running the current code.
 We get 5 which represents the priority of thread. Every thread will have a priority number associated with
it. These priority numbers will be in the range of 1 to 10.
 1 is minimum priority………….10 is maximum priority of thread.
 Highest priority number thread will be given first preference while execution by JVM.
 Default priority number of thread is 5.
 The next main indicates the thread group name to which thread belongs to. A thread group represents a
group of threads as a single unit.

Note: The above program indicates that when any program is written in java, JVM internally uses a thread called
“main thread” to run the statements of the program. This thread is responsible for executing our statements and
displaying results.

Which thread always runs in a java program by default ?


Answer : main thread

Create Thread by Implementing Runnable: ( java.lang.Runnable )

17
OOPS USING JAVA UNIT-2

The easiest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable, a class need only implement a single method called run( ), which is declared like this:

public void run();

Note : run() method is available both in thread class and Runnable interface.

The procedure for creating threads based on the Runnable interface is as follows:

1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An
object of this class is a Runnable object.

2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The
Thread object now has a Runnable object that implements the run() method.

3. The start() method is invoked on the Thread object created in the previous step. The start() method returns
immediately after a thread has been spawned.

4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught
exception.

Write a java program to create threads by implementing Runnable interface

class ThreadDemo2 implements Runnable


{
Thread t=new Thread();

public void run()


{
for(int i=1;i<=10;i++)
{
System.out.println(i+" "+t.getName());
try
{
Thread.sleep(2000);
}

catch(InterruptedException e)
{
e.printStackTrace();
}
} } }
class MyThread
{
public static void main(String args[])

18
OOPS USING JAVA UNIT-2

{
ThreadDemo2 t1=new ThreadDemo2();
ThreadDemo2 t2=new ThreadDemo2();

Thread a=new Thread(t1);


Thread b=new Thread(t2);
a.start();
b.start();
}
}
Output:

Creating threads by extending thread class:

The procedure for creating threads based on extending the Thread is as follows:

1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed
by the thread.

19
OOPS USING JAVA UNIT-2

2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super()
call.

3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread
eligible for running.

Write a java program to create threads by extending Thread class

class ThreadDemo extends Thread


{
Thread t=new Thread();
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println(i+" "+t.getName());
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class ExtendThread
{
public static void main(String x[])
{
ThreadDemo t1=new ThreadDemo();

t1.start();
}
}

Output:

20
OOPS USING JAVA UNIT-2

When creating threads, there are two reasons why implementing the Runnable interface may be
preferable to extending the Thread class:

 Extending the Thread class means that the subclass cannot extend any other class, whereas a class
implementing the Runnable interface
has this option.
 A class might only be interested in being runnable, and therefore, inheriting the full overhead of the
Thread class would be excessive.

TERMINATING A THREAD

 A thread will terminate automatically when it comes out of run() method.


 To terminate the thread on our own, we have to device our own logic.
 For this purpose the following statements can be used :
 Create a Boolean type variable and initialize it to false
boolean stop = false;
 Let us assume that we want to terminate the thread when the user presses <enter> key. So when
the user presses the enter key, make the Boolean type variable as true.
stop = true;
 Check this variable in run() method and when it is true make the thread return from the run()
method
public void run( )
{
if( stop == true )
return ; }
Write a program to create, run and stop a thread

21
OOPS USING JAVA UNIT-2

import java.io.*;
class mythread extends Thread
{
boolean stop = false;
public void run()
{
for(int i = 1; i<=25; i++)
{
System.out.println(i);
if(stop)
return;
}
}
}
class threddemo
{
public static void main(String[] args) throws IOException
{
mythread obj = new mythread();
Thread t = new Thread(obj);
t.start();
System.in.read();
obj.stop = true;
}
}
Output:

Thread Synchronization

22
OOPS USING JAVA UNIT-2

 When a thread is already acting on an object, preventing any other thread from acting on the same object
is called as Thread synchronization or Thread safe.
 Thread synchronization is recommended when multiple threads are acting on a single object

Program for thread synchronization

class reserve implements Runnable


{
int available =1;
int wanted;
reserve(int i)
{
wanted = i;
}
public void run()
{
synchronized(this)
{
System.out.println("avaialable berths = "+ available);
if(available>=wanted)
{
String name = Thread.currentThread().getName();
System.out.println(wanted+"berths reserved for"+name);
try
{
Thread.sleep(2000);
available = available-wanted;
}
catch(InterruptedException ie)
{
}
}
else
System.out.println("sorry no berths");
}
}
}
class safe
{
public static void main(String[] args)
{

reserve obj = new reserve(1);


Thread t1=new Thread(obj);
Thread t2=new Thread(obj);
t1.setName("first person");
t2.setName("second person");
t1.start();
t2.start();
} }

Output :

23
OOPS USING JAVA UNIT-2

avaialable berths = 1
1berths reserved forfirst person
avaialable berths = 0
sorry no berths

Difference between synchronized keyword and synchronized block is:-

 Synchronized block is useful to synchronize a block of statements.


 Synchronized keyword is useful to synchronize an entire method

Inter-thread communication

In some cases it is required that 2 or more threads should communicate with each other.
Example: producer-consumer problem

When producer thread completes the generation of data then only the consumer thread should utilize
that data.

Program to demonstrate inter-thread communication

class communicate
{
public static void main(String[] args)
{
producer obj1 = new producer();
consumer obj2 = new consumer(obj1);
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t2.start();
t1.start();
}
}
class producer extends Thread
{
StringBuffer sb ;
producer()
{
sb = new StringBuffer();
}
public void run()
{
synchronized(sb)
{
for(int i = 1;i<=20;i++)
{
try

24
OOPS USING JAVA UNIT-2

{
sb.append(i+" ");
Thread.sleep(1000);
System.out.println("appending");
}
catch(Exception e)
{
}
}
sb.notify();
}
}
}
class consumer extends Thread
{
producer p;
consumer(producer p)
{
this.p = p;
}
public void run()
{
synchronized(p.sb)
{
try
{
p.sb.wait();
}
catch(Exception e)
{
}
System.out.println(p.sb);
}
}

Output :

appending
appending
.
.
1 2 3 4 5 ……..20

When data generation is completed then sb.notify() statement in producer class sends a message to
wait() in the consumer class which unblocks the consumer class and allows to consume the data.

Some times instead of notify() another method called as notifyAll() has to be used to send an
acknowledgement message to all the waiting threads.

25
OOPS USING JAVA UNIT-2

Difference between sleep() and wait() methods is: that both those methods will block thread temporarily
from execution for some time. When sleep() is executed inside synchronized block, the object is still under
lock. When wait() is executed it breaks the synchronized block so that object is unlocked and available.

Thread priorities:
 Each thread will have some priority number assigned to it.
 When threads are executed a program called as “thread scheduler” which is a part of JVM will execute the
threads based on their priorities.
 Thread with higher priority number will be given first preference for execution.

Thread.MIN_PRIORITY (1)

Thread.MAX_PRIORITY (10)

Thread.NORM_PRIORITY(5) ( default priority)

Program to demonstrate thread priorities

class myclass extends Thread


{
int count = 0;
public void run()
{

System.out.println("completed thread: "+Thread.currentThread().getName());


System.out.println("priority of thread: "+Thread.currentThread().getPriority());
}
}
class priority
{
public static void main(String args[])
{
myclass obj = new myclass();
Thread t1=new Thread(obj,"one");
Thread t2 = new Thread(obj,"two");
t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);
t1.start();
t2.start();
}
}

Thread deadlock: Deadlock describes a situation where two or more threads are blocked forever,
waiting for each other.

26
OOPS USING JAVA UNIT-2

There is no proper solution for avoiding dead lock. While writing program the programmer should take
care that dead lock is to be avoided in the program.

isALive() and join() methods:


The main thread must be the last thread to finish. Sometimes this is accomplished by calling sleep() within main( ),
with a long enough delay to ensure that all child threads terminate prior to the main thread. However, this is
hardly a satisfactory solution, and it also raises a larger question: How can one thread know when another thread
has ended?

Fortunately, Thread provides a means by which you can answer this question.

Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread. This
method is defined by Thread, and its general form is shown here:

final boolean isAlive( )

The isAlive( ) method returns true if the thread upon which it is called is still running. It
returns falseotherwise. While isAlive( ) is occasionally useful, the method that you will more commonly use
to wait for a thread to finish is called join( ), shown here:

final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates. Its name comes from the concept of the
calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait for the specified thread to terminate.

Daemon thread: is a thread that executes continuously. Daemon threads are service providers for other
threads. It generally provides background processing.

yield() method:
Causes the currently executing thread object to temporarily pause and allow other threads to execute.

Now, it is very likely that your main thread will execute the loop five times before the run method of the new
thread is being executed, so all the calls to yield will happen only after the loop in the main thread is executed.
join will stop the current thread until the thread being called with join() is done executing.
interrupt will interrupt the thread it is being called on, causing InterruptedException.
yield allows a context switch to other threads, so this thread will not consume the entire CPU usage of the process.

public class MyRunnable implements Runnable

27
OOPS USING JAVA UNIT-2

   public static void main(String[] args) {


      Thread t = new Thread(new MyRunnable());
      t.start();

      for(int i=0; i<5; i++)


{
          System.out.println("Inside main");
   }
   }

   public void run() {


      for(int i=0; i<5; i++) {
          System.out.println("Inside run");
          Thread.yield();
   }
   }
}

The output obtained is

Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run

28
OOPS USING JAVA UNIT-2

I/O BASICS IN JAVA


A value can be assigned to a variable in 2 ways:-
1. compile-time allocation (static)
2. run-time allocation (dynamic)

In C-language:
compile-time allocation
int x=10; or
int x;
x=10;
run-time allocation
int x;
scanf(“%d”,&x);
In C++ language:
compile-time allocation
int x=10; or
int x;
x=10;
run-time allocation
int x;
cin>>x;

Also operators like new and delete, malloc and calloc can be used for dynamic memory allocation.

In java also, values can be assigned both at compile time and run time.

Compile time allocation is as same as we do in c and c++

Accepting input through key board while executing the program is different in java

To accept input from key board while executing the program we need to use STREAM.

STREAM is the flow of data from one end to other end

Example:

In pipe, water flows from one end to other end.

A stream can carry data from key board to memory; memory to printer; memory to file etc.,,

Similarly in order to move data from one place to other we need to use streams.

Streams are classified into:

1. Input Stream ( to read data from various places)


2. Output Stream( to write data to some other place)

All the input stream and output streams are represented by the classes present in java.io package

29
OOPS USING JAVA UNIT-2

System is a class in java.lang package

in is field in system class

System.in represents the standard input device that is KEY BOARD.

System.out represents the standard output device that is MONITOR

System.err represents the standard output device that is MONITOR

Thus, programmer can indicate what type of message he is displaying by using System.out or System.in

To accept the data from key board the steps to be followed are:

1. Connect the key board to input stream class


2. Connect the input stream class to buffered reader class
3. Then accept the data from key board

The above mentioned 3 steps are demonstrated as follows:

Connect the key board to input stream class

InputStreamReader is = new InputStreamReader(System.in); -------(1)

Connect the input stream class to buffered reader class

BufferedReader br = new BufferedReader( i ); ------(2)

Both (1) and (2) can be combined as:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Now the environment has been set up to accept the values from key board

accept the data from key board

make use of statements : br.read() or br.readLine()

read() and readLine() methods are present in buffered reader class so input stream reader class should be
connected to buffered reader class.

30
OOPS USING JAVA UNIT-2

PROGRAM TO ACCEPT SINGLE CHARACTER FROM KEYBOARD

import java.io.*;
class chardemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a character");
char ch = (char) br.read();
System.out.println("entered character is " +ch);
}
}
Output

Even if we enter a string read() accepts only a character (first character of that string) see the below
output:

Reason for writing the following statement in the above program is :

char ch = (char) br.read();


read() reads a character but returns its ascii value
since a character variable can’t hold an integer value type casting is being performed.

31
OOPS USING JAVA UNIT-2

Consider the following program

import java.io.*;
class chardemo1
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a character");
int ch = br.read();
System.out.println("entered character is " +ch);
}
}
Output

Ascii value of an integer is being returned

PROGRAM TO ACCEPT STRING FROM KEYBOARD

import java.io.*;
class stdemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a string");
String ch = br.readLine();
System.out.println("entered character is " +ch);
}
}
Output

32
OOPS USING JAVA UNIT-2

 except characters all other values will be treated as strings only..in java
 so other values integers also should be type casted. But string is a class and it can’t be type casted just like
a normal data type
 all basic data types are classes in java. So those classes and static methods present in them are to be used
to convert variables into a particular data type.
 Example: Integer is a class.. parseInt is a static method in that class which converts any data type into
integer.
PROGRAM TO ACCEPT AN INTEGER FROM KEYBOARD
import java.io.*;
class intdemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter aa integer");
int ch = Integer.parseInt(br.readLine());
System.out.println("entered integer is " +ch);
}
}
Output

Similarly other classes are:

Double.parseDouble
Float.parseFloat
Byte.parseByte etc.,,,,

33
OOPS USING JAVA UNIT-2

STRING HANDLING
 Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.
 The Java platform provides the String class to create and manipulate strings.
 In c and c++ string is a collection of characters that is terminated by a Null character. But it is not valid in
java.
 In java, string which is declared is an object of String class. It is not a character array.
 String class is a part of java.lang package, where all the necessary methods o work on strings are
available.

IS STRING A CLASS OR DATA TYPE ?

 String class is a part of java.lang package but in java all classes can be considered as data types. So String
can be taken as a object. ( since, class is nothing but a user-defined data type)

DIFFERENT WAYS OF INITIALIZING A STRING :

 Method – 1: String s = “ hello”;

 Method – 2: String s = { ‘h’,’e’,’l’,’l’,’o’};

Here we are converting string into character array. After the above declaration now create a string object

and pass array name to it.

String x = new String (s);

 Method – 3: String s = new String(“hello”);

We can create an object to string class by allocating memory using new operator . this is similar to
creating an object to a class. In the above declaration first object is being declared the value is being
stored into it.
OPERATIONS ON STRINGS
1. Length of string : counts number of characters.

class string
{
public static void main(String[] args)
{
String s1= "wel come";
System.out.println(s1.length());
// output : 8 (white space is also counted )
} }

2. Concatenation of strings : combines 2 strings.

class string2
{
public static void main(String[] args)
{
String s1= "welcome";

34
OOPS USING JAVA UNIT-2

String s2 = "to java lab";

System.out.println( s1 +" "+ s2 );


// ouput : welcome to java lab

System.out.println( s1+ s2 );
// ouput : welcometo java lab

System.out.println( s1 +" "+10+" "+20);


//output : welcome 10 20

}
}

3. Replace

class string3
{
public static void main(String[] args)
{
String s1= "welcome";
System.out.println( s1.replace('c','k'));
//output : welkome
}
}

4. Comparision

class string4
{
public static void main(String[] args)
{
String s1= "welcome";
String s2 = "to java lab";

System.out.println( s1 == s2); // output : false

System.out.println( s1 .equals(s2)); // output : false

String s3= "hello";


String s4 = "Hello";
System.out.println( s3 .equals(s4)); //output : false

System.out.println( s3 .equalsIgnoreCase(s4));
//output : true

}
}

5. trim : this method is used to remove white spaces on either sides of given string. If white spaces are
present in between string then they cannot be removed.

35
OOPS USING JAVA UNIT-2

class string4
{
public static void main(String[] args)
{
String s3= " welcome ";

System.out.println(s3.trim()); //output : welcome

String s4= "wel come";

System.out.println(s4.trim()); // wel come

}
}

6. charAt : this method specifies the character at that particular position in a given string. Counting starts
from 0.

class string5
{
public static void main(String[] args)
{
String s4= "welcome to java lab";

System.out.println(s4.charAt(5)); //output : m
System.out.println(s4.charAt(8));//output: t

}
}

7. toUpperCase : converts given string into upper case letters.


toLowerCase : converts given string into lower case letters

class string5
{
public static void main(String[] args)
{
String s4= "welcome to java lab";

System.out.println(s4.toUpperCase());
//output : WELCOME TO JAVA LAB

String s5= "WELCOME TO JAVA LAB";

System.out.println(s5.toLowerCase());
//output :welcome to java lab

}
}

36
OOPS USING JAVA UNIT-2

8. indexOf : this method is used to find the position of first character in a given string.

class string5
{
public static void main(String[] args)
{
String s5= "welcome to java lab";

System.out.println(s5.indexOf("t")); //output : 8

String s6= "hello";

System.out.println(s6.indexOf("n"));// output : -1
//If nothing is found then negative value is returned

}
}

9. lastIndexOf : prints position of last character in given string. If nothing is found it also returns negative
value. It returns the position of last occurrence of character in the given string.

class string5
{
public static void main(String[] args)
{
String s6= "madam";

System.out.println(s6.lastIndexOf("m")); //output : 4

}
}

10. substring : this method is useful to extract a part of the string from actual string.

class string5
{
public static void main(String[] args)
{
String s6= "this is notes on strings";

System.out.println(s6.substring(6)); // s notes on strings


System.out.println(s6.substring(6,12)); // s note

}
}

11. getChars : this method copies characters from a string into character array.

37
OOPS USING JAVA UNIT-2

getChars(int i1,int i2char a[],int i3)


the characters from position i1 to i2-1 are copied into array ‘a’ to a location starting from i3. Counting
stars from 0th position

class string6
{
public static void main(String[] args)
{
String s6= "this is notes on strings";
char a[ ] = new char [15];
s6.getChars(2,10,a,0);
System.out.println(a); // is is no

}
}

12. split : this method is useful to break a string into pieces a places represented by delimiter. Te resultant
pieces are returned into string type array. Suppose if delimiter is comma then string is cut into pieces
where ever comma occurs in the string.

class stringg
{
public static void main(String[] args) Ouput :
{
String s=" this is, ja,va lab"; this is
String str[ ];
str = s.split( "," ); java lab
for(int i=0;i<str.length;i++)
{
System.out.println(str[i]);
}
}
}

IMMUTABILITY OF STRINGS

String objects can be divided into :-


 mutable objects  contents can be modified
 immutable objects  contents cannot be modified.

String objects are immutable.


Consider the following program :

class str
{
public static void main(String[] args)
{
String s1="hello";
String s2="world";
s1=s1+s2;
System.out.println(s1); // hello world
}

38
OOPS USING JAVA UNIT-2

s1=s1+s2; using this statement we are modifying the contents of string object s1. String objects are
immutable. If it is true then why the output is hello world instead of hello.?

Reason:
Java Virtual machine creates 2 objects s1 and s2 separately

s1  hello
s2world

when s1+s2 is written JVM creates a separate location to store the content of s1+s2.
(s1+s2)  hello world
But the content of s1 is not modified. Instead the location to which s1 is pointing to is changed but not
the content. The old object’s reference contains hello and now it as lost its reference. It is said to be
unreferenced object. It will be removed by garbage collector from memory.

STRING BUFFER & STRING BUILDER

 whenever we are creating a string object we are creating a string that cannot be changed.
 That is once string object is created it cannot be modified. But all kinds of string operations can
be performed.
 The difference is :- whenever a modification is made to string that modified string should be
assigned to a new string object.
 The original string is left unchanged.
 This approach is used because fixed strings can be implemented more efficiently than changed
one’s.
 If in some cases the original string has to be modified then java has 2 options :-
String Buffer & String Builder. Both o them can hold strings that are modified after creation.
Since both of them part of java.lang package they are automatically available to all java
programs
 For this purpose there are several methods available in string buffer class.
 Objects can be created for string buffer class in the following way :

StringBuffer s = new stringBuffer(“hello”);


hello is being passed to string buffer object

StringBuffer s = new stringBuffer( );


Memory is allocated first in the above declaration. By default stringbuffer object will be created
with capacity of holding 16 characters.

StringBuffer s = new stringBuffer( 75);


‘s’ is created with a capacity of holding 75 characters

Note : we may or may not mention size of stringbuffer object but it can be expanded dynamically
( since it is mutable).

Methods in String Buffer class :

39
OOPS USING JAVA UNIT-2

1. append(): this method concatenates the string representation of any other type with the string
buffer object.

class stringbuffer
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("hello");
System.out.println(s.append("12345")); // output : hello12345
}
}

2. insert() : this method inserts one string into another string from the specified position.

class stringbuffer1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("java lab");
StringBuffer s2 =s1.insert(5, "programming");
System.out.println(s1); // output : java programming lab
}
}

3. reverse(): this method reverses the given string

class stringbuffer2
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("welcome");
s1.reverse();
System.out.println(s1); // output : emoclew
}
}

4. delete(int i, int j): this method deletes characters in a string from position ‘i’ to ‘j-1’.

class stringdelet
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("department");
System.out.println(s.delete(1,4)); // output : drtment
}
}

Program on finding the length and capacity of a StringBuffer object

class LengthCapacity

40
OOPS USING JAVA UNIT-2

{
Output :
public static void main(String args[])
{
Length of sb1 = 0
StringBuffer sb1 = new StringBuffer(); Length of sb2 = 9
StringBuffer sb2 = new StringBuffer("ObjectOne"); Capacity of sb1 = 16
System.out.println("Length of sb1 = "+sb1.length()); Capacity of sb2 = 25
System.out.println("Length of sb2 = " +sb2.length());
System.out.println("Capacity of sb1 = "+sb1.capacity());
System.out.println("Capacity of sb2 = "+sb2.capacity());
}
}

THE TOPICS Reading and Writing Files, Print Writer Class WILL
BE DISCUSSED AS PART OF UNIT-5

41

You might also like