JAVA-UNIT_3
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.
Applet Lifecycle:
init(): Called when the applet is initialized.
import java.applet.Applet;
import java.awt.Graphics;
Explanation:
1. The import java.applet.Applet statement includes the Applet class.
2. paint(Graphics g) :
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
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.
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).
3. paint(Graphics g) :
4. stop() :
Called when the applet is no longer active (e.g., when the browser
navigates away or the tab is minimized).
5. destroy() :
JAVA-UNIT 3 2
Called once before the applet is destroyed.
Lifecycle Diagram:
import java.applet.Applet;
import java.awt.Graphics;
Explanation:
1. init() : Prints "Applet Initialized" when the applet is loaded.
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
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.
Benefits of Multithreading:
1. Improved Performance: Tasks like file I/O, network calls, or computations can
run simultaneously.
JAVA-UNIT 3 4
() + ": " + i);
try {
Thread.sleep(500); // Pauses thread for 500ms
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
Explanation:
1. Extending Thread Class:
2. Creating Threads:
3. Starting Threads:
The start() method is called to begin thread execution, invoking the run()
method.
4. Thread Sleep:
Output Example:
The output may interleave depending on thread scheduling:
Thread-0: 1
Thread-1: 1
Thread-0: 2
Thread-1: 2
...
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.
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.
JAVA-UNIT 3 6
public static void main(String[] args) {
Counter thread1 = new Counter(1);
Counter thread2 = new Counter(10);
Explanation:
1. Two Threads, Different Workloads:
2. Concurrent Execution:
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:
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.
2. Thread-Based Multitasking:
Example:
Key Characteristics:
Lightweight tasks.
JAVA-UNIT 3 8
}
Explanation:
1. Two Threads:
2. Thread.sleep():
3. Concurrency:
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:
Each process operates independently and has its own memory space.
Example:
JAVA-UNIT 3 9
Key Characteristics:
Heavyweight tasks.
2. Thread-Based Multitasking:
Example:
Key Characteristics:
Lightweight tasks.
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"));
Explanation:
1. Two Threads:
2. Thread.sleep():
3. Concurrency:
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.
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:
3. Concurrency:
JAVA-UNIT 3 11
Allows multiple threads to execute simultaneously on multi-core
processors.
Explanation:
1. Extending Thread :
The MyThread class extends the Thread class, and its run() method defines
the task for the thread.
2. Thread Creation:
3. Thread Execution:
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
...
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);
}
}
}
t1.start(); // Start t1
t2.start(); // Start t2
}
}
Explanation:
1. Thread Creation:
2. Thread Execution:
3. Thread.sleep():
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.
State: NEW .
Example:
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:
Example:
Thread.sleep(1000);
5. Terminated:
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.
t1.start();
t2.start();
}
}
Example:
t1.start();
t2.start();
JAVA-UNIT 3 16
}
}
Key Methods:
1. start():
Example: t1.start();
2. run():
3. sleep(long millis):
Example:
try {
Thread.sleep(1000); // Pauses for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
4. join():
Example: t1.join();
5. isAlive():
Example:
if (t1.isAlive()) {
System.out.println("Thread is running");
}
6. yield():
Overview:
JAVA-UNIT 3 17
The Runnable interface is a functional interface used to define the task for a
thread.
Example:
2. Call the start() Method: Once a thread object is created, call the start()
3. Thread Scheduling: The thread scheduler decides when each thread will run.
JAVA-UNIT 3 18
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
Explanation:
start()triggers the run() method, allowing the thread to execute its task. It
ensures the thread runs concurrently with the main thread.
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.
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.
4. Graceful Termination: Ensures that resources are cleaned up, and errors are
properly handled without leaving the system in an inconsistent state.
1. Throwable:
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:
Throwable
├── Error
└── Exception
├── IOException (Checked)
├── SQLException (Checked)
└── RuntimeException (Unchecked)
├── NullPointerException
└── ArithmeticException
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:
Example:
import java.io.*;
2. Unchecked Exceptions:
JAVA-UNIT 3 21
These exceptions are not checked at compile-time. They occur at runtime.
Examples:
Example:
3. Errors:
Errors are usually not recoverable and represent serious problems like
hardware failures.
Examples:
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:
Invalid user input, such as entering text when a number is expected, may
throw an exception like NumberFormatException .
Example:
JAVA-UNIT 3 22
tion
3. Network Operations:
Example:
4. Database Operations:
Example:
Syntax:
try {
// Code that may throw an exception
}
2. catch :
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
}
3. finally :
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 :
Syntax:
5. throws :
Syntax:
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:
JAVA-UNIT 3 24
Makes the code cleaner and easier to read.
Explanation:
1. Outer try block:
JAVA-UNIT 3 25
2. Inner try block:
(division by zero).
3. Handling Exceptions:
Output:
block.
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:
Syntax:
Example of throw :
Explanation:
The checkAge method checks if the provided age is less than 18. If so, it throws
an IllegalArgumentException using the throw keyword.
JAVA-UNIT 3 27
Output:
Syntax:
Example of throws :
Explanation:
The method() throws a generic Exception , and the throws keyword declares this
in the method signature.
Output:
JAVA-UNIT 3 28