0% found this document useful (0 votes)
2 views

JAVA-UNIT_3

The document provides an overview of Java applets, multithreading, and multitasking, detailing their definitions, key features, lifecycle, and execution methods. It includes examples of Java code for applets and multithreading, explaining their functionality and benefits. Additionally, it compares process-based and thread-based multitasking, highlighting their characteristics and efficiency.

Uploaded by

SS GAMER
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA-UNIT_3

The document provides an overview of Java applets, multithreading, and multitasking, detailing their definitions, key features, lifecycle, and execution methods. It includes examples of Java code for applets and multithreading, explaining their functionality and benefits. Additionally, it compares process-based and thread-based multitasking, highlighting their characteristics and efficiency.

Uploaded by

SS GAMER
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

JAVA-UNIT 3

1. Applet in Java

What is an Applet?
An applet is a small Java program that runs inside a web browser or applet
viewer. It is part of the java.applet package and is used for creating interactive,
graphical applications embedded within web pages.

Key Features of Applets:


1. Execution: Runs within a browser or applet viewer.

2. Security Restrictions: Cannot access local files or other resources for


security reasons.

3. GUI: Supports graphical elements and user interactions.

4. No main() Method: The lifecycle of an applet is managed by the browser or


applet viewer.

Applet Lifecycle:
init(): Called when the applet is initialized.

start(): Called when the applet starts or becomes active.

stop(): Called when the applet is stopped.

destroy(): Called when the applet is terminated.

Example from PDF:

import java.applet.Applet;
import java.awt.Graphics;

public class FirstApplet extends Applet {


public void paint(Graphics g) {
g.drawString("Welcome to Applet!", 50, 50);
}
}

Explanation:
1. The import java.applet.Applet statement includes the Applet class.

2. paint(Graphics g) :

This method is used to draw on the applet window.

The drawString method draws the string "Welcome to Applet!" at the


specified coordinates (50, 50) .

JAVA-UNIT 3 1
HTML File to Run the Applet:

<html>
<body>
<applet code="FirstApplet.class" width="300" height
="300">
</applet>
</body>
</html>

How to Execute:
1. Compile the applet using:

javac FirstApplet.java

2. Open the HTML file in a browser or run using:

appletviewer FirstApplet.html

2. Applet Lifecycle
The lifecycle of an applet defines how it behaves from initialization to destruction.
It is managed by the browser or applet viewer using specific methods.

Applet Lifecycle Methods:


1. init() :

Called once when the applet is first loaded.

Used to initialize variables, set up the UI, or perform any one-time setup
tasks.

2. start() :

Called after init() or whenever the applet becomes active (e.g., when the
browser is refreshed or revisited).

Used for starting animations or any other repeated tasks.

3. paint(Graphics g) :

Called when the applet window needs to be redrawn.

Contains code for rendering graphics or displaying output.

4. stop() :

Called when the applet is no longer active (e.g., when the browser
navigates away or the tab is minimized).

Used to pause animations or tasks.

5. destroy() :

JAVA-UNIT 3 2
Called once before the applet is destroyed.

Used to release resources or perform cleanup operations.

Lifecycle Diagram:

init() -> start() -> paint() -> stop() -> destroy()

Example from PDF:

import java.applet.Applet;
import java.awt.Graphics;

public class LifeCycleDemo extends Applet {


public void init() {
System.out.println("Applet Initialized");
}

public void start() {


System.out.println("Applet Started");
}

public void paint(Graphics g) {


g.drawString("Applet Lifecycle Demo", 20, 20);
}

public void stop() {


System.out.println("Applet Stopped");
}

public void destroy() {


System.out.println("Applet Destroyed");
}
}

Explanation:
1. init() : Prints "Applet Initialized" when the applet is loaded.

2. start() : Prints "Applet Started" when the applet becomes active.

3. paint(Graphics g) : Displays "Applet Lifecycle Demo" on the screen.

4. stop() : Prints "Applet Stopped" when the applet becomes inactive.

5. destroy() : Prints "Applet Destroyed" before termination.

HTML to Run the Applet:

JAVA-UNIT 3 3
<html>
<body>
<applet code="LifeCycleDemo.class" width="300" height
="300">
</applet>
</body>
</html>

Execution Steps:
1. Compile the applet:

javac LifeCycleDemo.java

2. Open the HTML file in a browser or use:

appletviewer LifeCycleDemo.html

3. Multithreading

What is Multithreading?
Multithreading is a feature of Java that allows the concurrent execution of
two or more parts of a program, called threads. Each thread runs
independently, sharing the program's resources.

Key Concepts:
1. Thread: A lightweight subprocess that can execute independently.

2. Multithreading: The ability to run multiple threads simultaneously for better


resource utilization and performance.

3. Concurrency: Ensures multiple threads execute without conflict.

Benefits of Multithreading:
1. Improved Performance: Tasks like file I/O, network calls, or computations can
run simultaneously.

2. Efficient Resource Utilization: Threads share memory and system resources.

3. Responsiveness: Applications, especially GUI-based, remain responsive


during lengthy operations.

Example from PDF:

class MultithreadDemo extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName

JAVA-UNIT 3 4
() + ": " + i);
try {
Thread.sleep(500); // Pauses thread for 500ms
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public static void main(String[] args) {


MultithreadDemo t1 = new MultithreadDemo();
MultithreadDemo t2 = new MultithreadDemo();

t1.start(); // Starts thread t1


t2.start(); // Starts thread t2
}
}

Explanation:
1. Extending Thread Class:

The MultithreadDemo class extends Thread .

The run() method contains the logic to be executed by the thread.

2. Creating Threads:

Two threads ( t1 and t2 ) are created using the MultithreadDemo class.

3. Starting Threads:

The start() method is called to begin thread execution, invoking the run()

method.

4. Thread Sleep:

Thread.sleep(500) pauses the thread for 500 milliseconds.

Output Example:
The output may interleave depending on thread scheduling:

Thread-0: 1
Thread-1: 1
Thread-0: 2
Thread-1: 2
...

4. Advantages of Java Multithreading


Multithreading is one of the most powerful features of Java, providing several
advantages for modern applications. Below are the key benefits:

JAVA-UNIT 3 5
1. Efficient Utilization of CPU
Multithreading ensures that the CPU is not idle while waiting for tasks like file
I/O or network operations. Instead, it can switch to other threads, improving
CPU utilization.

2. Concurrent Execution
Threads run simultaneously, allowing multiple tasks to be performed at the
same time, such as updating the UI while processing data in the background.

3. Improved Application Responsiveness


Applications, especially GUI-based ones, remain responsive by performing
time-consuming operations in separate threads. For example:

Loading data in the background while keeping the interface interactive.

4. Simplifies Complex Applications


Tasks can be divided into smaller independent threads, making it easier to
write, manage, and debug complex programs.

5. Resource Sharing
Threads within the same process share memory and other system resources,
reducing the overhead compared to creating multiple processes.

6. Scalability
Multithreaded applications can handle increasing workloads effectively by
distributing tasks across threads, especially on multi-core systems.

Example from PDF:

class Counter extends Thread {


private int count;

public Counter(int start) {


this.count = start;
}

public void run() {


for (int i = count; i < count + 5; i++) {
System.out.println(Thread.currentThread().getName
() + ": " + i);
try {
Thread.sleep(300); // Simulate some work
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

JAVA-UNIT 3 6
public static void main(String[] args) {
Counter thread1 = new Counter(1);
Counter thread2 = new Counter(10);

thread1.start(); // Start first thread


thread2.start(); // Start second thread
}
}

Explanation:
1. Two Threads, Different Workloads:

thread1 starts counting from 1.

thread2 starts counting from 10.

2. Concurrent Execution:

Both threads execute their loops concurrently.

3. Thread.sleep():

Each thread pauses for 300 milliseconds, allowing the CPU to switch to
other tasks.

Output Example:
The output demonstrates concurrent execution:

Thread-0: 1
Thread-1: 10
Thread-0: 2
Thread-1: 11
...

5. Multitasking

What is Multitasking?
Multitasking refers to executing multiple tasks simultaneously. In computing,
it allows a system to perform various operations concurrently, improving
resource utilization and system efficiency.

Types of Multitasking:
1. Process-Based Multitasking:

Involves executing multiple processes (programs) simultaneously.

Each process operates independently and has its own memory space.

Example:

JAVA-UNIT 3 7
Running a media player, a browser, and a text editor simultaneously.

Key Characteristics:

Heavyweight tasks.

Requires significant context-switching overhead.

Processes are isolated from each other.

2. Thread-Based Multitasking:

Involves executing multiple threads of a single process.

Threads share the same memory space and resources, making it


lightweight compared to processes.

Example:

A web server handling multiple client requests using threads.

Key Characteristics:

Lightweight tasks.

Less overhead as threads share memory and resources.

More efficient for smaller tasks within the same application.

Comparison Table: Process-Based vs. Thread-Based Multitasking


Feature Process-Based Thread-Based

Execution Unit Independent processes Threads within a single process

Memory Separate memory space Shared memory space

Overhead High (context-switching) Low (shared resources)

Efficiency Suitable for large tasks Suitable for small tasks

Example of Thread-Based Multitasking from PDF:

class Task implements Runnable {


private String taskName;

public Task(String name) {


this.taskName = name;
}

public void run() {


for (int i = 1; i <= 5; i++) {
System.out.println(taskName + ": " + i);
try {
Thread.sleep(500); // Simulate task delay
} catch (InterruptedException e) {
System.out.println(e);
}
}

JAVA-UNIT 3 8
}

public static void main(String[] args) {


Thread t1 = new Thread(new Task("Task A"));
Thread t2 = new Thread(new Task("Task B"));

t1.start(); // Start Task A


t2.start(); // Start Task B
}
}

Explanation:
1. Two Threads:

t1 performs "Task A."

t2 performs "Task B."

2. Thread.sleep():

Introduces a delay between iterations, simulating multitasking.

3. Concurrency:

Both threads execute concurrently, improving responsiveness.

Output Example:

Task A: 1
Task B: 1
Task A: 2
Task B: 2
...

5. Multitasking

What is Multitasking?
Multitasking refers to executing multiple tasks simultaneously. In computing,
it allows a system to perform various operations concurrently, improving
resource utilization and system efficiency.

Types of Multitasking:
1. Process-Based Multitasking:

Involves executing multiple processes (programs) simultaneously.

Each process operates independently and has its own memory space.

Example:

Running a media player, a browser, and a text editor simultaneously.

JAVA-UNIT 3 9
Key Characteristics:

Heavyweight tasks.

Requires significant context-switching overhead.

Processes are isolated from each other.

2. Thread-Based Multitasking:

Involves executing multiple threads of a single process.

Threads share the same memory space and resources, making it


lightweight compared to processes.

Example:

A web server handling multiple client requests using threads.

Key Characteristics:

Lightweight tasks.

Less overhead as threads share memory and resources.

More efficient for smaller tasks within the same application.

Comparison Table: Process-Based vs. Thread-Based Multitasking

Feature Process-Based Thread-Based

Execution Unit Independent processes Threads within a single process

Memory Separate memory space Shared memory space

Overhead High (context-switching) Low (shared resources)

Efficiency Suitable for large tasks Suitable for small tasks

Example of Thread-Based Multitasking from PDF:

class Task implements Runnable {


private String taskName;

public Task(String name) {


this.taskName = name;
}

public void run() {


for (int i = 1; i <= 5; i++) {
System.out.println(taskName + ": " + i);
try {
Thread.sleep(500); // Simulate task delay
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

JAVA-UNIT 3 10
public static void main(String[] args) {
Thread t1 = new Thread(new Task("Task A"));
Thread t2 = new Thread(new Task("Task B"));

t1.start(); // Start Task A


t2.start(); // Start Task B
}
}

Explanation:
1. Two Threads:

t1 performs "Task A."

t2 performs "Task B."

2. Thread.sleep():

Introduces a delay between iterations, simulating multitasking.

3. Concurrency:

Both threads execute concurrently, improving responsiveness.

Output Example:

Task A: 1
Task B: 1
Task A: 2
Task B: 2
...

6. Thread in Java

What is a Thread?
A thread is the smallest unit of a program that can execute independently.

Threads in Java allow programs to perform multiple tasks simultaneously


within a single process.

Characteristics of a Thread:
1. Lightweight:

Threads share memory and resources with other threads in the same
process, making them efficient compared to processes.

2. Independent Execution:

Threads can execute concurrently without affecting each other.

3. Concurrency:

JAVA-UNIT 3 11
Allows multiple threads to execute simultaneously on multi-core
processors.

Thread Class in Java:


Java provides the java.lang.Thread class to create and manage threads.

Key Components of the Thread Class:

Constructors: Used to create thread instances.

Methods: Control thread execution (e.g., start() , run() , sleep() ).

Example from PDF:

class MyThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName
() + ": " + i);
try {
Thread.sleep(500); // Pause for 500ms
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public static void main(String[] args) {


MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

t1.start(); // Start thread t1


t2.start(); // Start thread t2
}
}

Explanation:
1. Extending Thread :

The MyThread class extends the Thread class, and its run() method defines
the task for the thread.

2. Thread Creation:

t1 and t2 are instances of MyThread .

3. Thread Execution:

Calling start() on a thread object invokes the run() method in a separate


thread.

4. Thread.sleep():

JAVA-UNIT 3 12
Introduces a delay of 500 milliseconds between iterations to simulate
multitasking.

Output Example:
The output interleaves due to concurrent execution:

Thread-0: 1
Thread-1: 1
Thread-0: 2
Thread-1: 2
...

7. Thread Class in Java

What is the Thread Class?


The java.lang.Thread class provides methods and mechanisms to create and
manage threads in Java.

Threads can be created by:

1. Extending the Thread class.

2. Implementing the Runnable interface (discussed later).

Key Components of the Thread Class:


1. Constructors:

Common constructors to create a thread:

Thread() : Creates a new thread without specifying a target.

Thread(Runnable target) : Creates a new thread with a specified target


( Runnable object).

Thread(String name) : Creates a thread with a specific name.

Thread(Runnable target, String name) : Creates a thread with a target and a


name.

2. Methods in the Thread Class:

start() : Starts the execution of the thread.

run() : Contains the task to be performed by the thread.

sleep(long millis) : Pauses the thread for the specified time.

join() : Waits for the thread to complete.

isAlive() : Checks if the thread is still running.

setName(String name) : Sets the name of the thread.

getName() : Gets the name of the thread.

Example from PDF:

JAVA-UNIT 3 13
class DemoThread extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(getName() + ": " + i);
try {
Thread.sleep(500); // Pause for 500ms
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public static void main(String[] args) {


DemoThread t1 = new DemoThread();
DemoThread t2 = new DemoThread();

t1.setName("Thread-A"); // Set thread name


t2.setName("Thread-B");

t1.start(); // Start t1
t2.start(); // Start t2
}
}

Explanation:
1. Thread Creation:

t1 and t2 are instances of the DemoThread class.

The setName(String name) method assigns names to threads.

2. Thread Execution:

The start() method begins execution, invoking the run() method in a


separate thread.

3. Thread.sleep():

Pauses each thread for 500 milliseconds during execution.

Output Example:
The output may vary due to thread interleaving:

Thread-A: 1
Thread-B: 1
Thread-A: 2
Thread-B: 2
Thread-A: 3
Thread-B: 3

JAVA-UNIT 3 14
Use Cases of the Thread Class:
Background Tasks: Perform long-running operations like file downloads or
database queries without freezing the main thread.

Parallel Processing: Execute multiple computations or tasks simultaneously


for improved performance.

8. Life Cycle of a Thread (Thread States)

Thread Life Cycle Stages:


1. New:

A thread is created but has not started execution.

State: NEW .

Example:

Thread t = new Thread();

2. Runnable:

After calling the start() method, the thread enters the Runnable state.

The thread is ready to run but awaits the thread scheduler for CPU
allocation.

State: RUNNABLE .

3. Running:

When the thread scheduler picks a thread from the runnable pool, it enters
the running state.

State: RUNNING .

4. Blocked/Waiting:

If a thread is waiting for a resource or another thread, it enters the blocked


or waiting state.

State: WAITING or BLOCKED .

Example:

Thread.sleep(1000);

5. Terminated:

A thread finishes execution and enters the terminated state.

State: TERMINATED .

9. Creating a Thread
Threads can be created in two main ways:

JAVA-UNIT 3 15
1. By Extending the Thread Class:
A class is created by extending the Thread class and overriding its run()

method.

Example from PDF:

class MyThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getN
ame() + ": " + i);
}
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

t1.start();
t2.start();
}
}

2. By Implementing the Runnable Interface:


The Runnable interface defines a single method, run() .

A class implements Runnable and passes an instance to a Thread object.

Example:

class MyRunnable implements Runnable {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getN
ame() + ": " + i);
}
}
}

public class ThreadExample {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());

t1.start();
t2.start();

JAVA-UNIT 3 16
}
}

10. Common Methods of the Thread Class

Key Methods:
1. start():

Starts the thread and calls the run() method.

Example: t1.start();

2. run():

Contains the code executed by the thread.

Example: public void run() { ... }

3. sleep(long millis):

Pauses the thread for the specified duration.

Example:

try {
Thread.sleep(1000); // Pauses for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}

4. join():

Waits for the thread to finish before proceeding.

Example: t1.join();

5. isAlive():

Checks if a thread is still running.

Example:

if (t1.isAlive()) {
System.out.println("Thread is running");
}

6. yield():

Suggests that the current thread allows other threads to execute.

11. Runnable Interface

Overview:

JAVA-UNIT 3 17
The Runnable interface is a functional interface used to define the task for a
thread.

It contains only one method:

public void run();

Why Use Runnable?


Allows a class to inherit from another class while still being able to create a
thread.

Example:

class MyRunnable implements Runnable {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName
() + ": " + i);
}
}
}

public class RunnableExample {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());

t1.start(); // Start thread t1


t2.start(); // Start thread t2
}
}

12. Starting a Thread


In Java, threads can be started by calling the start() method on a thread object.
This method invokes the run() method, which contains the logic to be executed
by the thread.

Steps to Start a Thread:


1. Create a Thread Object: You either extend the Thread class or implement the
Runnable interface.

2. Call the start() Method: Once a thread object is created, call the start()

method to begin the execution.

3. Thread Scheduling: The thread scheduler decides when each thread will run.

Example from PDF:

JAVA-UNIT 3 18
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}

public static void main(String[] args) {


MyThread t = new MyThread();
t.start(); // Starts the thread
}
}

Explanation:
start()triggers the run() method, allowing the thread to execute its task. It
ensures the thread runs concurrently with the main thread.

13. Exception Handling in Java


Exception handling in Java is used to manage runtime errors and maintain the
normal flow of the application. Java provides a powerful mechanism for handling
errors using the try , catch , finally , throw , and throws keywords.

Key Concepts:
1. try: Defines a block of code to monitor for exceptions.

2. catch: Catches and handles the exception thrown from the try block.

3. finally: Contains code that is always executed, regardless of whether an


exception was thrown or not.

4. throw: Used to explicitly throw an exception.

5. throws: Declares the types of exceptions that a method can throw.

Example from PDF:

class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an Arith
meticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}

JAVA-UNIT 3 19
Explanation:
try block: Contains the code that might throw an exception.

catch block: Handles the ArithmeticException thrown by the division by zero.

finally block: Executes regardless of the exception outcome, ensuring that


cleanup code (like closing files) runs.

14. Advantages of Exception Handling

Why Use Exception Handling in Java?


1. Improved Error Detection: Helps detect and handle errors at runtime instead
of crashing the program.

2. Separation of Error-Handling Code: Keeps the code clean by separating


normal logic from error-handling logic.

3. Program Continuity: Allows the program to continue running even if an


exception occurs.

4. Graceful Termination: Ensures that resources are cleaned up, and errors are
properly handled without leaving the system in an inconsistent state.

Example of Graceful Handling:


Instead of allowing a program to crash, we can handle the error:

public class FileReaderExample {


public static void main(String[] args) {
try {
// Code that may throw an exception
FileReader reader = new FileReader("nonexistent.t
xt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMess
age());
}
}
}

15. Hierarchy of Exception Classes


Java has a built-in exception hierarchy that classifies exceptions based on their
type and usage.

1. Throwable:

The superclass of all errors and exceptions.

Divided into two main categories:

Error: Serious issues that are typically outside the control of the
program (e.g., OutOfMemoryError , StackOverflowError ).

JAVA-UNIT 3 20
Exception: Issues that can be handled by the program.

2. Exception:

Checked Exceptions: Exceptions that are checked at compile time (e.g.,


IOException , SQLException ).

Unchecked Exceptions: Runtime exceptions that do not need to be


explicitly declared or handled (e.g., NullPointerException , ArithmeticException ).

Exception Class Hierarchy:

Throwable
├── Error
└── Exception
├── IOException (Checked)
├── SQLException (Checked)
└── RuntimeException (Unchecked)
├── NullPointerException
└── ArithmeticException

16. Types of Exceptions


Java exceptions are categorized into Checked and Unchecked Exceptions.

1. Checked Exceptions:
These are exceptions that are checked at compile-time.

The programmer must handle these exceptions either with a try-catch block or
by declaring them using the throws keyword.

Examples:

IOException : Thrown when an input/output operation fails.

SQLException : Thrown when there is an error interacting with a database.

Example:

import java.io.*;

public class CheckedExceptionExample {


public static void main(String[] args) throws IOExcept
ion {
FileReader file = new FileReader("file.txt");
BufferedReader reader = new BufferedReader(file);
reader.readLine();
}
}

2. Unchecked Exceptions:

JAVA-UNIT 3 21
These exceptions are not checked at compile-time. They occur at runtime.

Unchecked exceptions extend RuntimeException and typically indicate


programming errors.

Examples:

ArithmeticException : Occurs when a mathematical operation is invalid (e.g.,


division by zero).

NullPointerException : Occurs when trying to access or modify a null object


reference.

Example:

public class UncheckedExceptionExample {


public static void main(String[] args) {
int result = 10 / 0; // ArithmeticException (divi
de by zero)
}
}

3. Errors:
Errors are usually not recoverable and represent serious problems like
hardware failures.

Examples:

OutOfMemoryError : Occurs when the JVM runs out of memory.

StackOverflowError: Occurs when the call stack is exhausted, typically due to


infinite recursion.

17. Common Scenarios Where Exceptions May Occur


Exceptions in Java typically occur in the following situations:

1. File Operations:

Trying to read from or write to a file that does not exist, or lacks
appropriate permissions, can throw exceptions like FileNotFoundException .

Example:

FileReader fr = new FileReader("nonexistentFile.txt");

2. Input from the User:

Invalid user input, such as entering text when a number is expected, may
throw an exception like NumberFormatException .

Example:

int num = Integer.parseInt("abc"); // NumberFormatExcep

JAVA-UNIT 3 22
tion

3. Network Operations:

Failure to connect to a server or a timeout can throw exceptions like


SocketException or IOException .

Example:

Socket socket = new Socket("localhost", 8080); // may


throw SocketException

4. Database Operations:

Database errors like incorrect SQL syntax, connection issues, or invalid


queries can throw exceptions like SQLException .

Example:

Connection conn = DriverManager.getConnection("jdbc:mys


ql://localhost:3306/db", "user", "password");

18. Java Exception Handling Keywords


1. try :

Defines a block of code to monitor for exceptions.

Syntax:

try {
// Code that may throw an exception
}

2. catch :

Catches and handles exceptions thrown by the try block.

Syntax:

try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
}

3. finally :

A block of code that is always executed, regardless of whether an


exception was thrown or caught.

Syntax:

JAVA-UNIT 3 23
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
} finally {
// Cleanup code, always executed
}

4. throw :

Used to explicitly throw an exception.

Syntax:

throw new SomeException("Exception message");

5. throws :

Declares the types of exceptions that a method may throw.

Syntax:

public void method() throws SomeException {


// Code that might throw SomeException
}

19. Java Multi-Catch Block


Java 7 introduced the multi-catch block, which allows you to catch multiple
exceptions in a single catch block.

1. Syntax:

Instead of writing multiple catch blocks, you can use the | (OR) operator
to specify multiple exceptions in a single catch block.

Example:

try {
int[] arr = new int[5];
arr[10] = 30; // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException | ArithmeticExc
eption e) {
System.out.println("Exception occurred: " + e.getMe
ssage());
}

2. Advantages:

Reduces code duplication when multiple exceptions need similar handling.

JAVA-UNIT 3 24
Makes the code cleaner and easier to read.

20. Java Nested try Block


A nested try block refers to placing one try block inside another. This structure
allows handling different exceptions in separate blocks or performing more
specific exception handling for different parts of the code.

Why Use Nested try Blocks?


Complex Error Handling: When different code sections may throw different
types of exceptions, nested try blocks allow handling them individually.

Specific Handling: You can apply different exception handling strategies


depending on where the exception occurs in the nested blocks.

Example of Nested try Block:

public class NestedTryExample {


public static void main(String[] args) {
try {
System.out.println("Outer try block started.");

// Inner try block


try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch block: Divisi
on by zero error");
}

// More code that can throw an exception


int[] arr = new int[2];
arr[5] = 10; // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer catch block: Array inde
x error");
}

System.out.println("Program continues after exception


handling.");
}
}

Explanation:
1. Outer try block:

The outer block contains the code that might throw an


ArrayIndexOutOfBoundsException .

JAVA-UNIT 3 25
2. Inner try block:

The inner block contains code that might throw an ArithmeticException

(division by zero).

3. Handling Exceptions:

The inner block's catch handles the ArithmeticException .

The outer block's catch handles the ArrayIndexOutOfBoundsException .

Output:

Outer try block started.


Inner catch block: Division by zero error
Outer catch block: Array index error
Program continues after exception handling.

21. Java finally Block


The finally block in Java is used to execute important code, such as resource
cleanup, and it runs regardless of whether an exception was thrown or not. It's
commonly used for closing files, releasing resources, etc.

Characteristics of finally Block:


Always executes after the try block, whether or not an exception occurs.

Cannot be skipped, even if an exception is thrown in the try block or a catch

block.

Typically used for cleanup operations like closing database connections or


file streams.

Example of finally Block:

public class FinallyBlockExample {


public static void main(String[] args) {
try {
System.out.println("In the try block");
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e);
} finally {
System.out.println("Finally block executed, clean
up done.");
}
}
}

Explanation:

JAVA-UNIT 3 26
The finally block executes whether or not an exception is caught, ensuring
that necessary cleanup happens.

Even if the exception is caught in the catch block, the finally block will always
execute.

Output:

In the try block


Caught an exception: java.lang.ArithmeticException: / by zero
Finally block executed, cleanup done.

22. Java throw Keyword


The throw keyword is used to explicitly throw an exception. This is often used for
custom exception handling or to propagate exceptions from one method to
another.

Syntax:

throw new ExceptionType("Error message");

Example of throw :

public class ThrowExample {


public static void main(String[] args) {
try {
checkAge(15);
} catch (IllegalArgumentException e) {
System.out.println("Caught exception: " + e);
}
}

static void checkAge(int age) {


if (age < 18) {
throw new IllegalArgumentException("Age must be 1
8 or older");
}
System.out.println("Age is valid");
}
}

Explanation:
The checkAge method checks if the provided age is less than 18. If so, it throws
an IllegalArgumentException using the throw keyword.

The exception is caught in the main method’s catch block.

JAVA-UNIT 3 27
Output:

Caught exception: java.lang.IllegalArgumentException: Age mus


t be 18 or older

23. Java throws Keyword


The throws keyword is used in a method signature to declare that a method may
throw one or more exceptions. It informs the calling method that it should handle
these exceptions.

Syntax:

public void methodName() throws ExceptionType1, ExceptionType


2 {
// Code that may throw exceptions
}

Example of throws :

public class ThrowsExample {


public static void main(String[] args) {
try {
method();
} catch (Exception e) {
System.out.println("Exception caught: " + e);
}
}

static void method() throws Exception {


throw new Exception("Something went wrong");
}
}

Explanation:
The method() throws a generic Exception , and the throws keyword declares this
in the method signature.

The main() method handles the exception using a try-catch block.

Output:

Exception caught: java.lang.Exception: Something went wrong

JAVA-UNIT 3 28

You might also like