0% found this document useful (0 votes)
14 views27 pages

Oops Unit4

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)
14 views27 pages

Oops Unit4

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/ 27

1

PART A
1.Define thread.
A thread is a lightweight sub-process that defines a separate path of execution. It is the
smallest unit of processing that can run concurrently with the other parts (other threads) of the
same process.
2.Compare Process and Thread.

3.What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread that runs in background to perform tasks such as
garbage collection. Its life depend on the mercy of user threads i.e. when all the user threads
dies, JVM terminates this thread automatically.
Methods: The java.lang.Thread class provides two methods for java daemon thread.
2

4. Analyze the different states of thread.


Different states, a thread (or applet/servlet) travels from its object creation to object removal
(garbage collection) is known as life cycle of thread. A thread goes through various stages in
its life cycle. At any time, a thread always exists in any one of the following state:
1.New State
2.Runnable State
3.Running State
4.Waiting/Timed Waiting/Blocked state
5.Terminated State/ dead state
5.What is synchronization? Give example.
When two or more threads need to use a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process of ensuring single thread
access to a shared resource at a time is called synchronization.
Syntax to use synchronized method:
Access_modifier synchronized return_type method_name(parameters) { …….. }.
6.Differentiate exception and error in java.
3

7.What is an exception?
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of
a program, i.e. at run time, that disrupts the normal flow of the program‟s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains information
about the exception, such as the name and description of the exception and the state of the
program when the exception occurred.
8.How does Java differentiate between checked and unchecked exceptions?
A checked exception is the one that the compiler checks or notifies during compilation.
Checked Exceptions are also known as compile-time exceptions. These exceptions cannot be
ignored. If a code within a function throws a checked exception, the function must handle the
exception or specify it using the throws keyword.
An unchecked exception occurs during the execution process. Unchecked Exceptions are
also known as runtime exceptions. Programming mistakes, such as logic errors or improper
use of an API, are examples of this. Runtime exceptions are ignored during compilation.
9.Formulate the advantages of using exception handling.
•Exceptions separate error handling code from regular code.
Benefit: Cleaner algorithms, less clutter
•Exceptions propagate errors up the call stack.
Benefit: Nested methods do not have to explicitly catch-and-forward errors (less work,
more reliable)
•Exception classes group and differentiate error types.
You can group errors by their generalize parent class, or Differentiate errors by their
actual class
•Exceptions standardize error handling.
10.What are the two methods available in Stack Trace Elements?
4

11.Differentiate between throw and throws.

PART B
1. Explain different states of thread in detail.
Different states, a thread (or applet/servlet) travels from its object creation to object
removal (garbage collection) is known as life cycle of thread. A thread goes through various
stages in its life cycle. At any time, a thread always exists in any one of the following state:
1. New State
2. Runnable State
3. Running State
4. Waiting/Timed Waiting/Blocked state
5. Terminated State/ dead state
1. New State:
A new thread begins its life cycle in the new state. It remains in this state until the program starts
the thread by calling start() method, which places the thread in the runnable state.
 A new thread is also referred to as a born thread.
 When the thread is in this state, only start() and stop() methods can be called. Calling any other
5

methods causes an IllegalThreadStateException.


 Sample Code: Thread myThread=new Thread();
2. Runnable State:
After a newly born thread is started, the thread becomes runnable or running by calling the run()
method.
 A thread in this state is considered to be executing its task.
 Sample code: myThread.start();
 The start() method creates the system resources necessary to run the thread, schedules the thread
to run and calls the thread’s run() method.
3. Running state:
 Thread scheduler selects thread to go from runnable to running state. In running state Thread
starts executing by entering run() method.
 Thread scheduler selects thread from the runnable pool on basis of priority, if priority of two
threads is same, threads are scheduled in unpredictable manner. Thread scheduler behaviour is
completely unpredictable.
 When threads are in running state, yield() method can make thread to go in Runnable state.
4. Waiting/Timed Waiting/Blocked State :
 Waiting State:
Sometimes one thread has to undergo in waiting state because another thread starts executing. A
runnable thread can be moved to a waiting state by calling the wait() method.
 A thread transitions back to the runnable state only when another thread signals the waiting
thread to continue executing.
 A call to notify() and notifyAll() may bring the thread from waiting state to runnable state.
 Timed Waiting:
A runnable thread can enter the timed waiting state for a specified interval of time by calling the
sleep() method.
 After the interval gets over, the thread in waiting state enters into the runnable state.
 Sample Code:
try {
Thread.sleep(3*60*1000);// thread sleeps for 3 minutes
}
catch(InterruptedException ex) { }
 Blocked State:
When a particular thread issues an I/O request, then operating system moves the thread to
6

blocked state until the I/O operations gets completed.


 This can be achieved by calling suspend() method.
 After the I/O completion, the thread is sent back to the runnable state.
5. Terminated State:
A runnable thread enters the terminated state when,
(i) It completes its task (when the run() method has finished)
public void run() { }
(ii) Terminates ( when the stop() is invoked) – myThread.stop();
A terminated thread cannot run again.
2. Explain how to create threads. Write a java program that prints numbers from 1 to 10 line
by line after every 5 seconds.
1.Although the main thread is created automatically when our program is started, it can be controlled
through a Thread object.
2.To do so, we must obtain a reference to it by calling the method currentThread()
Example:
class CurrentThreadDemo {
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(“Current Thread: “+t);
// change the name of the main thread
t.setName(“My Thread”);
System.out.println(“After name change : “+t);
try {
for(int n=10;n>0;n--) {
System.out.println(n);
Thread.sleep(1000);// delay for 1 second
}
} catch(InterruptedException e) {
System.out.println(“Main Thread Interrrupted”);
}
}
}
Output:
7

Current Thread: Thread[main,5,main]


After name change: Thread[My Thread,5,main]
10
9
8
7
6
5
4
3
2
1
3. Illustrate the two methods for creation of threads with examples.
We can create threads by instantiating an object of type Thread. Java defines two ways to
create threads:
1. By implementing Runnable interface (java.lang.Runnable)
2. By extending the Thread class (java.lang.Thread)
1. Creating threads by implementing Runnable interface:
The Runnable interface has only one method that must be overridden by the class which
implements this interface:
public void run()// run() contains the logic of the thread
{
// implementation code
}
 Steps for thread creation:
1. Create a class that implements Runnable interface. An object of this class is
Runnable object.
public class MyThread implements Runnable
{
---
}
2. Override the run() method to define the code executed by the thread.
3. Create an object of type Thread by passing a Runnable object as argument.
Thread t=new Thread(Runnable threadobj, String threadName);
8

4. Invoke the start() method on the instance of the Thread class.


t.start();
 Example:
class MyThread implements Runnable
{
public void run()
{
for(int i=0;i<3;i++)
{
System.out.println(Thread.currentThread().getName()+" # Printing "+i);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
public class RunnableDemo {
public static void main(String[] args)
{
MyThread obj=new MyThread();
MyThread obj1=new MyThread();
Thread t=new Thread(obj,"Thread-1");
t.start();
Thread t1=new Thread(obj1,"Thread-2");
t1.start();
}
}
Output:
Thread-0 # Printing 0
Thread-1 # Printing 0
9

Thread-1 # Printing 1
Thread-0 # Printing 1
Thread-1 # Printing 2
Thread-0 # Printing 2
2. Creating threads by extending Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r, String name)
All the above constructors creates a new thread.
 Steps for thread creation:
1. Create a class that extends java.lang.Thread class.
public class MyThread extends Thread
{
---
}
2. Override the run() method in the sub class to define the code executed by the thread.
3. Create an object of this sub class.
MyThread t=new MyThread(String threadName);
4. Invoke the start() method on the instance of the subclass to make the thread for
running.
start();
 Example:
class SampleThread extends Thread
{
public void run()
{
for(int i=0;i<3;i++)
{
System.out.println(Thread.currentThread().getName()+" # Printing "+i);
try
10

{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
SampleThread obj=new SampleThread();
obj.start();
SampleThread obj1=new SampleThread();
obj1.start();
}
}
Output:
Thread-0 # Printing 0
Thread-1 # Printing 0
Thread-1 # Printing 1
Thread-0 # Printing 1
Thread-0 # Printing 2
Thread-1 # Printing 2
4. Demonstrate the java synchronized methods and java synchronized blocks.
Java synchronized 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.
Syntax to use synchronized method:
Access_modifier synchronized return_type method_name(parameters)
{ …….. }
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);
11

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);
}
}
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();
}}
Output:
5
10
15
20
25
100
200
300
400
500
Synchronized block in java
 Synchronized block can be used to perform synchronization on any specific resource of
the method.
 Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
 If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block
 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
12

Syntax to use synchronized block


1. synchronized (object reference expression) {
2. //code block
3. }
Example of synchronized block
class Table{
void printTable(int n)
{
synchronized(this)//synchronized block
{
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronizedBlock1
{
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();
}
}
Output:
5
10
15
20
25
13

100
200
300
400
500
5. Create a Bank database application program to illustrate the use of multithreading.
Program:
class Customer{
int Balance=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw..."+amount);
if(Balance<amount)
{
System.out.println("Less balance; Balance = Rs. "+Balance+"\nWaiting for deposit...\n");
try
{
wait();
}
catch(Exception e){}
}
Balance-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit... Rs. "+amount);
Balance+=amount;
System.out.println("deposit completed... Balance = "+Balance);
notify();
}
}
class ThreadCommn
{
public static void main(String args[]) {
14

Customer c=new Customer();


new Thread()
{
public void run(){c.withdraw(20000);}
}.start();
new Thread(){
public void run(){c.deposit(15000);}
}.start();
}
}
Output:
going to withdraw...20000
Less balance; Balance = Rs. 10000
Waiting for deposit...
going to deposit... Rs. 15000
deposit completed... Balance = 25000
withdraw completed...

6. Explain the exception hierarchy in java?

All exceptions and errors extend from a common java.lang. Throwable parent class.

The Throwable class is further divided into two classes:


1. Exceptions and
2. Errors.
15

Exceptions: Exceptions represents errors in the Java application program, written by the user.
Because the error is in the program, exceptions are expected to be handled, either
 Try to recover it if possible
 Minimally, enact a safe and informative shutdown.
Sometimes it also happens that the exception could not be caught and the program may get
terminated. Eg. ArithmeticException
An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
Errors: Errors represent internal errors of the Java run-time system which could not be handled
easily. Eg. OutOfMemoryError.
16

DIFFERENCE BETWEEN EXCEPTION AND ERROR:


17

EXCEPTION HIERARCHY

Types of Exceptions:
1. Checked Exceptions
2. Unchecked Exceptions
1. Checked Exceptions:
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions
It is an exception that is typically a user error or a problem that cannot foreseen by the
programmer.
Checked exceptions are checked at compile-time.
Checked Exceptions forces programmers to deal with the exception that may be thrown.
Checked exceptions must be caught using try.. catch () block or we should throw the exception
using throws clause. If you dont, compilation of program will fail.

Example:
1. ClassNotFoundException
2. CloneNotSupportedException
3. IllegalAccessException,
4. MalformedURLException.
5. NoSuchFileException
6. NoSuchMethodException
7. IOException
18

FileNotFoundException is a checked exception in Java. Anytime, we want to read a file from filesystem,
Java forces us to handle error situation where file may not be present in place.

To make program able to compile, you must handle this error situation in try-catch block. Below given
code will compile absolutely fine.
19

2. Unchecked Exceptions(RunTimeException):
The classes that extend RuntimeException are known as unchecked exceptions.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch
the exception or declare it in a throws clause.
In fact, the programmers may not even know that the exception could be thrown.
They are either irrecoverable (Errors) and the program should not attempt to deal with them,
or they are logical programming errors. (Runtime Exceptions).

Example:
1. ArrayIndexOutOfBoundsException
2. ArithmeticException
3. NullPointerException

7.Write a java program to test the” Divide by Zero exception” and “ArrayIndexOutofBouund” with
example program (get inputs from the user).

import java.util.Scanner;

public class ExceptionTest {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
20

// Test Divide by Zero Exception


try {
System.out.print("Enter a number to divide: ");
int numerator = scanner.nextInt();
System.out.print("Enter a number to divide by: ");
int denominator = scanner.nextInt();

int result = numerator / denominator; // This can throw ArithmeticException


System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}

// Test ArrayIndexOutOfBoundsException
try {
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] array = new int[size];

System.out.print("Enter an index to access: ");


int index = scanner.nextInt();

// This can throw ArrayIndexOutOfBoundsException


System.out.println("Value at index " + index + ": " + array[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index is out of bounds.");
} catch (NegativeArraySizeException e) {
System.out.println("Error: Array size cannot be negative.");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close();
}
21

}
}

OUTPUT:

8. Discuss the role of the finally block in exception handling. Create a Java program that
demonstrates its use and explains how it ensures that certain code is executed regardless of
whether an exception occurs.

 finally Block:
A finally block is always executed, regardless of the cause of exit from the try block, or whether
any catch block was executed.
Generally finally block is used for freeing resources, cleaning up, closing connections etc.
Even though there is any exception in the try block, the statements assured by finally block are
sure to execute.
Rule:
 For each try block there can be zero or more catch blocks, but only one finally block.
 The finally block will not be executed if program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).

Rules for try, catch and finally Blocks:

1) Statements that might generate an exception are placed in a try block.


2) Not all statements in the try block will execute; the execution is interrupted if an exception
occurs
3) For each try block there can be zero or more catch blocks, but only one finally block.
4) The try block is followed by i. one or more catch blocks ii. or, if a try block has no catch
block, then it must have the finally block
5) A try block must be followed by either at least one catch block or one finally block.
6) A catch block specifies the type of exception it can catch. It contains the code known as
exception handler
7) The catch blocks and finally block must always appear in conjunction with a try block.
22

8) The order of exception handlers in the catch block must be from the most specific

PROGRAM:

import java.util.Scanner;

public class FinallyBlockExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter a number to divide: ");
int numerator = scanner.nextInt();
System.out.print("Enter a number to divide by: ");
int denominator = scanner.nextInt();

// This may throw ArithmeticException


int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
// This block is always executed
System.out.println("Execution of the finally block.");
scanner.close();
}

System.out.println("Program has ended.");


}
}

OUTPUT:
23

9. Illustrate how Java handles overflows and underflows exception with example.

In Java, overflow and underflow situations occur when arithmetic operations exceed the range
of the data type. Java does not throw exceptions for integer overflows and underflows; instead,
it wraps around using modular arithmetic. However, it does provide checks for floating-point
overflows and underflows through special values like Infinity and NaN.

 Integer Overflow/Underflow: Integer types wrap around without throwing exceptions.


 Floating-Point Overflow/Underflow: Floating-point types result in Infinity or 0 when limits
are exceeded or fallen below.

Integer Overflow and Underflow

For integer types (e.g., byte, short, int, long), when the result of an operation exceeds the
maximum or minimum value, it wraps around.

OVERFLOW:

PROGRAM:

public class IntegerOverflowExample {


public static void main(String[] args) {
int maxInt = Integer.MAX_VALUE; // 2147483647
System.out.println("Max Integer: " + maxInt);

int overflowedValue = maxInt + 1; // Overflow occurs


System.out.println("Overflowed Value: " + overflowedValue); // -2147483648
}
}

OUTPUT:

UNDERFLOW:

PROGRAM:

public class IntegerUnderflowExample {


public static void main(String[] args) {
int minInt = Integer.MIN_VALUE; // -2147483648
System.out.println("Min Integer: " + minInt);
24

int underflowedValue = minInt - 1; // Underflow occurs


System.out.println("Underflowed Value: " + underflowedValue); // 2147483647
}
}

OUTPUT:

The minimum value for an int is -2147483648. When you subtract 1 from this value, it wraps
around to 2147483647, demonstrating underflow.

Floating-Point Overflow and Underflow


For floating-point types (float, double), when an operation exceeds the maximum range, it
results in Infinity, and operations that go below the minimum representable value can yield 0
or -0.
Example of Floating-Point Overflow:

public class FloatingPointOverflowExample {


public static void main(String[] args) {
double largeValue = Double.MAX_VALUE; // Largest double
System.out.println("Max Double: " + largeValue);

double overflowedValue = largeValue * 2; // Overflow occurs


System.out.println("Overflowed Value: " + overflowedValue); // Infinity
}
}

OUTPUT:

The maximum value for a double is approximately 1.7976931348623157E308. Multiplying it


by 2 causes an overflow, resulting in Infinity.

Example of Floating-Point Underflow:


25

public class FloatingPointUnderflowExample {


public static void main(String[] args) {
double smallValue = 1e-300; // A small double value
System.out.println("Small Value: " + smallValue);

double underflowedValue = smallValue / 10; // Underflow occurs


System.out.println("Underflowed Value: " + underflowedValue); // 0.0
}
}

OUTPUT:

The small value 1e-300 is significantly smaller than the minimum representable value.
Dividing it results in 0.0, demonstrating underflow.

10. Create your own exception for “Temperature>40” in an “Atomic Reactor Based
Application” and write appropriate exception handling code in the main program.

// Custom exception class for temperature exceeding 40 degrees


class TemperatureExceededException extends Exception {
public TemperatureExceededException(String message) {
super(message);
}
}

class AtomicReactor {
private double temperature;

public AtomicReactor(double initialTemperature) {


this.temperature = initialTemperature;
}
26

public void increaseTemperature(double increment) throws TemperatureExceededException {


temperature += increment;
if (temperature > 40) {
throw new TemperatureExceededException("Temperature exceeds 40 degrees!");
}
}

public double getTemperature() {


return temperature;
}
}

public class Main {


public static void main(String[] args) {
AtomicReactor reactor = new AtomicReactor(30);

try {
reactor.increaseTemperature(15); // This will throw an exception
System.out.println("Reactor temperature: " + reactor.getTemperature());
} catch (TemperatureExceededException e) {
System.err.println("Exception caught: " + e.getMessage());
System.err.println("Shutting down reactor due to excessive temperature...");
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}
27

OUTPUT:

You might also like