Module 5: Multithreaded Programming & Java
Features
Threads, Enumerations, Autoboxing
Department of Computer Science & Engineering
MVJCE
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 1 / 125
Agenda
1 Multithreaded Programming in Java
2 Type Wrappers and Autoboxing
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 2 / 125
What is Multithreading?
Definition
Multithreading allows concurrent execution of multiple parts of a
program, called threads. Threads share the same memory space
within a process.
Multithreading means doing more than one task at the
same time.
Each task is done using a small unit called a thread.
All threads work inside the same program.
Threads share memory, so they can work faster.
Example:
One thread for downloading
One thread for music
One thread for typing
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 3 / 125
Thread vs Process
A Process is a full running program.
Each process has its own memory.
Example: One browser, one music player.
A Thread is a small part inside a program.
Threads share the same memory.
Example: One browser with many tabs.
Creating a thread is faster and cheaper than creating a
process.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 4 / 125
Benefits of Multithreading
Better CPU Utilization: The computer does not stay idle and
works efficiently.
Responsive Applications: The application does not freeze
even when a task is slow.
Efficient Resource Sharing: Threads inside the same program
can easily share data.
Economical: Creating threads uses less memory and time than
creating processes.
Multi-core Utilization: Different CPU cores can run different
threads at the same time.
Simple Real-Life Example
A web server can handle many users at the same time using
multithreading.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 5 / 125
Java Thread Model
A thread is a small part of a program that runs independently.
Java supports asynchronous execution, which means:
Tasks can run at the same time
One task does not wait for another to finish
Java uses multiple threads to perform many tasks together.
If one thread is paused, other threads continue working.
This is useful for:
Animations
File downloading
Playing music or videos
Java threads work on:
Single-core systems (threads share CPU time)
Multi-core systems (threads run at the same time)
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 6 / 125
Thread Life Cycle in Java
Main States:
New – Thread object is created but not started.
Runnable – Thread is ready to run and waiting for CPU.
Running – Thread is executing its run() method.
Blocked / Waiting – Thread is not running because it is
waiting for I/O, sleep(), wait(), or a lock.
Terminated – Thread has finished execution.
Common Transitions:
New → Runnable: using [Link]().
Runnable ↔ Running: decided by CPU scheduler.
Running → Blocked: thread calls sleep(), wait(), or waits for
a lock.
Blocked → Runnable: sleep ends, I/O completes, lock available,
or notify() called.
Running → Terminated: run() method finishes.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 7 / 125
Thread Life Cycle Diagram
Figure: Java Thread Life Cycle: New, Runnable, Running, Blocked, and
Terminated States
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 8 / 125
The Main Thread in Java
When a Java program starts, one thread begins immediately.
This is called the Main Thread.
It is the thread that executes the main() method.
Importance of Main Thread
It is the thread from which all child threads are spawned.
It is usually the last thread to finish execution.
It performs important shutdown operations.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 9 / 125
Accessing the Main Thread
The main thread is created automatically by the JVM.
It can be controlled using a Thread object.
A reference to the current thread is obtained using:
Method Syntax
static Thread currentThread()
This method returns a reference to the currently executing
thread.
Once obtained, the main thread can be controlled like any other
thread.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 10 / 125
Program: Controlling the Main Thread
Java Program
// Controlling the main Thread.
class CurrentThreadDemo {
public static void main(String[] args) {
Thread t = [Link]();
[Link]("Current thread: " + t);
// change the name of the thread
[Link]("My Thread");
[Link]("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
[Link](n);
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Main thread interrupted");
}
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 11 / 125
Explanation of the Program
currentThread() gets the reference to the main thread.
The thread reference is stored in variable t.
The current thread details are printed using println().
setName() changes the name of the thread.
A loop runs from 5 to 1 with a 1-second delay using sleep().
try-catch is used because sleep() may throw an exception.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 12 / 125
Program Output
Output
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
Output shows: Thread Name, Priority, and Group Name.
Default name: main
Default priority: 5
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 13 / 125
sleep() Method in Java
Method Syntax
static void sleep(long milliseconds) throws
InterruptedException
Causes the current thread to pause for specified time.
Time is specified in milliseconds.
It may throw InterruptedException.
Second Form
static void sleep(long milliseconds, int nanoseconds)
throws InterruptedException
Allows more precise delay using nanoseconds.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 14 / 125
Thread Name Methods
Method Declarations
final void setName(String threadName)
final String getName()
setName() changes the name of a thread.
getName() returns the name of a thread.
Thread name helps in debugging and monitoring.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 15 / 125
Creating Threads: Two Approaches
1. Extending Thread Class
class MyThread extends Thread {
public void run () {
// thread code
}
}
// Usage
MyThread t = new MyThread () ;
t . start () ;
2. Implementing Runnable Interface
class MyRunnable implements Runnable {
public void run () {
// thread code
}
}
// Usage
Thread t = new Thread ( new MyRunnable () ) ;
t . start () ;
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 16 / 125
Thread Creation (runnable interface)
class NewThread implements Runnable {
Thread t;
NewThread() {
t = new Thread(this, "Demo Thread");
[Link]("Child thread: " + t);
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
[Link]("Child Thread: " + i);
[Link](500);
}
} catch (InterruptedException e) {
[Link]("Child interrupted.");
}
[Link]("Exiting child thread.");
}}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 17 / 125
Main Thread in Java
class ThreadDemo {
public static void main(String[] args) {
NewThread nt = new NewThread();
[Link](); // Start child thread
// Main thread continues execution
for(int i = 5; i > 0; i--) {
[Link]("Main Thread: " + i);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("Main thread interrupted");
}
}
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 18 / 125
Output of Runnable and Main Thread Program
Sample Output
Child thread: Thread[Demo Thread,5,main]
Child Thread: 5
Main Thread: 5
Child Thread: 4
Child Thread: 3
Main Thread: 4
Child Thread: 2
Child Thread: 1
Exiting child thread.
Main Thread: 3
Main Thread: 2
Main Thread: 1
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 19 / 125
Explanation: Runnable and Main Thread
The program creates a thread by implementing the Runnable
interface.
NewThread implements Runnable and defines the run() method.
A Thread object is created using new Thread(this, "Demo
Thread").
Calling start() begins execution of the child thread.
The child thread prints numbers from 5 to 1 with a delay of 500 ms.
The main thread runs simultaneously and prints its own countdown.
Both threads execute independently and concurrently.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 20 / 125
Extending Thread - Part 1
class NewThread extends Thread {
NewThread() {
super("Demo Thread");
[Link]("Child thread: " + this);
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
[Link]("Child Thread: " + i);
[Link](500);
}
} catch (InterruptedException e) {
[Link]("Child interrupted.");
}
[Link]("Exiting child thread.");
} }
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 21 / 125
Extending Thread - Part 2
class ExtendThread {
public static void main(String[] args) {
NewThread nt = new NewThread(); // create a new th
[Link](); // start the thread
// Main thread continues its execution
// ...
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 22 / 125
Creating Multiple Threads – Part 1
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
[Link]("New thread: " + t);
}
// entry point for thread
public void run() {
try {
for(int i = 5; i > 0; i--) {
[Link](name + ": " + i);
[Link](1000);
}
} catch (InterruptedException e) {
[Link](name + " Interrupted");
}
[Link](name + " exiting.");
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 23 / 125
Output of Extending Thread Program
Sample Output
Child thread: Thread[Demo Thread,5,main]
Child Thread: 5
Child Thread: 4
Child Thread: 3
Child Thread: 2
Child Thread: 1
Exiting child thread.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 24 / 125
Explanation: Extending Thread Program
The program creates a thread by extending the Thread class.
The constructor uses super("Demo Thread") to set the thread
name.
Printing this displays thread details (name, priority, group).
The run() method is the entry point of the child thread.
Inside run(), a loop prints numbers from 5 to 1.
[Link](500) pauses the thread for 500 milliseconds.
start() creates a new thread and calls run() internally.
After completing execution, the thread prints "Exiting child
thread."
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 25 / 125
Creating Multiple Threads – Part 2
class MultiThreadDemo {
public static void main(String[] args) {
NewThread nt1 = new NewThread("One");
NewThread nt2 = new NewThread("Two");
NewThread nt3 = new NewThread("Three");
// Start the threads
[Link]();
[Link]();
[Link]();
try {
// wait for other threads to end
[Link](10000);
} catch (InterruptedException e) {
[Link]("Main thread Interrupted");
}
[Link]("Main thread exiting.");
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 26 / 125
Sample Output
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 27 / 125
Using isAlive() and join()
isAlive() Method
Returns true if thread is running
Returns false if thread terminated
Useful for checking thread status
join() Method
Waits for thread to terminate
Calling thread blocks until target thread completes
Can specify timeout
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 28 / 125
Using join() to Wait for Threads – Part 1
// Using join() to wait for threads to finish.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
[Link]("New thread: " + t);
}
// Entry point for thread
public void run() {
try {
for(int i = 5; i > 0; i--) {
[Link](name + ": " + i);
[Link](1000);
}
} catch (InterruptedException e) {
[Link](name + " interrupted.");
}
[Link](name + " exiting.");
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 29 / 125
Using join() to Wait for Threads – Part 2
class DemoJoin {
public static void main(String[] args) {
NewThread nt1 = new NewThread("One");
NewThread nt2 = new NewThread("Two");
NewThread nt3 = new NewThread("Three");
// Start the threads
[Link]();
[Link]();
[Link]();
[Link]("Thread One is alive: " + [Link]());
[Link]("Thread Two is alive: " + [Link]());
[Link]("Thread Three is alive: " + [Link]());
// wait for threads to finish
try {
[Link]("Waiting for threads to finish.");
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread Interrupted");
}
[Link]("Thread One is alive: " + [Link]());
[Link]("Thread Two is alive: " + [Link]());
[Link]("Thread Three is alive: " + [Link]());
[Link]("Main thread exiting.");
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 30 / 125
Output of join() Program
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
One exiting.
Two exiting.
Three exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 31 / 125
Thread Priorities – Part I
Thread priority tells the scheduler which thread is more important.
A thread with a higher priority usually gets more CPU time.
High-priority threads can stop (preempt) low-priority threads and run
first.
Threads with the same priority:
They should ideally get equal CPU time.
But real behavior depends on the operating system.
In systems where threads are not preemptive, threads with equal
priority should sometimes call yield() to let others run.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 32 / 125
Setting Thread Priority:
Use setPriority(int level).
Priority range: MIN PRIORITY (1) to MAX PRIORITY (10).
Default priority: NORM PRIORITY (5).
Getting Thread Priority:
Use getPriority() to retrieve a thread’s priority.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 33 / 125
Setting and Getting Thread Priority
// Set thread priority
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.NORM_PRIORITY); // 5
[Link](Thread.MAX_PRIORITY); // 10
// Get thread priority
[Link]([Link]() + " Priority: " + [Link]());
[Link]([Link]() + " Priority: " + [Link]());
[Link]([Link]() + " Priority: " + [Link]());
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 33 / 125
Need for Synchronization
Problem
Multiple threads accessing shared resources can cause:
Race conditions
Data corruption
Inconsistent states
Solution: Synchronization
Only one thread can own a monitor at a time
Other threads wait for monitor release
Achieved with synchronized keyword
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 34 / 125
Unsynchronized Example – Part I
// This program is not synchronized.
class Callme {
void call(String msg) {
[Link]("[" + msg);
try {
[Link](1000);
} catch(InterruptedException e) {
[Link]("Interrupted");
}
[Link]("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
}
public void run() {
[Link](msg);
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 35 / 125
Unsynchronized Example – Part II
class Synch {
public static void main(String[] args) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
[Link]();
[Link]();
[Link]();
try {
[Link]();
[Link]();
[Link]();
} catch(InterruptedException e) {
[Link]("Interrupted");
}
}
}
Sample Output:
[Hello[Synchronized[World]
]
]
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 36 / 125
Synchronized Example – Part I
// This program uses synchronized to fix the output.
class Callme {
synchronized void call(String msg) {
[Link]("[" + msg);
try {
[Link](1000);
} catch(InterruptedException e) {
[Link]("Interrupted");
}
[Link]("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
}
public void run() {
[Link](msg);
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 37 / 125
Synchronized Example – Part II
class Synch {
public static void main(String[] args) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
[Link]();
[Link]();
[Link]();
try {
[Link]();
[Link]();
[Link]();
} catch(InterruptedException e) {
[Link]("Interrupted");
}
}
}
Sample Output (Correct Ordered):
[Hello]
[Synchronized]
[World]
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 38 / 125
Unsynchronized vs Synchronized Programs
In the unsynchronized program, multiple threads enter the call() method at the same time.
Each thread prints [msg], then sleeps, allowing other threads to execute.
Because there is no synchronization, outputs from different threads get interleaved.
This results in mixed and unordered output, with brackets not matching correctly.
In the synchronized program, the call() method is declared synchronized.
Synchronization ensures that only one thread can execute call() at a time.
Each thread completes printing [msg] before the next thread enters.
Hence, the output becomes correct, ordered, and predictable.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 39 / 125
Interthread Communication – Part I
Interthread Communication: Interthread communication is a
mechanism that allows threads to communicate and coordinate with
each other so that they can share data and work efficiently without
wasting CPU time.
wait():
Makes the current thread stop running and release the lock.
Thread waits until another thread calls notify() or
notifyAll().
notify():
Wakes up one thread that is waiting on the same object’s
monitor.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 40 / 125
Interthread Communication – Part II
notifyAll():
Wakes up all threads waiting on the same object.
Only one thread continues after obtaining the lock.
Spurious Wakeup:
A rare situation where a waiting thread wakes up even though
no notify() or notifyAll() was called.
To avoid errors, always use wait() inside a while loop that
checks the condition again.
Important:
All these methods must be used inside a synchronized block
or method.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 41 / 125
Incorrect Producer-Consumer – Part I
// Incorrect implementation of Producer & Consumer
class Q {
int n;
synchronized int get() {
[Link]("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
[Link]("Put: " + n);
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 42 / 125
Incorrect Producer-Consumer – Part II
class Producer implements Runnable {
Q q;
Thread t;
Producer(Q q) {
this.q = q;
t = new Thread(this, "Producer");
}
public void run() {
int i = 0;
while(true) {
[Link](i++);
}
}
}
class Consumer implements Runnable {
Q q;
Thread t;
Consumer(Q q) {
this.q = q;
t = new Thread(this, "Consumer");
}
public void run() {
while(true) {
[Link]();
}
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 43 / 125
Incorrect Producer-Consumer – Part III
class PC {
public static void main(String[] args) {
Q q = new Q();
Producer p = new Producer(q);
Consumer c = new Consumer(q);
[Link]();
[Link]();
[Link]("Press Control-C to stop.");
}
}
Erroneous Output Example:
Put: 1
Got: 1
Got: 1
Got: 1
Put: 2
Put: 3
Put: 4
Got: 7
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 44 / 125
Why the First Producer-Consumer Program Is Incorrect – Part I
The methods put() and get() are synchronized, but
synchronization alone cannot control the order of execution between
threads.
Problem 1: Producer Overruns Consumer
Producer keeps producing values continuously without waiting.
Consumer cannot consume quickly enough, so values get
overwritten.
Problem 2: Consumer Reads Same Value Multiple Times
Sometimes Consumer runs faster than Producer.
Without coordination, Consumer prints the same value again
and again.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 45 / 125
Why the First Producer-Consumer Program Is Incorrect – Part II
Reason for Bad Output:
No mechanism tells Producer to wait after placing a value.
No mechanism tells Consumer to wait until a new value arrives.
What Synchronization Does NOT Do:
It prevents two threads from running the same method
simultaneously.
But it does NOT manage timing or communication.
Conclusion:
Threads run at different speeds, causing inconsistencies.
To fix this, we must use wait(), notify(), and notifyAll() to
coordinate Producer and Consumer properly.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 46 / 125
Correct Producer-Consumer – Part I
// Correct implementation using wait() and notify()
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
[Link]("InterruptedException caught");
}
[Link]("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(valueSet)
try {
wait();
} catch(InterruptedException e) {
[Link]("InterruptedException caught");
}
this.n = n;
valueSet = true;
[Link]("Put: " + n);
notify();
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 47 / 125
Correct Producer-Consumer – Part II
class Producer implements Runnable {
Q q;
Thread t;
Producer(Q q) {
this.q = q;
t = new Thread(this, "Producer");
}
public void run() {
int i = 0;
while(true) {
[Link](i++);
}
}
}
class Consumer implements Runnable {
Q q;
Thread t;
Consumer(Q q) {
this.q = q;
t = new Thread(this, "Consumer");
}
public void run() {
while(true) {
[Link]();
}
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 48 / 125
Correct Producer-Consumer – Part III
class PCFixed {
public static void main(String[] args) {
Q q = new Q();
Producer p = new Producer(q);
Consumer c = new Consumer(q);
[Link]();
[Link]();
[Link]("Press Control-C to stop.");
}
}
Synchronous Behavior Explanation:
get() waits until Producer puts data.
Producer waits until Consumer gets data.
notify() signals the other thread to continue.
Clean Output Example:
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 49 / 125
Why the Correct Producer-Consumer Program Works – Part I
The correct version uses wait() and notify() to allow Producer
and Consumer to communicate and coordinate properly.
How get() Works:
Consumer calls wait() if there is no new value to consume.
When Producer puts a value and calls notify(), Consumer
wakes up.
How put() Works:
Producer calls wait() if Consumer has not yet taken the
previous value.
After Consumer gets the value and calls notify(), Producer
continues.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 50 / 125
Why the Correct Producer-Consumer Program Works – Part II
Role of valueSet Flag:
Prevents Producer from producing too early.
Prevents Consumer from consuming before a new value is ready.
Result: Clean Alternation
Output becomes: Put 1 → Got 1 → Put 2 → Got 2 → ...
No overwriting and no duplicate reads.
Conclusion:
wait() and notify() ensure proper order and timing.
Producer and Consumer now operate in perfect synchronization.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 51 / 125
Suspending, Resuming, and Stopping Threads
Deprecated Methods in Early Java:
Java originally supported:
suspend()
resume()
stop()
These methods are deprecated because they can cause:
Deadlocks (e.g., suspend() does not release locks)
Data corruption (stop() terminates thread abruptly)
Unsafe behaviour in multithreaded applications
Therefore, they should NOT be used in modern Java code.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 52 / 125
Modern Thread Control Mechanism
Safe Alternative Approach:
Use a flag variable inside the thread:
running – thread continues
suspendFlag – thread waits
stopFlag – thread exits
Threads should periodically check the flag.
Use wait() and notify() for:
suspending a thread safely
resuming a thread safely
Avoids runtime errors and ensures thread-safe behaviour.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 53 / 125
Suspending and Resuming a Thread — Program
// Suspending and resuming a thread the modern way.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
[Link]("New thread: " + t);
suspendFlag = false;
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
[Link](name + ": " + i);
[Link](200);
synchronized(this) {
while(suspendFlag) {
wait();
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 54 / 125
Suspending and Resuming a Thread — Program
}
}
}
} catch (InterruptedException e) {
[Link](name + " interrupted.");
}
[Link](name + " exiting.");
}
synchronized void mysuspend() { suspendFlag = true; }
synchronized void myresume() { suspendFlag = false; notify(); }
}
// Main class
class SuspendResume {
public static void main(String[] args) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
[Link](); // Start the thread
[Link](); // Start the thread
try {
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 55 / 125
Suspending and Resuming a Thread — Program
[Link](1000);
[Link]();
[Link]("Suspending thread One");
[Link](1000);
[Link]();
[Link]("Resuming thread One");
[Link]();
[Link]("Suspending thread Two");
[Link](1000);
[Link]();
[Link]("Resuming thread Two");
} catch (InterruptedException e) {
[Link]("Main thread Interrupted");
}
// wait for threads to finish
try {
[Link]("Waiting for threads to finish.");
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread Interrupted");
}
[Link]("Main thread exiting.");
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 56 / 125
Output of Suspend–Resume Program
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
One: 15
Two: 15
One: 14
Two: 14
One: 13
Suspending thread One
Two: 13
Two: 12
Two: 11
Resuming thread One
One: 12
One: 11
Suspending thread Two
One: 10
One: 9
Resuming thread Two
Two: 10
Two: 9
Waiting for threads to finish.
One exiting.
Two exiting.
Main thread exiting.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 57 / 125
Explanation of Suspend–Resume Program (Part 1)
Why suspend(), resume(), stop() are not used:
These old Thread methods are deprecated because they are unsafe.
suspend() can freeze a thread while it still holds a lock → leads to
deadlock.
stop() can terminate a thread suddenly → data may become
corrupted.
Modern Solution Used in This Program:
Instead of old methods, Java uses a flag variable called
suspendFlag.
The thread checks this flag inside the run() method.
If the flag becomes true, the thread pauses by calling wait().
When the flag is changed to false, the thread wakes up using
notify().
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 58 / 125
Explanation of Suspend–Resume Program (Part 2)
Role of synchronized:
synchronized ensures only one thread accesses suspend/resume logic at a
time.
Required because wait() and notify() must be inside synchronized
blocks.
How the main() method works:
Creates two threads: "One" and "Two".
Starts both using [Link]().
Suspends and resumes each thread with delays using [Link]().
Uses join() to wait for both threads to finish.
Final Output Behavior:
Each thread prints numbers from 15 → 1.
When suspended, printing stops.
When resumed, printing continues.
Both threads exit safely after completing.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 59 / 125
Obtaining a Thread’s State
getState() Method:
Java provides the getState() method to find the current state of a
thread.
It is defined in the Thread class.
Method Syntax:
[Link] getState()
Description:
This method returns an object of type [Link].
[Link] is an enumeration that represents the state of a
thread.
The returned value indicates the thread’s state at the time the
method is called.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 60 / 125
Thread States ([Link] Enumeration)
State Description
NEW Thread has been created but has not started
execution.
RUNNABLE Thread is executing or ready to execute
when CPU is available.
BLOCKED Thread is waiting to acquire a lock to enter
a synchronized block or method.
WAITING Thread is waiting indefinitely for another
thread to perform an action (e.g., wait(),
join()).
TIMED WAITING Thread is waiting for a specified time (e.g.,
sleep(), timed wait(), timed join()).
TERMINATED Thread has finished execution and exited.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 61 / 125
Thread Life Cycle Diagram
figureLife Cycle of a Java Thread Showing Different States
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 62 / 125
Enumerations in Java
An enumeration (enum) is a special data type in Java.
It is used to define a fixed set of named constant values.
Enums are a better and safer alternative to using final constants.
They are commonly used to represent states, days, directions, or
error codes.
Enums are widely used in the Java API.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 63 / 125
Why Use Enumerations?
Improves code readability and clarity.
Prevents invalid values from being assigned.
Makes programs easier to understand and maintain.
Supports methods, variables, and constructors.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 64 / 125
Enumeration Fundamentals: Definition
Enumerations are created using the enum keyword.
The values inside an enum are called enumeration constants.
Each constant represents a fixed legal value.
Example
enum Day { MON, TUE, WED, THU, FRI }
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 65 / 125
Enumeration Constants
Enumeration constants are:
public
static
final
Each constant is an object of the enum type.
Constants cannot be changed once defined.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 66 / 125
Enum Instantiation and Usage
Enums define a class type.
They are not created using the new keyword.
Enum variables are declared like primitive variables.
Example
Day d = [Link];
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 67 / 125
Assignment and Comparison
Enum variables can hold only predefined enum values.
Values are assigned using dot notation.
Enum constants can be compared using ==.
Example
if(d == [Link])
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 68 / 125
Enums in Switch Statement
Enum values can be used in switch statements.
All case labels must belong to the same enum.
Case constants are written without enum name.
Example
switch(d) {
case MON: break;
case TUE: break;
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 69 / 125
Displaying Enumeration Constants
Enum constants are displayed using their names.
They are referenced using dot notation.
Printing an enum prints its constant name.
Example
[Link]([Link]);
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 70 / 125
Apple Enumeration Program (Part 1)
// An enumeration of apple varieties
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo {
public static void main(String[] args) {
Apple ap;
ap = [Link];
// Output an enum value
[Link]("Value of ap: " + ap);
[Link]();
ap = [Link];
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 71 / 125
Apple Enumeration Program (Part 2)
// Compare two enum values
if (ap == [Link])
[Link]("ap contains GoldenDel.\n");
// Use enum in switch statement
switch (ap) {
case Jonathan:
[Link]("Jonathan is red.");
break;
case GoldenDel:
[Link]("Golden Delicious is yellow.");
break;
case RedDel:
[Link]("Red Delicious is red.");
break;
case Winesap:
[Link]("Winesap is red.");
break;
case Cortland:
[Link]("Cortland is red.");
break;
}
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 72 / 125
Output of the Program
Output
Value of ap: RedDel
ap contains GoldenDel.
Golden Delicious is yellow.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 73 / 125
Explanation of Apple Enumeration Program
Apple is an enumeration that defines fixed apple varieties.
Variable ap can store only values from the Apple enum.
First, ap is assigned [Link].
Printing ap displays the enum constant name.
Then ap is assigned [Link].
Enum values are compared using the == operator.
The switch statement uses enum constants as case labels.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 74 / 125
Key Points
Enum constants are public, static, and final.
Enums improve type safety and readability.
Enum values can be compared using ==.
Enums work directly with switch statements.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 75 / 125
values() and valueOf() Methods
All Java enumerations automatically contain two methods:
values()
valueOf()
These methods are provided by Java internally.
They help in accessing and using enum constants easily.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 76 / 125
Method Syntax
General Forms
public static enum-type[] values()
public static enum-type valueOf(String str)
enum-type is the name of the enumeration.
These methods are called using the enum name.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 77 / 125
Purpose of values() and valueOf()
values():
Returns an array containing all enum constants.
Used to loop through enum values.
valueOf():
Returns an enum constant matching the given string.
String must exactly match the constant name.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 78 / 125
Enum Program Using values() and valueOf() (Part
1)
Java Code
// An enumeration of apple varieties
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo2 {
public static void main(String[] args) {
Apple ap;
[Link]("Here are all Apple constants:");
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 79 / 125
Enum Program Using values() and valueOf() (Part
2)
Java Code
// Use values()
Apple[] allapples = [Link]();
for (Apple a : allapples)
[Link](a);
[Link]();
// Use valueOf()
ap = [Link]("Winesap");
[Link]("ap contains " + ap);
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 80 / 125
Output of the Program
Output
Here are all Apple constants:
Jonathan
GoldenDel
RedDel
Winesap
Cortland
ap contains Winesap
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 81 / 125
Explanation of the Program
values() returns all enum constants as an array.
A for-each loop is used to print each constant.
valueOf("Winesap") converts the string into enum constant.
Returned value is stored in enum variable ap.
Enum constants are printed by their names automatically.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 82 / 125
Java Enumerations Are Class Types
In Java, enumerations are treated as class types.
They are more powerful than simple constants.
Enums can contain:
Constructors
Instance variables
Methods
Interface implementations
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 83 / 125
Enumeration Constants as Objects
Each enumeration constant is an object of the enum type.
Constructors can be defined inside an enum.
The constructor is automatically called for each constant.
Instance variables are maintained separately for each constant.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 84 / 125
Enum with Constructor (Apple Example – Part 1)
Java Code
// Use an enum constructor
enum Apple {
Jonathan(10), GoldenDel(9), RedDel,
Winesap(15), Cortland(8);
private int price; // price of each apple
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 85 / 125
Enum with Constructor (Apple Example – Part 2)
Java Code
// Constructor
Apple(int p) {
price = p;
}
// Overloaded constructor
Apple() {
price = -1;
}
int getPrice() {
return price;
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 86 / 125
Explanation of Apple Enum
Each apple variety has its own price.
The constructor initializes the price.
If no price is provided, default value -1 is used.
The getPrice() method returns the apple price.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 87 / 125
Enumerations Inherit [Link]
All enums automatically inherit from [Link].
Enums cannot extend other classes.
But inheritance from Enum is implicit.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 88 / 125
Important Enum Methods
ordinal() – returns position of constant (starts from 0)
compareTo() – compares ordinal values
equals() – checks if two constants are the same
== operator can also be used for comparison
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 89 / 125
Enum Methods Demo (Part 1)
Java Code
// Demonstrate ordinal(), compareTo(), and equals()
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo4 {
public static void main(String[] args) {
Apple ap, ap2, ap3;
[Link]("Here are all apple constants and t
for (Apple a : [Link]())
[Link](a + " " + [Link]());
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 90 / 125
Enum Methods Demo (Part 2)
ap = [Link];
ap2 = [Link];
ap3 = [Link];
[Link]();
if ([Link](ap2) > 0)
[Link](ap2 + " comes before " + ap);
if ([Link](ap3) == 0)
[Link](ap + " equals " + ap3);
if ([Link](ap3))
[Link](ap + " equals " + ap3);
if (ap == ap3)
[Link](ap + " == " + ap3);
}}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 91 / 125
Program Output (Summary)
Each enum constant has an ordinal value.
compareTo() compares based on ordinal.
equals() and == confirm same constant.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 92 / 125
Another Enumeration Example
Earlier, interface constants were used for answers.
Using enums is a better and safer approach.
Enum Answers represents possible responses.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 93 / 125
Decision Maker Using Enum (Part 1)
Java Code
import [Link];
// Enumeration of possible answers
enum Answers {
NO, YES, MAYBE, LATER, SOON, NEVER
}
class Question {
Random rand = new Random();
Answers ask() {
int prob = (int)(100 * [Link]());
if (prob < 15)
return [Link];
else if (prob < 30)
return [Link];
else if (prob < 60)
return [Link];
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 94 / 125
Decision Maker Using Enum (Part 2)
Java Code
else if (prob < 75)
return [Link];
else if (prob < 98)
return [Link];
else
return [Link];
}
}
class AskMe {
static void answer(Answers result) {
switch (result) {
case NO: [Link]("No"); break;
case YES: [Link]("Yes"); break;
case MAYBE: [Link]("Maybe"); break;
case LATER: [Link]("Later"); break;
case SOON: [Link]("Soon"); break;
case NEVER: [Link]("Never"); break;
}
}
public static void main(String[] args) {
Question q = new Question();
answer([Link]());
answer([Link]());
answer([Link]());
answer([Link]());
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 95 / 125
Key Takeaways
Enums are full-fledged class types in Java.
Enum constants are objects.
Enums support constructors, methods, and inheritance from Enum.
Enums make programs safer and more readable.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 96 / 125
Type Wrappers in Java
What are Type Wrappers?
Classes that encapsulate primitive types as objects, allowing primitives to
be used where objects are required.
Java provides type wrapper classes for primitive data types.
A wrapper class converts a primitive type into an object.
This allows primitive values to be used where objects are required.
Wrapper classes integrate primitive types into Java’s object-oriented
structure.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 97 / 125
Wrapper Classes
Byte – wraps byte
Short – wraps short
Integer – wraps int
Long – wraps long
Float – wraps float
Double – wraps double
Character – wraps char
Boolean – wraps boolean
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 98 / 125
Autoboxing and Unboxing
Autoboxing: automatic conversion of primitive type to wrapper
object.
Unboxing: automatic conversion of wrapper object to primitive type.
These conversions are handled automatically by the compiler.
Autoboxing simplifies programming and reduces code complexity.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 99 / 125
Character Wrapper Class
Character is a wrapper around the primitive type char.
Earlier constructor:
Character(char ch)
From JDK 9, constructors are deprecated.
Recommended method:
static Character valueOf(char ch)
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 100 / 125
Character Methods
valueOf(char ch):
Returns a Character object that wraps the character.
charValue():
Returns the primitive char value.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 101 / 125
Boolean Wrapper Class
Boolean is a wrapper around the primitive type boolean.
Old constructors (deprecated):
Boolean(boolean value)
Boolean(String value)
New recommended methods:
[Link](boolean value)
[Link](String value)
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 102 / 125
Boolean Methods
valueOf() returns a Boolean object.
booleanValue():
Returns the primitive boolean value.
String "true" (any case) gives true, otherwise false.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 103 / 125
Numeric Type Wrappers
Numeric wrapper classes:
Byte, Short, Integer
Long, Float, Double
All numeric wrappers inherit from the abstract class Number.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 104 / 125
Number Class Methods
byteValue()
shortValue()
intValue()
longValue()
floatValue()
doubleValue()
Purpose: Convert the wrapped value into different numeric forms.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 105 / 125
Integer Wrapper Constructors
Integer(int num)
Integer(String str)
If the string is invalid, NumberFormatException is thrown.
Preferred factory methods:
[Link](int val)
[Link](String valStr)
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 106 / 125
Boxing and Unboxing Example
Java Code
// Demonstrate a type wrapper
class Wrap {
public static void main(String[] args) {
Integer iOb = [Link](100); // boxing
int i = [Link](); // unboxing
[Link](i + " " + iOb); // 100 100
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 107 / 125
Boxing and Unboxing Explained
Boxing: converting primitive to wrapper object.
Example:
Integer iOb = [Link](100);
Unboxing: converting wrapper object to primitive.
Example:
int i = [Link]();
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 108 / 125
Key Takeaways
Wrapper classes bridge primitive types and objects.
Autoboxing and unboxing simplify coding.
Numeric wrappers inherit from Number.
Wrapper classes override toString() for easy output.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 109 / 125
Autoboxing and Methods
Autoboxing occurs when a primitive value is converted into an object.
Auto-unboxing occurs when an object is converted into a primitive.
These conversions happen automatically when:
Passing arguments to methods
Returning values from methods
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 110 / 125
Autoboxing with Methods
Java Code
// Autoboxing/unboxing with methods
class AutoBox2 {
// Takes Integer and returns int
static int m(Integer v) {
return v; // auto-unboxing
}
public static void main(String[] args) {
// 100 is autoboxed into Integer
Integer iOb = m(100);
[Link](iOb);
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 111 / 125
Output and Explanation
Output
100
Primitive 100 is autoboxed into Integer.
Method returns int, which is again autoboxed.
All conversions happen automatically.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 112 / 125
Autoboxing/Unboxing in Expressions
Autoboxing and unboxing also occur inside expressions.
Wrapper objects are automatically unboxed.
Expression result is reboxed if required.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 113 / 125
Autoboxing in Expressions (Part 1)
Java Code
class AutoBox3 {
public static void main(String[] args) {
Integer iOb, iOb2;
int i;
iOb = 100;
[Link]("Original value of iOb: " + iOb);
++iOb; // unbox, increment, rebox
[Link]("After ++iOb: " + iOb);
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 114 / 125
Autoboxing in Expressions (Part 2)
Java Code
iOb2 = iOb + (iOb / 3);
[Link]("iOb2 after expression: " + iOb2);
i = iOb + (iOb / 3);
[Link]("i after expression: " + i);
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 115 / 125
Output Explanation
Output
Original value of iOb: 100
After ++iOb: 101
iOb2 after expression: 134
i after expression: 134
++iOb unboxes, increments, and reboxes.
Expression results are reboxed if stored in wrapper.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 116 / 125
Mixing Numeric Wrapper Types
Java Code
class AutoBox4 {
public static void main(String[] args) {
Integer iOb = 100;
Double dOb = 98.6;
dOb = dOb + iOb;
[Link]("dOb after expression: " + dOb);
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 117 / 125
Explanation
Integer and Double are auto-unboxed.
Standard numeric promotion occurs.
Result is reboxed into Double.
Output
dOb after expression: 198.6
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 118 / 125
Using Integer in switch
Java Code
Integer iOb = 2;
switch(iOb) {
case 1:
[Link]("one");
break;
case 2:
[Link]("two");
break;
default:
[Link]("error");
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 119 / 125
Boolean and Character Autoboxing
Java Code
class AutoBox5 {
public static void main(String[] args) {
Boolean b = true;
if (b)
[Link]("b is true");
Character ch = ’x’;
char ch2 = ch;
[Link]("ch2 is " + ch2);
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 120 / 125
Output
Output
b is true
ch2 is x
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 121 / 125
Autoboxing Helps Prevent Errors
Manual unboxing can cause unexpected errors.
Autoboxing/unboxing avoids incorrect conversions.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 122 / 125
Manual Unboxing Error Example
Java Code
class UnboxingError {
public static void main(String[] args) {
Integer iOb = 1000;
int i = [Link](); // incorrect unboxing
[Link](i);
}
}
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 123 / 125
Key Takeaways
Autoboxing/unboxing simplifies code.
Works with methods, expressions, switch, Boolean, Character.
Reduces errors compared to manual unboxing.
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 124 / 125
Thank You!
Questions?
Department of Computer Science & Engineering
Module
(MVJCE)
5: Multithreaded Programming & Java Features 125 / 125