Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
JAVA PROGRAMMING
Unit – Multithreaded Programming & Applets
Java Thread Model | Main Thread | Creating Threads
isAlive() & join() | Thread Priorities | Synchronization
Inter-Thread Communication | Suspend / Resume / Stop
File I/O | Console I/O | Applet Fundamentals
AWT Package | AWT Event Handling
End-Semester Exam Preparation | High-Quality Conceptual Notes
Complete Coverage • Diagrams • Code Examples • Exam Questions
High-Quality Exam-Oriented Notes Page 1
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
TABLE OF CONTENTS
# Topic Coverage
1 Introduction to Multithreading Definition, Process vs Thread, Advantages
2 Java Thread Model Thread class, Runnable, Life Cycle (diagram)
3 Main Thread Default thread, controlling main thread
4 Creating Threads Extending Thread, Implementing Runnable (code)
5 isAlive() & join() Methods explained with code
6 Thread Priorities Constants, setPriority, getPriority
7 Synchronization synchronized keyword, deadlock
8 Inter-Thread Communication wait(), notify(), notifyAll()
9 Suspend, Resume & Stop Deprecated methods + safe alternatives
10 Console I/O Reading/Writing control input-output
11 File I/O FileReader, FileWriter, BufferedReader, code
12 Applet Fundamentals Life cycle, init/start/stop/destroy, HTML
13 AWT Package Components, Containers, Layout Managers
14 AWT Event Handling Event model, listeners, adapters
15 Quick Revision Summary All key points at a glance
High-Quality Exam-Oriented Notes Page 2
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
1. INTRODUCTION TO MULTITHREADING
1.1 What is Multithreading?
Formal Definition: Multithreading is a programming concept in which a single program is divided into
two or more concurrently running sub-tasks, called threads. Each thread represents an independent path
of execution that shares the same memory space (heap) of the parent process but has its own program
counter, stack, and local variables. Java provides built-in language-level support for multithreading
through the [Link] class and the [Link] interface.
Conceptual Definition: Think of a restaurant. One chef cooks food, another manages orders, and a
third handles billing — all at the same time, sharing the kitchen. In Java, these "chefs" are threads
sharing the program's memory.
Key Idea / Purpose: Multithreading exists to maximize CPU utilization, improve application
responsiveness (GUI stays active while background work runs), and allow parallel execution of
independent tasks (e.g., downloading a file while displaying progress).
1.2 Process vs Thread
Understanding the difference between a Process and a Thread is critical — examiners love this
comparison.
Aspect Process Thread (Light-weight Process)
Definition Independent program in execution Sub-unit of a process
Memory Separate memory space Shares heap with parent process
Communication Inter-process comm (complex, slow) Direct shared memory (fast)
Creation Cost Heavy (OS-level) Lightweight (JVM-level)
Context Switch Expensive Cheaper
Crash Impact Crashes independently One thread crash can affect others
Example MS Word, Chrome (separate) Spell check + typing in MS Word
1.3 Advantages of Multithreading
• Better CPU Utilization: While one thread waits for I/O, another thread executes on the CPU.
• Improved Responsiveness: GUI applications do not freeze; background tasks run separately.
• Resource Sharing: Threads share the same process memory — no need for complex IPC
mechanisms.
• Economy: Creating and switching threads is cheaper than creating new processes.
• Scalability: Multi-core CPUs can run threads truly in parallel, speeding up computation.
■ MEMORY TRICK: CURE-S = CPU utilization, Unblocked UI, Resource sharing, Economy, Scalability — 5
advantages of multithreading.
High-Quality Exam-Oriented Notes Page 3
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
2. JAVA THREAD MODEL & THREAD LIFE CYCLE
2.1 Java Thread Model
The Java thread model defines how threads are created, managed, and communicate within the JVM.
Java implements threads using the [Link] class. The JVM maps Java threads to OS-level
native threads. Every Java program has at least one thread — the main thread — started automatically
by the JVM when the program begins.
2.2 Thread Life Cycle (State Diagram)
A thread passes through multiple states during its lifetime. Understanding these states with transitions is a
very common exam question.
State Description How Entered / Exited
new Thread() → NEW
NEW Thread object created but start() not yet called.
start() → RUNNABLE
start() enters this state
RUNNABLE Thread is ready to run or is running on CPU.
Scheduler picks it for CPU
Scheduler assigns CPU
RUNNING Thread currently executing on CPU.
yield() / time-slice ends → RUNNABLE
sleep(), wait(), join(),
BLOCKED /
Thread paused waiting for resource or signal. or I/O → BLOCKED
WAITING
Notified / timer expires → RUNNABLE
sleep(ms), wait(ms),
TIMED_WAITING Thread waiting for a specified time period.
join(ms) → TIMED_WAITING
run() completes → TERMINATED
TERMINATED Thread finished execution (run() returned or exception).
Cannot be restarted
Diagram – Thread State Transitions (ASCII):
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ JAVA THREAD LIFE CYCLE ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
new Thread() start() CPU Assigned
■■■■■■■■■■■ [NEW] ■■■■■■■■ [RUNNABLE] ■■■■■■■■ [RUNNING]
▲ ■
■ sleep()/wait() ■
notify() ■ join()/I-O wait ▼
[BLOCKED / WAITING / TIMED_WAITING]
run() returns / exception
[RUNNING] ■■■■■■■■■■■■■■■■■■■■■■■■■■ [TERMINATED]
■ EXAM NOTE: A TERMINATED thread CANNOT be restarted by calling start() again. Calling start() on a
dead thread throws IllegalThreadStateException.
■ EXAM Q: Draw and explain the complete life cycle of a Java thread with all states and transitions.
High-Quality Exam-Oriented Notes Page 4
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
3. MAIN THREAD
When a Java program starts, the JVM automatically creates one thread to execute the main() method.
This is called the main thread. It is the first thread to run and the last to finish. Child threads are
spawned from the main thread. You can get a reference to it using [Link]().
3.1 Controlling the Main Thread
• [Link](): Returns reference to the currently executing thread object.
• getName(): Returns the name of the thread (default: "main").
• setName(String): Sets a custom name for the thread.
• sleep(long ms): Pauses the current thread for specified milliseconds.
• getPriority(): Returns the thread's priority (1–10).
3.2 Code – Main Thread Demo
// [Link]
class MainThreadDemo {
public static void main(String[] args) {
// Get reference to current (main) thread
Thread t = [Link]();
[Link]("Current thread: " + t);
// Prints: Thread[main,5,main] -> name, priority, group
[Link]("MyMainThread"); // Rename the thread
[Link]("After rename: " + [Link]());
try {
for (int i = 3; i > 0; i--) {
[Link]("Count: " + i);
[Link](1000); // Pause 1 second; throws InterruptedException
}
} catch (InterruptedException e) {
[Link]("Main thread interrupted");
}
[Link]("Main thread ending");
}
}
Expected Output:
Current thread: Thread[main,5,main]
After rename: MyMainThread
Count: 3 Count: 2 Count: 1 (one per second)
Main thread ending
■ EXAM Q: What is the main thread in Java? How do you get a reference to it and change its name?
High-Quality Exam-Oriented Notes Page 5
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
4. CREATING THREADS – TWO WAYS
Java provides two standard approaches to create a new thread:
1. Extending the Thread class – Override the run() method.
2. Implementing the Runnable interface – Provide run() via an interface; pass object to Thread
constructor.
Runnable is generally preferred because Java does not support multiple inheritance; using Runnable
allows the class to extend another class.
4.1 Method 1 – Extending Thread Class
// Method 1: Extend Thread class
class MyThread extends Thread {
String name;
MyThread(String name) {
[Link] = name;
}
// Override run() – code that executes in this thread
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](name + " - Count: " + i);
try { [Link](400); }
catch (InterruptedException e) { [Link]("Interrupted"); }
}
}
}
class ThreadDemo1 {
public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-A");
MyThread t2 = new MyThread("Thread-B");
[Link](); // Starts t1; calls run() internally
[Link](); // Starts t2 concurrently
}
}
Sample Output (order may vary – threads are concurrent):
Thread-A - Count: 1
Thread-B - Count: 1
Thread-A - Count: 2
Thread-B - Count: 2
Thread-A - Count: 3
Thread-B - Count: 3
4.2 Method 2 – Implementing Runnable Interface
// Method 2: Implement Runnable interface
class MyRunnable implements Runnable {
String name;
High-Quality Exam-Oriented Notes Page 6
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
MyRunnable(String name) { [Link] = name; }
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](name + " -> " + i);
try { [Link](300); }
catch (InterruptedException e) {}
}
}
}
class ThreadDemo2 {
public static void main(String[] args) {
MyRunnable r1 = new MyRunnable("Runnable-X");
MyRunnable r2 = new MyRunnable("Runnable-Y");
Thread t1 = new Thread(r1); // Pass Runnable to Thread constructor
Thread t2 = new Thread(r2);
[Link]();
[Link]();
}
}
Feature Extending Thread Implementing Runnable
Inheritance Cannot extend another class Can extend another class ✓
Code Reuse Less flexible More flexible (preferred) ✓
Object sharing Not easy Same Runnable → multiple threads ✓
Lambda support No Yes (functional interface) ✓
Separation of concern Thread logic mixed Task logic separated ✓
■ MEMORY TRICK: R-E-L-S-S → Runnable wins in: Reuse, Extensibility, Lambda, Sharing, Separation.
■ COMMON MISTAKE: Calling run() directly does NOT create a new thread — it executes run() in the
CURRENT thread like a normal method call. Always call start() to create a new thread!
■ EXAM Q: What are the two ways to create a thread in Java? Which is preferred and why? Write code
for both.
High-Quality Exam-Oriented Notes Page 7
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
5. isAlive() AND join() METHODS
5.1 isAlive()
isAlive() is a method of the Thread class that returns true if the thread on which it is called has been
started and has not yet died (i.e., its run() method has not finished). Returns false if the thread has not
been started yet or has completed execution.
• Syntax: boolean isAlive()
• Useful to check thread status before proceeding with dependent logic.
5.2 join()
join() causes the calling thread to wait until the thread on which join() is called completes its execution.
For example, if main thread calls [Link](), the main thread will pause and wait until t1 finishes, then
continue. You can also call join(long millis) to wait for at most the specified number of milliseconds.
• Syntax: void join() throws InterruptedException
• join(long ms): Waits at most ms milliseconds for the thread to die.
• Without join(), the main thread may finish before child threads — causing abrupt JVM shutdown.
5.3 Code – isAlive() and join() Demo
class AliveJoinDemo extends Thread {
public void run() {
try {
[Link](getName() + " started");
[Link](1000);
[Link](getName() + " finished");
} catch (InterruptedException e) {}
}
}
class TestAliveJoin {
public static void main(String[] args) throws InterruptedException {
AliveJoinDemo t1 = new AliveJoinDemo();
AliveJoinDemo t2 = new AliveJoinDemo();
[Link]();
[Link]();
// Check if threads are alive right after start
[Link]("t1 alive after start: " + [Link]()); // true
[Link]("t2 alive after start: " + [Link]()); // true
[Link](); // Main waits for t1 to finish
[Link](); // Main waits for t2 to finish
// Now both threads have completed
[Link]("t1 alive after join: " + [Link]()); // false
[Link]("t2 alive after join: " + [Link]()); // false
High-Quality Exam-Oriented Notes Page 8
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
[Link]("Main thread ends");
}
}
Expected Output:
t1 alive after start: true
t2 alive after start: true
Thread-0 started
Thread-1 started
Thread-0 finished
Thread-1 finished
t1 alive after join: false
t2 alive after join: false
Main thread ends
■ EXAM Q: Explain isAlive() and join() with a working Java program.
High-Quality Exam-Oriented Notes Page 9
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
6. THREAD PRIORITIES
Every Java thread has a priority — an integer value between 1 (lowest) and 10 (highest) that gives a
hint to the thread scheduler about the relative importance of threads. Higher-priority threads are
generally executed before lower-priority ones, but this is not guaranteed — it depends on the OS
scheduler. Java defines three priority constants in the Thread class.
Constant Value Meaning
Thread.MIN_PRIORITY 1 Lowest priority — runs only when no higher-priority thread needs CPU
Thread.NORM_PRIORITY 5 Default priority assigned to every new thread
Thread.MAX_PRIORITY 10 Highest priority — gets CPU time first (not guaranteed)
6.1 Priority Methods
• setPriority(int p): Sets the thread priority (1–10). Throws IllegalArgumentException if out of range.
• getPriority(): Returns the thread's current priority.
• Child thread inherits parent's priority at creation time.
class PriorityDemo extends Thread {
public void run() {
[Link](getName() + " priority: " + getPriority());
}
}
class TestPriority {
public static void main(String[] args) {
PriorityDemo t1 = new PriorityDemo();
PriorityDemo t2 = new PriorityDemo();
PriorityDemo t3 = new PriorityDemo();
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.NORM_PRIORITY); // 5
[Link](Thread.MAX_PRIORITY); // 10
[Link](); [Link](); [Link]();
}
}
Output (likely order): t3 (10), t2 (5), t1 (1) — but OS may vary.
■ Priority is only a HINT — the JVM does not guarantee strict priority-based scheduling. Priority starvation
(low-priority thread never runs) is possible.
■ EXAM Q: What are thread priorities in Java? Explain MIN, NORM, MAX priority with code.
High-Quality Exam-Oriented Notes Page 10
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
7. SYNCHRONIZATION
Synchronization is the mechanism in Java that controls access to shared resources by multiple threads
simultaneously. Without synchronization, two or more threads can read/write shared data concurrently,
producing inconsistent, unpredictable results — called a race condition. Java provides the
synchronized keyword to lock access to a block or method so only one thread can execute it at a time.
7.1 The Problem – Race Condition
Imagine two threads both incrementing a counter: Thread-1 reads count=5, Thread-2 reads count=5, both
write count=6. Expected: 7. Actual: 6. This is a race condition.
7.2 synchronized Keyword – Two Forms
• Synchronized Method: Entire method is locked. Only one thread can execute it at a time on the
same object.
• Synchronized Block: Only a specific section of code is locked — more efficient than locking the
entire method.
// Synchronized Method Example
class Counter {
int count = 0;
// synchronized keyword locks this method on 'this' object
synchronized void increment() {
count++;
}
}
class SyncDemo implements Runnable {
Counter c;
SyncDemo(Counter c) { this.c = c; }
public void run() {
for (int i = 0; i < 1000; i++) {
[Link](); // Thread-safe increment
}
}
}
class TestSync {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(new SyncDemo(counter));
Thread t2 = new Thread(new SyncDemo(counter));
[Link](); [Link]();
[Link](); [Link]();
[Link]("Final count: " + [Link]);
// Without sync: count < 2000 (random) With sync: always 2000
}
}
Output with synchronization: Final count: 2000 (always correct)
High-Quality Exam-Oriented Notes Page 11
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
7.3 How Synchronization Works – Monitor / Lock
Every Java object has an intrinsic monitor lock (also called a mutex). When a thread enters a
synchronized method/block, it acquires the lock. Other threads trying to enter the same synchronized
section on the same object are blocked until the lock is released (when the thread exits the synchronized
block).
Object Monitor Lock
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ Thread-1 holds lock → executing ■
■ Thread-2 → BLOCKED (waiting) ■
■ Thread-3 → BLOCKED (waiting) ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
When Thread-1 exits synchronized block:
Lock released → Thread-2 or Thread-3 acquires it
7.4 Deadlock
Deadlock occurs when two or more threads are waiting for each other to release locks, and none can
proceed. Thread-1 holds Lock-A and waits for Lock-B; Thread-2 holds Lock-B and waits for Lock-A →
circular wait → both blocked forever.
■ EXAM TRAP: "Deadlock" is very commonly asked. Know the 4 Coffman conditions: Mutual Exclusion,
Hold & Wait, No Preemption, Circular Wait. Prevention: always acquire locks in the same order.
■ EXAM Q: What is synchronization in Java? Explain with a code example. Also explain deadlock.
High-Quality Exam-Oriented Notes Page 12
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
8. INTER-THREAD COMMUNICATION
Inter-thread communication (also called Cooperation) allows synchronized threads to communicate with
each other. Java provides three methods defined in the Object class (not Thread!) for this purpose:
wait(), notify(), and notifyAll(). These methods must be called from within a synchronized context
(synchronized method or block).
Method Description Who Calls?
wait() Releases the lock and puts the calling thread into waiting state until
Thread
notified.
that is waiting for a condition
notify() Wakes up ONE thread that is waiting on the same object's monitor.
Thread that has fulfilled the condition
notifyAll() Wakes up ALL threads waiting on the same object's monitor. When multiple waiters should be notified
wait(long ms) Waits for specified milliseconds or until notified, whichever comes
Thread
first. with timeout
8.1 Classic Producer-Consumer Example
// Producer-Consumer using wait() and notify()
class SharedBox {
int value;
boolean hasValue = false;
synchronized void produce(int v) throws InterruptedException {
while (hasValue) wait(); // Wait if box is full
value = v;
hasValue = true;
[Link]("Produced: " + v);
notify(); // Notify consumer
}
synchronized void consume() throws InterruptedException {
while (!hasValue) wait(); // Wait if box is empty
[Link]("Consumed: " + value);
hasValue = false;
notify(); // Notify producer
}
}
class TestITC {
public static void main(String[] args) {
SharedBox box = new SharedBox();
new Thread(() -> {
for (int i = 1; i <= 3; i++)
try { [Link](i); } catch (Exception e) {}
}).start();
new Thread(() -> {
for (int i = 1; i <= 3; i++)
try { [Link](); } catch (Exception e) {}
}).start();
}
}
High-Quality Exam-Oriented Notes Page 13
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
Output:
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
■ IMPORTANT: wait(), notify(), notifyAll() MUST be called inside a synchronized block/method; otherwise
IllegalMonitorStateException is thrown. These are methods of Object class, NOT Thread class!
■ EXAM Q: Explain wait(), notify(), and notifyAll() with Producer-Consumer example.
High-Quality Exam-Oriented Notes Page 14
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
9. SUSPENDING, RESUMING, AND STOPPING THREADS
Earlier versions of Java provided suspend(), resume(), and stop() methods in the Thread class to
control thread execution. However, these methods are deprecated in modern Java because they are
inherently unsafe — stop() can leave shared objects in inconsistent states, and suspend() can cause
deadlocks. The correct approach is to use a boolean flag variable to control thread execution.
Deprecated Method Problem Safe Alternative
stop() Leaves objects in inconsistent state (abrupt termination)
Use boolean flag; set flag=false to stop
suspend() Can cause deadlock if thread holds a lock while suspended
Use wait() to pause; notify() to resume
resume() Only meaningful with deprecated suspend() Use notify() with wait()
9.1 Safe Thread Control Using Boolean Flag
class SafeThread extends Thread {
private volatile boolean suspended = false; // volatile: always read from main memo
ry
private volatile boolean stopped = false;
public void run() {
while (!stopped) { // Check stop flag
synchronized (this) {
while (suspended) { // Check suspend flag
try { wait(); } catch (InterruptedException e) {}
}
}
[Link](getName() + " running...");
try { [Link](500); } catch (InterruptedException e) {}
}
[Link](getName() + " stopped.");
}
public synchronized void mySuspend() {
suspended = true;
[Link](getName() + " suspended.");
}
public synchronized void myResume() {
suspended = false;
notify(); // Wake up the waiting thread
[Link](getName() + " resumed.");
}
public void myStop() { stopped = true; }
}
class TestSafe {
public static void main(String[] args) throws InterruptedException {
SafeThread t = new SafeThread();
[Link]();
[Link](1500); [Link]();
[Link](1000); [Link]();
High-Quality Exam-Oriented Notes Page 15
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
[Link](1500); [Link]();
}
}
Key concept: volatile keyword ensures that changes to the flag variable are immediately visible to all
threads (prevents CPU caching issues).
■ EXAM Q: Why are suspend(), resume(), and stop() deprecated? Write safe alternatives using flags.
High-Quality Exam-Oriented Notes Page 16
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
10. READING CONTROL INPUT & WRITING CONTROL OUTPUT
Java provides several ways to read input from the keyboard (console/standard input) and write output to
the console (standard output). The primary classes are: [Link] (InputStream for reading),
[Link] (PrintStream for writing), BufferedReader with InputStreamReader for efficient character
input, and Scanner class ([Link]) for easy typed input parsing.
10.1 Reading Console Input
import [Link].*;
import [Link];
class ConsoleIODemo {
public static void main(String[] args) throws IOException {
// ----- Method 1: BufferedReader (classic Java I/O) -----
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link](); // Reads a full line as String
[Link]("Hello, " + name);
// ----- Method 2: Scanner (modern, easier) -----
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link](); // Reads integer
[Link]("Age: " + age);
// Reading a single character
[Link]("Enter a character: ");
char ch = (char) [Link](); // Reads one byte as char
[Link]("Character: " + ch);
[Link]();
}
}
Scanner methods: nextInt(), nextDouble(), nextLine(), next(), nextBoolean() — used for different data
types. Always close Scanner after use.
10.2 Writing Console Output
class OutputDemo {
public static void main(String[] args) {
// print: no newline at end
[Link]("Hello ");
[Link]("World");
// println: adds newline at end
[Link]();
[Link]("New line here");
// printf: formatted output (like C-style)
[Link]("Name: %-10s Age: %3d%n", "Alice", 25);
High-Quality Exam-Oriented Notes Page 17
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
// %-10s = left-aligned string in 10 chars; %3d = int in 3 chars
// format: same as printf but returns formatted string
String s = [Link]("Pi = %.2f", [Link]);
[Link](s);
}
}
■ EXAM Q: Explain different methods for reading console input in Java with examples.
High-Quality Exam-Oriented Notes Page 18
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
11. READING AND WRITING FILES
Java's [Link] package provides classes for file input/output operations. File I/O is classified into two
categories: Byte streams (FileInputStream, FileOutputStream) for raw binary data, and Character
streams (FileReader, FileWriter) for text data. For efficiency, character streams are wrapped in
BufferedReader and BufferedWriter.
Class Type Use
FileReader Character Read text characters from a file
FileWriter Character Write text characters to a file
BufferedReader Character Efficient reading with readLine() support
BufferedWriter Character Efficient writing with newLine() support
FileInputStream Byte Read raw bytes from a file
FileOutputStream Byte Write raw bytes to a file
PrintWriter Character Formatted text output to file (println, printf)
11.1 Writing to a File
import [Link].*;
class WriteFileDemo {
public static void main(String[] args) {
// try-with-resources: auto-closes stream even on exception
try (FileWriter fw = new FileWriter("[Link]");
BufferedWriter bw = new BufferedWriter(fw)) {
[Link]("Line 1: Hello, File!");
[Link](); // OS-appropriate newline
[Link]("Line 2: Java File I/O");
[Link]();
[Link]("Line 3: Done.");
[Link]("File written successfully.");
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
11.2 Reading from a File
import [Link].*;
class ReadFileDemo {
public static void main(String[] args) {
try (FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr)) {
String line;
High-Quality Exam-Oriented Notes Page 19
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
[Link]("--- File Contents ---");
// readLine() returns null when end-of-file is reached
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (FileNotFoundException e) {
[Link]("File not found!");
} catch (IOException e) {
[Link]("I/O Error: " + [Link]());
}
}
}
Output:
--- File Contents ---
Line 1: Hello, File!
Line 2: Java File I/O
Line 3: Done.
■ TIP: Always use try-with-resources (try(resource) {...}) to ensure streams are closed automatically. This
prevents resource leaks and is best practice since Java 7.
■ FileWriter(filename, true) → appends to file. FileWriter(filename) or FileWriter(filename, false) → overwrites
file. This is a common exam trap!
■ EXAM Q: Write a Java program to read from and write to a file using BufferedReader and
BufferedWriter.
High-Quality Exam-Oriented Notes Page 20
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
12. APPLET FUNDAMENTALS
An Applet is a special type of Java program that can be embedded in a web page and runs inside a web
browser's Java plug-in or the appletviewer tool. Unlike standalone applications, applets do not have a
main() method — they are managed by the browser's applet container, which controls their lifecycle
through specific callback methods: init(), start(), stop(), destroy(), and paint(). Applets extend the
[Link] class (AWT-based) or [Link] (Swing-based).
12.1 Applet Life Cycle
The applet life cycle is one of the most important and frequently examined topics in this unit.
Method Called When Purpose
init() Applet is first loaded into browser Initialization (like constructor) — called ONCE
start() After init() and every time page is revisited Start execution; resume activity
stop() When user leaves the page or minimizes browser
Pause execution; conserve resources
destroy() When browser closes or applet is removedRelease resources; called ONCE
paint(Graphics g) When applet needs to draw itself Rendering content on applet canvas
repaint() Called by programmer to request redraw Triggers paint() to be called again
update(Graphics g) Called by repaint() Clears background then calls paint()
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ APPLET LIFE CYCLE ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
Browser loads applet
■
▼
[init()] ■■■■ called ONCE when applet is first loaded
■
▼
[start()] ■■■■ called after init(); also called when page revisited
■
▼
[paint()] ■■■■ called to display applet on screen
■
(User leaves page)
■
▼
[stop()] ■■■■ called when page is left (NOT destroyed)
■
(User returns to page)
■
▼
[start()] ■■■■ called again (NO init() this time)
■
(Browser closes)
■
▼
High-Quality Exam-Oriented Notes Page 21
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
[destroy()] ■■■■ called ONCE when applet is fully removed
12.2 Applet Code Example
import [Link].*;
import [Link].*;
/*
* <applet code="[Link]" width="300" height="150">
* </applet>
* Save this HTML comment in a .html file and open with appletviewer
*/
public class HelloApplet extends Applet {
String message;
// Called ONCE when applet is loaded
public void init() {
message = "Hello from Java Applet!";
setBackground([Link]);
}
// Called to render the applet on screen
public void paint(Graphics g) {
[Link]([Link]);
[Link](new Font("Arial", [Link], 18));
[Link](message, 50, 75); // x=50, y=75
[Link](10, 10, 280, 130); // Draw border
}
}
To run:
1. Compile: javac [Link]
2. Run: appletviewer [Link] (if HTML comment is in .java file)
12.3 Passing Parameters to Applets
// HTML: <param name="greeting" value="Welcome!">
public class ParamApplet extends Applet {
public void init() {
String msg = getParameter("greeting"); // Read HTML param
if (msg == null) msg = "Default Message";
// use msg...
}
}
■ EXAM Q: Explain the applet life cycle with a diagram. What are init(), start(), stop(), destroy()?
High-Quality Exam-Oriented Notes Page 22
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
13. AWT PACKAGE
AWT (Abstract Window Toolkit) is Java's original GUI toolkit, part of the [Link] package. It provides
components for building graphical user interfaces. AWT components are heavyweight — they use the
underlying OS's native GUI widgets. This makes them platform-dependent in look-and-feel. AWT was
later supplemented by Swing (lightweight, pure Java) and JavaFX.
13.1 AWT Component Hierarchy
[Link]
■■■ [Link] (base class for all AWT components)
■■■ [Link] (can contain other components)
■ ■■■ [Link] (basic container, used in applets)
■ ■■■ [Link]
■ ■ ■■■ [Link] (top-level window with title)
■ ■ ■■■ [Link] (secondary window)
■ ■■■ [Link] (embedded in browser)
■■■ [Link]
■■■ [Link]
■■■ [Link] (single-line input)
■■■ [Link] (multi-line input)
■■■ [Link]
■■■ [Link] (drop-down list)
■■■ [Link] (scrollable list)
■■■ [Link] (drawing area)
13.2 Common AWT Components
Component Description Key Methods
Button Clickable button setLabel(), getLabel()
Label Non-editable text display setText(), getText()
TextField Single-line text input getText(), setText(), setColumns()
TextArea Multi-line scrollable text input getText(), append(), setRows()
Checkbox Toggle button (on/off) getState(), setState()
Choice Drop-down list (select one item) add(), getSelectedItem()
List Scrollable list (select one or more items) add(), getSelectedItem()
Scrollbar Horizontal or vertical scrollbar getValue(), setValue()
Canvas Blank drawing area paint(Graphics g)
13.3 Layout Managers
Layout managers control how components are positioned and sized within a container. Java provides
several built-in layout managers:
Layout Manager Description Usage
FlowLayout Arranges components left-to-right, wraps at end (Default for
setLayout(new
Panel/Applet)
FlowLayout())
High-Quality Exam-Oriented Notes Page 23
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
Layout Manager Description Usage
BorderLayout Divides container into 5 regions: N, S, E, W, CENTER (Default
add(comp,
for Frame)
[Link])
GridLayout Arranges components in equal-sized grid cells new GridLayout(rows, cols)
CardLayout Shows one component at a time like a deck of cards first(), next(), last()
GridBagLayout Most flexible: precise control over position and size GridBagConstraints
null Layout Absolute positioning (no manager) setBounds(x, y, w, h)
■ EXAM Q: Explain AWT component hierarchy. What are layout managers? Compare FlowLayout,
BorderLayout, GridLayout.
High-Quality Exam-Oriented Notes Page 24
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
14. AWT EVENT HANDLING
Event handling in Java follows the Delegation Event Model (introduced in JDK 1.1). In this model, an
event source (e.g., Button) generates an event object when an action occurs (e.g., click). This event is
delegated to a registered Event Listener object which has an appropriate handler method. This cleanly
separates the source of events from the code that processes them.
14.1 Key Concepts
• Event Source: The component that generates an event (e.g., Button, TextField, Checkbox).
• Event Object: An object that encapsulates information about the event (e.g., ActionEvent,
MouseEvent, KeyEvent).
• Event Listener: An interface with methods to handle events (e.g., ActionListener, MouseListener,
KeyListener).
• Registration: Source registers a listener using addXxxListener() method.
• Adapter Classes: Abstract classes that implement listener interfaces with empty methods — useful
when you only need to override a few methods.
14.2 Common Events and Listeners
Event Class Listener Interface Key Methods Generated By
ActionEvent ActionListener actionPerformed(ActionEvent e) Button, MenuItem, TextField (Enter)
mouseClicked(), mousePressed(),
MouseEvent MouseListener Mouse clicks/movement
mouseReleased(), mouseEntered(), mouseExited()
MouseMotionEvent MouseMotionListener mouseDragged(), mouseMoved() Mouse movement
KeyEvent KeyListener keyPressed(), keyReleased(), keyTyped()
Keyboard input
ItemEvent ItemListener itemStateChanged(ItemEvent e) Checkbox, Choice, List
WindowEvent WindowListener windowClosing(), windowOpened() Frame/window operations
FocusEvent FocusListener focusGained(), focusLost() Component focus change
TextEvent TextListener textValueChanged(TextEvent e) TextField, TextArea
14.3 Complete AWT Event Handling Example
import [Link].*;
import [Link].*;
// Frame with button click counter
class EventDemo extends Frame implements ActionListener {
Button btn;
Label lbl;
int count = 0;
EventDemo() {
// Setup window
setTitle("AWT Event Demo");
setSize(300, 200);
High-Quality Exam-Oriented Notes Page 25
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
setLayout(new FlowLayout());
lbl = new Label("Clicks: 0");
btn = new Button("Click Me!");
// Register THIS object as the ActionListener for btn
[Link](this);
add(lbl);
add(btn);
setVisible(true);
// Handle window close button
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}
// This method is called automatically when button is clicked
@Override
public void actionPerformed(ActionEvent e) {
count++;
[Link]("Clicks: " + count);
}
public static void main(String[] args) {
new EventDemo();
}
}
What happens: Window opens with a button. Each click increments the counter and updates the label.
WindowAdapter (adapter class) handles the close button.
14.4 Adapter Classes
Adapter classes are abstract classes that implement listener interfaces with all methods having empty
bodies. Instead of implementing all 7 methods of WindowListener, you can extend WindowAdapter and
override only the methods you need. Key adapter classes: WindowAdapter, MouseAdapter,
KeyAdapter, MouseMotionAdapter, FocusAdapter.
// Without adapter: must implement ALL 7 WindowListener methods (even if empty)
class MyListener implements WindowListener {
public void windowClosing(WindowEvent e) { [Link](0); }
public void windowOpened(WindowEvent e) {} // Empty - must still define!
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
}
// With adapter: only override what you need (MUCH cleaner!)
High-Quality Exam-Oriented Notes Page 26
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
class MyAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) { [Link](0); }
// That's it! All other methods default to empty.
}
■ EXAM Q: Explain the Delegation Event Model in Java with a diagram. Write a program demonstrating
ActionListener.
■ EXAM Q: What are adapter classes? Why are they used? Give an example with WindowAdapter.
High-Quality Exam-Oriented Notes Page 27
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
15. QUICK REVISION SUMMARY – ALL KEY POINTS
Multithreading Cheat Sheet
Topic Key Point to Remember
Thread vs Process Thread = lightweight; shares memory. Process = heavy; separate memory.
Creating Thread 2 ways: extend Thread OR implement Runnable. Prefer Runnable.
start() vs run() start() creates new thread. run() = normal method call (no new thread).
Thread Life Cycle NEW → RUNNABLE → RUNNING → BLOCKED/WAITING → TERMINATED
isAlive() Returns true if thread started and not yet finished.
join() Caller waits for the joined thread to complete.
Thread Priority Range 1–10. MIN=1, NORM=5, MAX=10. Only a hint, not guaranteed.
synchronized Prevents race conditions. Only 1 thread in sync block at a time.
Deadlock 4 conditions: Mutual Exclusion, Hold&Wait, No Preemption, Circular Wait
wait()/notify() Object class methods. Must be inside synchronized block.
volatile Ensures variable changes are visible to all threads immediately.
Deprecated: stop/suspend Use boolean flags + wait()/notify() instead.
File I/O FileReader+BufferedReader for read. FileWriter+BufferedWriter for write.
Applet Life Cycle init() → start() → paint() → stop() → destroy()
AWT Heavyweight, platform-dependent GUI. [Link] package.
Delegation Event Model Source → Event Object → Listener → Handler method
Adapter Classes Extend adapter instead of implementing all listener methods.
Top Exam Questions Summary
1. Explain Java thread life cycle with diagram (ALL states and transitions).
2. What are the two ways to create a thread? Write code for both. Which is preferred and why?
3. Differentiate: Process vs Thread, synchronized method vs synchronized block.
4. Explain synchronization with example. What is a race condition? What is deadlock?
5. Explain wait(), notify(), notifyAll() with Producer-Consumer program.
6. Explain applet life cycle with diagram. What is the role of init(), start(), stop(), destroy()?
7. Explain AWT event handling (Delegation model). Write a button click counter program.
8. What are adapter classes in Java AWT? Why are they useful? Give example.
9. Write a Java program to write data to a file and read it back.
10. Explain thread priorities. What are MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY?
11. What is isAlive()? What is join()? Explain with code.
12. Why are suspend(), resume(), stop() deprecated? How to safely stop a thread?
High-Quality Exam-Oriented Notes Page 28
Java Programming – Multithreaded Programming & Applets End-Semester Exam Notes
END OF NOTES — Best of Luck for Your Exams! ■
High-Quality Exam-Oriented Notes Page 29