Oops Unit4
Oops Unit4
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
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
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
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
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
All exceptions and errors extend from a common java.lang. Throwable parent class.
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
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;
// Test ArrayIndexOutOfBoundsException
try {
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] array = new int[size];
}
}
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).
8) The order of exception handlers in the catch block must be from the most specific
PROGRAM:
import java.util.Scanner;
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();
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.
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:
OUTPUT:
UNDERFLOW:
PROGRAM:
OUTPUT:
The minimum value for an int is -2147483648. When you subtract 1 from this value, it wraps
around to 2147483647, demonstrating underflow.
OUTPUT:
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.
class AtomicReactor {
private double temperature;
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: