[Go to site: main page, start]

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

Java QB Module-4

The document outlines the concepts of exception handling and multithreading in Java, detailing the mechanisms for managing runtime errors, including the use of try, catch, and finally blocks. It classifies exceptions into checked and unchecked types, explains thread lifecycle stages, and discusses thread synchronization and critical sections. Additionally, it contrasts in-built exceptions with user-defined exceptions and highlights the importance of inter-thread communication in multithreaded applications.

Uploaded by

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

Java QB Module-4

The document outlines the concepts of exception handling and multithreading in Java, detailing the mechanisms for managing runtime errors, including the use of try, catch, and finally blocks. It classifies exceptions into checked and unchecked types, explains thread lifecycle stages, and discusses thread synchronization and critical sections. Additionally, it contrasts in-built exceptions with user-defined exceptions and highlights the importance of inter-thread communication in multithreaded applications.

Uploaded by

muraliking1107
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

E.G.S.

PILLAY ENGINEERING COLLEGE (Autonomous)


QB
NAGAPATTINAM – 611 002. (Affiliated to Anna University,
Chennai | Accredited by NAAC with ‘A++’ Grade Accredited Regulations 2023
by NBA | Approved by AICTE, New Delhi) CSE

Year/Semester :II/IV
2302CS405 - OBJECT ORIENTED PROGRAMMING IN JAVA
PART A (Marks : 02) Marks CO
CO : 4

1 Summarize the idea of exception handling in Java and list its advantages 2 CO4
Idea:
Exception handling in Java is a mechanism to handle runtime errors using try, catch, and finally
blocks, ensuring the program continues execution without abrupt termination.
Advantages:
 Ensures smooth program flow
 Prevents abnormal termination (crash)
 Improves code readability and maintainability
 Helps in handling errors effectively
2 Illustrate the “Divide by Zero” error in Java with a suitable example. 2 CO4
A divide by zero error occurs when a number is divided by zero. In Java, this causes an
ArithmeticException at runtime.
Example:
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 0;
int result = a / b; // Causes ArithmeticException
[Link](result);
}
}
Output:
Exception in thread "main" [Link]: / by zero
3 Classify the different types of exceptions in Java. 2 CO4
Exceptions in Java are classified into two main types:
1. Checked Exceptions
o Checked at compile time
o Must be handled using try-catch or declared with throws
o Example: IOException, SQLException
2. Unchecked Exceptions (Runtime Exceptions)
o Occur at runtime
o Not checked at compile time
o Example: ArithmeticException, NullPointerException
4 Outline the concept of in-built exceptions in Java 2 CO4
In-built exceptions are predefined exception classes provided by Java (in [Link] and other
packages) that handle common runtime errors automatically.
Examples:
 These exceptions help in identifying and handling standard errors efficiently.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
NumberFormatException
5 Explain the concept of threads in Java. 2 CO4
 A thread is the smallest unit of execution in a program that allows multiple tasks to run
concurrently. Java supports multithreading using the Thread class or Runnable interface.
 Threads improve performance by enabling parallel execution of tasks.
6 Justify the requirement for multi-threaded programming 2 CO4
Multithreaded programming is required to execute multiple tasks concurrently within a single program,
thereby improving overall efficiency.
Justification:
 Maximizes CPU utilization
 Reduces execution time
 Enhances application responsiveness
7 Describe the stages involved in the life cycle of a thread in Java 2 CO4
A thread in Java passes through different stages during its execution:
 New – Thread is created but not started
 Runnable – Thread is ready to run
 Running – Thread is executing
 Waiting/Blocked – Thread is paused or waiting for resources
 Terminated (Dead) – Thread has finished execution
👉 These stages define the complete life cycle of a thread.
8 Summarize the ways of creating threads in java 2 CO4
Threads in Java can be created in two standard ways:
1. Extending the Thread class – Override the run() method and call start()
2. Implementing the Runnable interface – Implement run() and pass the object to a Thread
👉 Both approaches enable multithreading and concurrent execution of tasks.
9 Interpret the concept of thread synchronization 2 CO4
 Thread synchronization is a mechanism used to control the access of multiple threads to a shared
resource, ensuring that only one thread executes a critical section at a time.
 It prevents data inconsistency and race conditions in multithreaded programs.
10 Explain the meaning of a critical section in multithreaded programming. 2 CO4
A critical section is a part of a program where shared resources (data) are accessed or modified
by multiple threads. It must be executed by only one thread at a time to avoid data inconsistency.
👉 Proper synchronization is required to protect the critical section and prevent race conditions.
CO4 PART A (Marks : 16) Mark CO
1. Classify the different types of exceptions and errors in Java with suitable
16 Co4
examples
Classification of Exceptions and Errors in Java
 In Java, an exception is an abnormal condition that disrupts the normal flow of a program during
execution. To handle such situations, Java provides a powerful exception handling mechanism.
 All exceptions and errors in Java are derived from the superclass Throwable, which is a part of
the [Link] package.

Hierarchy of Exceptions and Errors


At the top of the hierarchy is the class Throwable, which has two main subclasses:
1. Exception
2. Error
Throwable
/ \
Exception Error
|
----------------------------------
| |
Checked Exception Unchecked Exception
(Compile-time) (Runtime)

1. Exceptions in Java
Exceptions are conditions that occur during program execution and can be handled by the programmer.
Types of Exceptions
A. Checked Exceptions
Definition:
Checked exceptions are the exceptions that are checked at compile time. The Java compiler ensures that
these exceptions are either handled using a try-catch block or declared using the throws keyword.
Examples:
 IOException
 SQLException
 FileNotFoundException
 ClassNotFoundException

Example:
import [Link].*;
class CheckedDemo {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
} catch (FileNotFoundException e) {
[Link]("File not found");
}
}
}

Features:
 Checked during compilation
 Mandatory to handle
 Usually occur due to external resources

B. Unchecked Exceptions (Runtime Exceptions)


Definition:
Unchecked exceptions are those that occur during runtime and are not checked by the compiler.
Examples:
 ArithmeticException
 NullPointerException
 ArrayIndexOutOfBoundsException
 NumberFormatException

Example:
class UncheckedDemo {
public static void main(String[] args) {
int a = 10, b = 0;
int c = a / b; // causes ArithmeticException
}
}

Features:
 Occur at runtime
 Not mandatory to handle
 Caused by logical/programming errors

C. User-Defined Exceptions
Definition:
Java allows programmers to create their own exceptions by extending the Exception class.
Example:
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}
class Test {
public static void main(String[] args) {
try {
int age = 16;
if (age < 18) {
throw new InvalidAgeException("Not eligible");
}
} catch (InvalidAgeException e) {
[Link]([Link]());
}
}
}

Features:
 Custom exceptions for application-specific needs
 Improves readability and control

2. Errors in Java
Definition:
Errors are serious problems that arise due to system failures or JVM issues. They are not recoverable
and cannot be handled effectively by the program.

Examples:
 OutOfMemoryError
 StackOverflowError
 VirtualMachineError
 AssertionError
Example:
class ErrorDemo {
public static void main(String[] args) {
recursive();
}
static void recursive() {
recursive(); // leads to StackOverflowError
}
}

Features:
 Occur at runtime
 Caused by system-level issues
 Not meant to be handled using try-catch

3. Difference Between Exceptions and Errors


Aspect Exceptions Errors
Meaning Abnormal condition that can be handled Serious system problem
Handling Can be handled using try-catch Cannot be handled normally
Occurrence Compile time or runtime Only runtime
Cause Program logic or external issues JVM/system failure
StackOverflowError, OutOfMemory
Examples IOException, NullPointerException
Error
2. Demonstrate the use of try, catch, and finally blocks in handling runtime errors. 16 CO4
Demonstration of try, catch, and finally Blocks in Handling Runtime Errors
In Java, a runtime error (exception) is an unexpected event that occurs during the execution of a
program and disrupts its normal flow. To handle such situations, Java provides a structured mechanism
called exception handling using the keywords try, catch, and finally.
These blocks help in detecting, handling, and managing runtime errors, thereby ensuring the
smooth execution of programs without abrupt termination.

try Block
The try block is used to enclose the code that may generate an exception during execution.
Syntax:
try {
// risky code
}

Explanation:
 The statements that may cause an exception are placed inside the try block.
 A try block must be followed by at least one catch block or a finally block.
 If an exception occurs, the control is immediately transferred to the appropriate catch block.

catch Block
The catch block is used to handle the exception thrown from the try block.
Syntax:
catch (ExceptionType e) {
// exception handling code
}

Explanation:
 It catches and handles the specific type of exception.
 Multiple catch blocks can be used to handle different exceptions.
 The exception object (e) provides information about the error.

finally Block
The finally block is used to execute important code that must run regardless of whether an exception
occurs or not.
Syntax:
finally {
// cleanup code
}

Explanation:
 It is always executed after the try and catch blocks.
 It is commonly used for closing resources like files, database connections, etc.
 Even if an exception is not handled, the finally block will execute.

Working of try-catch-finally
1. The program starts execution inside the try block.
2. If no exception occurs, the catch block is skipped and the finally block executes.
3. If an exception occurs, the control moves to the matching catch block.
4. After executing the catch block, the finally block is executed.

Demonstration with Example


Program:
class TryCatchFinallyDemo {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // causes ArithmeticException
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Exception caught: Division by zero is not allowed");
}
finally {
[Link]("Finally block executed");
}
}
}
Output:
Exception caught: Division by zero is not allowed
Finally block executed

Example with Multiple catch Blocks


class MultipleCatchExample {
public static void main(String[] args) {
try {
int arr[] = new int[5];
arr[10] = 30; // ArrayIndexOutOfBoundsException
}
catch (ArithmeticException e) {
[Link]("Arithmetic Exception");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Out of Bounds Exception");
}
finally {
[Link]("Execution completed");
}
}
}

Example Without Exception


class NoExceptionExample {
public static void main(String[] args) {
try {
int a = 10, b = 2;
int result = a / b;
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Exception occurred");
}
finally {
[Link]("Finally block always executes");
}
}
}

Advantages of try-catch-finally
 Prevents abnormal termination of programs
 Maintains normal flow of execution
 Helps in identifying and handling runtime errors
 Improves program reliability and robustness
 Ensures proper resource management through finally
3. i). Show the difference between throw and throws by using them in Java
programs
16 CO4
ii). Construct a comparison between in-built exceptions and user-defined
exceptions in Java
i) Difference between throw and throws with Java Programs
In Java exception handling, the keywords throw and throws are used to manage exceptions.
Although they appear similar, they have different purposes and usage in a program.

throw Keyword
The throw keyword is used to explicitly throw an exception from within a method or block of code.
Explanation:
 It is used when the programmer wants to manually create and throw an exception.
 It transfers control immediately to the nearest catch block.
 Only one exception can be thrown at a time.

Syntax:
throw new ExceptionType("message");

Program using throw:


class ThrowDemo {
public static void main(String[] args) {
int age = 16;
try {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
[Link]("Eligible to vote");
}
catch (ArithmeticException e) {
[Link]([Link]());
}
}
}
Output:
Not eligible to vote

throws Keyword
The throws keyword is used in a method declaration to declare one or more exceptions that a method
may throw.
Explanation:
 It informs the caller of the method about possible exceptions.
 It is mainly used with checked exceptions.
 The calling method must handle or further declare the exception.

Syntax:
returnType methodName() throws ExceptionType {
// code
}

Program using throws:


import [Link].*;
class ThrowsDemo {
static void readFile() throws IOException {
FileReader fr = new FileReader("[Link]");
}
public static void main(String[] args) {
try {
readFile();
}
catch (IOException e) {
[Link]("File handling error");
}
}
}
Output:
File handling error

Difference between throw and throws


Aspect throw throws
Definition Used to explicitly throw an exception Used to declare exceptions
Placement Inside method/block In method declaration
Number of Exceptions Only one at a time Multiple exceptions allowed
Usage Programmer creates exception Method passes exception to caller
Type Statement Keyword (declaration)

ii) Comparison between In-built Exceptions and User-defined Exceptions


Java provides in-built exceptions for common errors. However, programmers can create user-defined
exceptions to handle specific application requirements.

In-built Exceptions
In-built exceptions are predefined exceptions available in Java libraries.
Explanation:
 These exceptions are automatically generated by Java runtime.
 Used to handle common errors like arithmetic errors, null references, etc.

Examples:
 ArithmeticException
 NullPointerException
 ArrayIndexOutOfBoundsException
 IOException

Program (In-built Exception):


class BuiltInDemo {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int c = a / b;
}
catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
}
}
Output:
Cannot divide by zero

User-defined Exceptions
User-defined exceptions are custom exceptions created by the programmer by extending the
Exception class.
Explanation:
 Used for application-specific conditions
 Helps in better control and readability

Program (User-defined Exception):


class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}
class UserDefinedDemo {
public static void main(String[] args) {
int age = 15;
try {
if (age < 18) {
throw new InvalidAgeException("Not eligible to vote");
}
}
catch (InvalidAgeException e) {
[Link]([Link]());
}
}
}
Output:
Not eligible to vote

Comparison Table
Aspect In-built Exceptions User-defined Exceptions
Definition Predefined in Java Created by programmer
Availability Available in libraries Must be created manually
Purpose Handle common errors Handle specific conditions
Flexibility Limited Highly flexible
Example ArithmeticException InvalidAgeException
4. i). Demonstrate inter-thread communication and justify its importance in
multithreaded Applications
16 C04
ii). Apply the concept of critical section and identify the critical factors involved
in multithreading
i) Inter-Thread Communication and Its Importance in Multithreaded Applications
In multithreading, multiple threads run concurrently and often need to share data. To avoid
problems like data inconsistency and unnecessary CPU usage, Java provides a mechanism called inter-
thread communication.
Inter-thread communication allows threads to communicate and coordinate with each other,
mainly using the methods:
 wait()
 notify()
 notifyAll()
These methods are defined in the Object class.

Concept of Inter-Thread Communication


 It is used when one thread depends on the result of another thread.
 It avoids busy waiting (continuous checking).
 Threads can pause and resume execution in a controlled manner.

Methods Used
1. wait()
 Causes the current thread to release the lock and enter waiting state.
2. notify()
 Wakes up one waiting thread.
3. notifyAll()
 Wakes up all waiting threads.

Program Demonstration (Producer–Consumer Problem)


class Shared {
int data;
boolean hasValue = false;
synchronized void produce(int value) {
try {
if (hasValue)
wait(); // wait until consumed
data = value;
[Link]("Produced: " + data);
hasValue = true;
notify(); // notify consumer
} catch (InterruptedException e) {
[Link](e);
}
}
synchronized void consume() {
try {
if (!hasValue)
wait(); // wait until produced
[Link]("Consumed: " + data);
hasValue = false;
notify(); // notify producer
} catch (InterruptedException e) {
[Link](e);
}
}
}
class Producer extends Thread {
Shared s;
Producer(Shared s) { this.s = s; }

public void run() {


for (int i = 1; i <= 5; i++) {
[Link](i);
}
}
}

class Consumer extends Thread {


Shared s;
Consumer(Shared s) { this.s = s; }

public void run() {


for (int i = 1; i <= 5; i++) {
[Link]();
}
}
}
public class InterThreadDemo {
public static void main(String[] args) {
Shared s = new Shared();
new Producer(s).start();
new Consumer(s).start();
}
}

Importance of Inter-Thread Communication


 Ensures proper coordination between threads
 Prevents data inconsistency
 Avoids CPU wastage (busy waiting)
 Improves performance and efficiency
 Enables safe data sharing

ii) Critical Section and Factors in Multithreading


In multithreading, multiple threads may access shared resources such as variables, files, or objects. The
portion of code where shared resources are accessed is called the critical section.

Definition of Critical Section


A critical section is a part of the program where shared resources are accessed or modified, and it
must not be executed by more than one thread at a time.

Example of Critical Section


class Counter {
int count = 0;
synchronized void increment() { // critical section
count++;
}
}

class MyThread extends Thread {


Counter c;
MyThread(Counter c) { this.c = c; }

public void run() {


for (int i = 0; i < 1000; i++) {
[Link]();
}
}
}
public class CriticalSectionDemo {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
MyThread t1 = new MyThread(c);
MyThread t2 = new MyThread(c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Final Count: " + [Link]);
}
}

Explanation
 The method increment() is synchronized, so only one thread can execute it at a time.
 This prevents race conditions and ensures correct output.

Critical Section Problem


If multiple threads access the critical section simultaneously, it may lead to:
 Race condition
 Data inconsistency
 Unexpected results

Critical Factors in Multithreading


1. Mutual Exclusion
 Only one thread can execute the critical section at a time.
 Achieved using synchronized.
2. Progress
 If no thread is in the critical section, another thread should be allowed to enter.
3. Bounded Waiting
 A thread should not wait indefinitely to enter the critical section.
4. Synchronization
 Proper coordination between threads to avoid conflicts.
5. Deadlock Avoidance
 Threads should not get stuck waiting for each other.

Techniques to Handle Critical Section


 synchronized keyword
 Locks (ReentrantLock)
 Semaphores (advanced)
5. Apply the concept of threads and multithreading in Java to a real-time application
16 C04
scenario
Application of Threads and Multithreading in Java (Real-Time Scenario)
A thread is the smallest unit of execution within a program. Java supports
multithreading, which allows multiple threads to run concurrently within a single
program.
Multithreading improves performance, responsiveness, and resource
utilization, especially in real-time applications where multiple tasks must be performed
simultaneously.

Concept of Threads in Java


 A thread is created using:
o Extending the Thread class
o Implementing the Runnable interface
 Each thread runs independently but shares the same memory space.

Multithreading
Multithreading is the process of executing two or more threads concurrently to
perform multiple tasks efficiently.
Advantages:
 Better CPU utilization
 Faster execution
 Improved application responsiveness
 Efficient resource sharing

Real-Time Application Scenario: Online Banking System


Problem Description
In an online banking system, multiple users perform operations simultaneously such as:
 Checking balance
 Depositing money
 Withdrawing money
These operations must run concurrently without causing errors like incorrect balance
updates.

Application of Multithreading
 Each user request is handled by a separate thread
 Shared resource → Bank Account balance
 Synchronization is required to avoid race conditions

Java Program (Multithreading in Banking System)


class BankAccount {
private int balance = 1000;
// synchronized method (critical section)
synchronized void deposit(int amount) {
balance += amount;
[Link]([Link]().getName() +
" Deposited: " + amount + " | Balance: " + balance);
}

synchronized void withdraw(int amount) {


if (balance >= amount) {
balance -= amount;
[Link]([Link]().getName() +
" Withdrawn: " + amount + " | Balance: " + balance);
} else {
[Link]([Link]().getName() +
" Insufficient Balance");
}
}
}

class User extends Thread {


BankAccount account;

User(BankAccount account, String name) {


super(name);
[Link] = account;
}
public void run() {
[Link](500);
[Link](700);
}
}
public class BankingApp {
public static void main(String[] args) {
BankAccount account = new BankAccount();
User u1 = new User(account, "User1");
User u2 = new User(account, "User2");
[Link]();
[Link]();
}
}

Explanation
 BankAccount is a shared resource.
 deposit() and withdraw() methods are synchronized to avoid conflicts.
 Multiple threads (User1, User2) perform operations simultaneously.
 Synchronization ensures correct balance updates.

Other Real-Time Applications of Multithreading


1. Web Servers
o Handle multiple client requests simultaneously
2. Online Shopping Systems
o Multiple users browsing and placing orders
3. Chat Applications
o Sending and receiving messages concurrently
4. Video Streaming
o Buffering and playing video at the same time
5. Gaming Applications
o Graphics rendering, input handling, and game logic run in parallel

Key Concepts Applied


 Thread creation (Thread class)
 Concurrent execution
 Shared resources
 Synchronization (synchronized)
 Avoiding race conditions

Advantages in Real-Time Scenario


 Faster processing of multiple requests
 Better user experience
 Efficient use of CPU
 Reduced waiting time
6. Design the life cycle of a thread by examining its various states and transitions with a neat diagram
Thread Life Cycle in Java
A thread is the smallest unit of execution in a program. In Java, each thread passes through a
sequence of stages from its creation to termination. These stages are collectively known as the Thread
Life Cycle.
Understanding the life cycle helps in controlling thread execution and improving the
performance of multithreaded applications.

Thread Life Cycle States


A thread in Java goes through the following five main states:
1. New (Born) State
2. Runnable State
3. Running State
4. Blocked / Waiting State
5. Terminated (Dead) State

Neat Diagram of Thread Life Cycle

1. New (Born) State


Definition:
 A thread is in the new state when it is created but not yet started.
Example:
Thread t = new Thread();
Key Point:
 Thread object is created, but start() method is not called.

2. Runnable State
Definition:
 After calling start(), the thread enters the runnable state.
 It is ready to run and waiting for CPU time.
Example:
[Link]();
Key Point:
 Thread scheduler decides when the thread will execute.

3. Running State
Definition:
 When the thread gets CPU time, it enters the running state.
Key Point:
 The thread executes the run() method.

4. Blocked / Waiting State


Definition:
 A thread enters this state when it is temporarily inactive.
Causes:
 sleep()
 wait()
 Waiting for I/O
 Waiting for lock (synchronization)
Example:
[Link](1000);
Key Point:
 After completion of waiting condition, thread returns to runnable state.

5. Terminated (Dead) State


Definition:
 A thread enters this state after completing execution.
Key Point:
 Once terminated, a thread cannot be restarted.

State Transitions
From State To State Method/Condition
New Runnable start()
Runnable Running CPU scheduling
Running Waiting/Blocked sleep(), wait()
Waiting Runnable notify(), timeout
Running Terminated End of run()
Program Demonstrating Thread Life Cycle
class LifeCycleDemo extends Thread {
public void run() {
[Link]("Thread is running");
try {
[Link](1000); // moves to waiting state
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Thread finished execution");
}
public static void main(String[] args) {
LifeCycleDemo t = new LifeCycleDemo();
[Link]("State after creation: " + [Link]());
[Link]();
[Link]("State after start: " + [Link]());
}
}

Explanation of Program
 Thread is initially in New state
 After calling start(), it moves to Runnable state
 When CPU is assigned → Running state
 sleep() → moves to Waiting state
 After execution → Terminated state

Importance of Thread Life Cycle


 Helps in efficient thread management
 Prevents deadlock and resource conflicts
 Improves performance and responsiveness
 Ensures proper synchronization

You might also like