OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
OBJECT ORIENTED PROGRAMMING THROUGH JAVA
UNIT - III : Exception handling and Multithreading-- Concepts of exception handling,
benefits of exception handling, Termination or resumptive models, exception
hierarchy, usage of try, catch, throw, throws and finally, built in exceptions, creating
own exception subclasses. String handling, Exploring java.util. Differences between
multithreading and multitasking, thread life cycle, creating threads, thread priorities,
synchronizing threads, inter thread communication, thread groups, daemon threads.
Enumerations, autoboxing, annotations, generics.
Exception Handling in Java – Concepts
1. What is an Exception?
An exception is an unexpected event that occurs during program execution
and disrupts the normal flow of instructions.
It is an object that is thrown at runtime.
Example:
o Dividing by zero → ArithmeticException
o Accessing an array beyond size → ArrayIndexOutOfBoundsException
2. Error vs Exception
Feature Error Exception
Serious problems that cannot be Events that can be handled
Definition
handled by program using try-catch
OutOfMemoryError, ArithmeticException,
Example
StackOverflowError NullPointerException
Recoverable? ❌No ✅Yes
3. Types of Exceptions
1. Checked Exceptions (compile-time exceptions)
o Must be either handled using try-catch or declared with throws.
o Example: IOException, SQLException.
2. Unchecked Exceptions (runtime exceptions)
o Occur during execution, not checked at compile time.
o Example: ArithmeticException, NullPointerException.
3. Errors
o Beyond control of program.
o Example: OutOfMemoryError.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 1
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
4. Example Program (Exception Concept)
public class ExceptionConcept
{
public static void main(String[] args)
{
int a = 10, b = 0;
try {
int c = a / b; // risky code
System.out.println("Result: " + c);
} catch (ArithmeticException e)
{
System.out.println("Exception caught: " + e);
}
System.out.println("Program continues...");
}
}
Output
Exception caught: java.lang.ArithmeticException: / by zero
Program continues...
5. Key Concepts
Exception handling allows separating error-handling code from normal code.
Prevents program termination on runtime errors.
Uses keywords: try, catch, throw, throws, finally.
Benefits of Exception Handling in Java
1. Graceful Error Handling
Without exception handling, the program terminates abruptly on errors.
With exception handling, errors are caught and managed, and the program
continues execution.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 2
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Example
public class Benefit1 ‘
{
public static void main(String[] args)’
{
int arr[] = {10, 20, 30};
try {
System.out.println(arr[5]); // invalid index
} catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error: " + e);
}
System.out.println("Program did not crash!");
}
}
Output:
Error: java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
Program did not crash!
2. Separation of Error-Handling Code from Normal Code
Code remains clean and readable.
Error-handling is kept separate inside catch block.
Example
public class Benefit2 {
public static void main(String[] args) {
try {
int num = Integer.parseInt("ABC"); // risky
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + e.getMessage());
}
}
}
Output:
Invalid number format: For input string: "ABC"
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 3
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
3. Propagation of Errors (Exception Propagation)
Exceptions can be thrown up the call stack to be handled at a higher level.
Example
class A {
void methodA() {
int x = 5 / 0; // generates exception
}
}
public class Benefit3 {
public static void main(String[] args) {
try {
new A().methodA();
} catch (ArithmeticException e) {
System.out.println("Caught at higher level: " + e);
}
}
}
Output:
Caught at higher level: java.lang.ArithmeticException: / by zero
4. Ensures Program Continuity
Allows program to continue execution even if an error occurs.
Summary of Benefits
1. Provision to Complete Program Execution
2. Easy Identiication of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
6. Prevents abnormal termination.
7. Improves reliability of applications.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 4
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Models of Exception Handling
1. Termination Model
In this model, once an exception is caught, the program control cannot
return to the point where the exception occurred.
Instead, it terminates the block where the error occurred and moves on with
the next statement after the catch block.
Java uses the Termination Model.
Example (Java)
public class TerminationModel
{
public static void main(String[] args) {
try {
int x = 10 / 0; // Exception occurs here
System.out.println("This will not execute");
} catch (ArithmeticException e) {
System.out.println("Error handled: " + e);
}
System.out.println("Program continues after catch block...");
}
}
Output:
Error handled: java.lang.ArithmeticException: / by zero
Program continues after catch block...
Note: After handling the exception, program does not go back to int x = 10/0;. It
moves forward.
2. Resumptive Model
In this model, once the exception is handled, the program resumes
execution from the point where the exception occurred.
The faulty statement is retried (after correction).
Java does NOT support this model, but some older programming languages
(like PL/I) did.
Conceptual Example (Not Java):
try {
risky code;
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 5
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
} catch {
fix problem;
resume from risky code;
}
A workaround in Java that simulates resumptive behavior by re-executing the faulty
statement after handling.
1. Conceptual Example (Pseudo-code in a language that supports Resumptive
Model)
try {
x = 10 / y; // risky division
} catch (DivideByZeroException e) {
y = 2; // fix problem
resume; // resume execution from x = 10 / y
}
If y = 0, exception occurs → handler fixes y = 2 → program resumes from the
division again.
2. Simulating Resumptive Model in Java
public class ResumptiveExample
{
public static void main(String[] args)
{
int a = 10, b = 0;
try {
int result = a / b; // risky division
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// fix the problem and retry
b = 2;
int result = a / b; // retry operation
System.out.println("Fixed Result: " + result);
}
}
}
Output
Fixed Result: 5
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 6
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Key Point
Java strictly follows the Termination Model.
This means once an exception is thrown and caught, the program never goes
back to the point of error, but continues after the catch or finally block.
Exception Hierarchy in Java
1. Root Class → Throwable
All exceptions and errors in Java are subclasses of the Throwable class.
It has two main branches:
1. Exception (recoverable conditions)
2. Error (serious problems, usually unrecoverable)
2. Hierarchy Diagram
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 7
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
java.lang.Object
|
---> java.lang.Throwable
|
+-- java.lang.Exception
| |
| +-- RuntimeException (unchecked exceptions)
| | +-- NullPointerException
| | +-- ArithmeticException
| | +-- ArrayIndexOutOfBoundsException
| |
| +-- IOException (checked exception)
| +-- SQLException (checked exception)
|
+-- java.lang.Error
+-- OutOfMemoryError
+-- StackOverflowError
3. Exceptions
Checked Exceptions (compile-time)
Must be handled with try-catch or declared with throws.
Examples:
o IOException (file handling issues)
o SQLException (database errors)
import java.io.*;
public class CheckedExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("missing.txt"); // file may not exist
} catch (IOException e) {
System.out.println("File error: " + e);
}
}
}
Unchecked Exceptions (runtime)
Occur during execution, not checked at compile time.
Subclasses of RuntimeException.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 8
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Examples:
o NullPointerException
o ArithmeticException
o ArrayIndexOutOfBoundsException
public class UncheckedExample
{
public static void main(String[] args)
{
int nums[] = {1, 2, 3};
System.out.println(nums[5]); // ArrayIndexOutOfBoundsException
}
}
4. Errors
Indicate serious problems that applications should not try to handle.
Examples:
o OutOfMemoryError
o StackOverflowError
public class ErrorExample
{
public static void recursive()
{
recursive(); // infinite recursion → StackOverflowError
}
public static void main(String[] args) {
recursive();
} }
Summary
Throwable is the root of all errors/exceptions.
Exception → recoverable problems.
o Checked (must handle)
o Unchecked (runtime errors)
Error → serious problems, not handled by programs.
Usage of try, catch, throw, throws, and finally
1. try
Used to wrap risky code (code that may throw an exception).
If an exception occurs inside the try block, control is transferred to the catch.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 9
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Example
public class TryExample
{
public static void main(String[] args) {
try {
int a = 10 / 0; // risky code
System.out.println("This will not execute");
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
}
}
}
Output:
Exception caught: java.lang.ArithmeticException: / by zero
2. catch
Used to handle exceptions thrown by the try block.
You can have multiple catch blocks for different exception types.
Example
public class CatchExample {
public static void main(String[] args) {
try {
String s = null;
System.out.println(s.length()); // NullPointerException
} catch (NullPointerException e) {
System.out.println("Null pointer problem handled!");
}
}
}
Output:
Null pointer problem handled!
3. throw
Used to explicitly throw an exception object inside a method or block.
Syntax: throw new ExceptionType("message");
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 10
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Example
public class ThrowExample
{
public static void main(String[] args) {
try {
// Explicitly throwing an exception
throw new ArithmeticException("Division by zero not allowed!");
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
System.out.println("Program continues after handling exception...");
}
}
Output:
Exception caught: Division by zero not allowed!
Program continues after handling exception...
4. throws
Used in method declaration to indicate that the method may throw exceptions.
Caller must handle or declare them.
Example
import java.io.*;
public class ThrowsExample
{
static void readFile() throws IOException {
FileReader fr = new FileReader("test.txt"); // may throw IOException
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("File handling error: " + e);
}
}
}
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 11
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Output:
File handling error: java.io.FileNotFoundException: test.txt (No such file or directory)
5. finally
A block that always executes, whether or not an exception occurs.
Commonly used for cleanup code (closing files, DB connections, etc.).
Example
public class FinallyExample
{
public static void main(String[] args) {
try {
int a = 10 / 0; // risky
} catch (ArithmeticException e) {
System.out.println("Exception handled: " + e);
} finally {
System.out.println("Finally block executed");
}
System.out.println("Rest of the code...");
}
}
Output:
Exception handled: java.lang.ArithmeticException: / by zero
Finally block executed
Rest of the code...
Summary
Keyword Purpose
try Wraps risky code where exception may occur
catch Handles the exception thrown by try
throw Explicitly throws an exception
throws Declares exceptions a method may throw
finally Always executes (cleanup code)
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 12
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Built-in Exceptions in Java
Java provides a rich set of predefined (built-in) exception classes in the java.lang
package.
These exceptions are automatically available without importing any extra package.
1. Categories of Built-in Exceptions
Checked Exceptions (Compile-time)
Must be either handled with try-catch or declared using throws.
Examples:
o IOException
o SQLException
o ClassNotFoundException
o InterruptedException
Unchecked Exceptions (Runtime)
Subclasses of RuntimeException.
Occur during execution, not checked at compile time.
Examples:
o ArithmeticException
o NullPointerException
o ArrayIndexOutOfBoundsException
o NumberFormatException
o StringIndexOutOfBoundsException
Errors (Serious issues, not handled)
Subclasses of Error.
Examples:
o OutOfMemoryError
o StackOverflowError
2. Common Built-in Exceptions with Examples
1. ArithmeticException
public class ArithmeticDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // division by zero
} catch (ArithmeticException e) {
System.out.println("Error: " + e);
}
}
}
Output:
Error: java.lang.ArithmeticException: / by zero
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 13
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
2. NullPointerException
public class NullPointerDemo {
public static void main(String[] args) {
try {
String s = null;
System.out.println(s.length()); // accessing null object
} catch (NullPointerException e) {
System.out.println("Error: " + e);
}
}
}
Output:
Error: java.lang.NullPointerException
3. ArrayIndexOutOfBoundsException
public class ArrayIndexDemo {
public static void main(String[] args) {
try {
int arr[] = {10, 20, 30};
System.out.println(arr[5]); // invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e);
}
}
}
Output:
Error: java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
4. NumberFormatException
public class NumberFormatDemo {
public static void main(String[] args) {
try {
int num = Integer.parseInt("ABC"); // invalid integer
} catch (NumberFormatException e) {
System.out.println("Error: " + e);
}
}
}
Output:
Error: java.lang.NumberFormatException: For input string: "ABC"
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 14
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
5. StringIndexOutOfBoundsException
public class StringIndexDemo {
public static void main(String[] args) {
try {
String s = "JAVA";
System.out.println(s.charAt(10)); // invalid index
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Error: " + e);
}
}
}
Output:
Error: java.lang.StringIndexOutOfBoundsException: String index out of range: 10
Summary
Exception When it occurs
ArithmeticException Divide by zero
NullPointerException Accessing object with null reference
ArrayIndexOutOfBoundsException Accessing array element outside range
NumberFormatException Invalid string to number conversion
StringIndexOutOfBoundsException Accessing invalid string index
IOException File handling errors
SQLException Database errors
OutOfMemoryError Memory exhausted
StackOverflowError Infinite recursion
User-Defined Exceptions in Java
1. What is a User-Defined Exception?
Java already provides many built-in exceptions, but sometimes we need to
create custom exceptions for specific business logic.
Example:
o In an ATM system, throwing an InsufficientFundsException when
withdrawal amount exceeds balance.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 15
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
To create one:
1. Create a class that extends Exception (for checked exceptions) or
RuntimeException (for unchecked exceptions).
2. Use throw to explicitly throw the exception.
3. Handle it using try-catch.
2. Syntax
class MyException extends Exception
{
public MyException(String message) {
super(message); // pass message to Exception class
}
}
3. Example – Age Validation
// Step 1: Create custom exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message)
{
super(message);
}
}
public class CustomExceptionDemo
{
// Step 2: Method that declares exception
static void checkAge(int age) throws InvalidAgeException {
if (age < 18)
{
// Step 3: Throw exception
throw new InvalidAgeException("Age must be 18 or above to vote.");
} else {
System.out.println("Valid age. You can vote!");
}
}
public static void main(String[] args) {
try {
checkAge(15); // risky call
} catch (InvalidAgeException e)
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 16
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
{
System.out.println("Caught: " + e.getMessage());
}
}
}
Output
Caught: Age must be 18 or above to vote.
Built-in vs User-defined Exceptions in Java
Aspect Built-in Exceptions User-defined Exceptions
Predefined exception classes
Custom exception classes created by the
Definition provided by Java (java.lang
programmer.
package).
ArithmeticException, InvalidAgeException,
Examples NullPointerException, InsufficientFundsException,
IOException, SQLException. NegativeMarksException.
Handle common programming Handle application-specific errors
Purpose
errors and runtime issues. based on business logic.
Created by extending Exception
Creation Already available in Java. (checked) or RuntimeException
(unchecked).
Thrown automatically by JVM
Throwing Must be thrown explicitly using throw.
or explicitly using throw.
Handled using try-catch or Also handled using try-catch or declared
Handling
declared using throws. using throws.
Can be reused across any Java
Reusability Tailored to specific application needs.
program.
class InvalidAgeException extends
Example try { int x = 10/0; } catch
Exception { ... } throw new
Code (ArithmeticException e) { ... }
InvalidAgeException("Invalid Age");
Summary
Built-in Exceptions → Handle general programming errors.
User-defined Exceptions → Handle specific business logic errors (e.g.,
underage voting, insufficient funds, invalid input).
Both work with the same mechanism: try, catch, throw, throws, and optionally
finally.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 17
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
String Handling in Java
1. What is a String?
A String is a sequence of characters.
In Java, strings are represented by the String class in the java.lang package.
Strings are immutable → once created, they cannot be changed.
Example
public class StringBasics
{
public static void main(String[] args
){
String s1 = "Hello"; // String literal
String s2 = new String("Hi"); // Using new keyword
System.out.println(s1);
System.out.println(s2);
}
}
Output:
Hello
Hi
2. Ways to Create Strings
1. String Literal
String s1 = "Java";
Stored in String Constant Pool (SCP).
2. Using new keyword
String s2 = new String("Java");
Stored in heap memory (outside SCP).
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 18
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
3. Common String Methods
Method Description Example Output
Returns length of
length() "Java".length() 4
string
Returns char at
charAt(int i) "Java".charAt(2) v
index
Concatenates
concat(String s) "Hello".concat("World") HelloWorld
two strings
Compares strings
equals(Object o) "Java".equals("java") false
(case-sensitive)
equalsIgnoreCase(String Compares
"Java".equalsIgnoreCase("java") true
s) ignoring case
Converts to
toUpperCase() "java".toUpperCase() JAVA
uppercase
Converts to
toLowerCase() "JAVA".toLowerCase() java
lowercase
substring(int begin, int
Extract substring "Programming".substring(0, 6) Progra
end)
4. Example Program (String Methods)
public class StringMethods {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "Programming";
System.out.println("Length: " + str1.length());
System.out.println("Character at index 2: " + str1.charAt(2));
System.out.println("Concatenation: " + str1.concat(" " + str2));
System.out.println("Equals: " + str1.equals("JAVA"));
System.out.println("Equals Ignore Case: " + str1.equalsIgnoreCase("JAVA"));
System.out.println("Uppercase: " + str2.toUpperCase());
System.out.println("Substring: " + str2.substring(0, 6));
}
}
Output
Length: 4
Character at index 2: v
Concatenation: Java Programming
Equals: false
Equals Ignore Case: true
Uppercase: PROGRAMMING
Substring: Progra
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 19
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Exploring java.util Package in Java
1. Introduction
The java.util package is one of the most widely used utility packages in Java.
It contains collections framework, date & time utilities, random number
generator, scanner class, string tokenizer, etc.
It provides helper classes that make programming tasks easier.
2. Commonly Used Classes in java.util
(A) Scanner – Input Handling
Used to take input from keyboard, file, or string.
import java.util.*;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name);
sc.close();
}
}
Output (user enters "Ravi"):
Enter your name: Ravi
Hello, Ravi
(B) Random – Random Number Generation
Used to generate random numbers.
import java.util.*;
public class RandomDemo {
public static void main(String[] args) {
Random rand = new Random();
System.out.println("Random int: " + rand.nextInt(100)); // 0 to 99
System.out.println("Random double: " + rand.nextDouble());
}
}
Output (sample):
Random int: 42
Random double: 0.732187142
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 20
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
(C) Date – Date and Time
Represents date and time.
import java.util.*;
public class DateDemo {
public static void main(String[] args) {
Date d = new Date();
System.out.println("Current Date & Time: " + d);
}
}
Output (sample):
Current Date & Time: Mon Sep 09 10:15:30 IST 2025
(D) StringTokenizer – Splitting Strings
Used to break a string into tokens (words).
import java.util.*;
public class StringTokenizerDemo {
public static void main(String[] args) {
String text = "Java is fun";
StringTokenizer st = new StringTokenizer(text, " ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:
Java
is
fun
(E) Collections Framework (Brief)
Some important classes in java.util for data structures:
ArrayList, LinkedList → List implementations.
HashSet, TreeSet → Set implementations.
HashMap, TreeMap → Map implementations.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 21
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
import java.util.*;
public class CollectionDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
System.out.println("Languages: " + list);
}
}
Output:
Languages: [Java, Python, C++]
Multithreading in Java
1. What is Multithreading?
Multithreading is a programming feature that allows concurrent execution of
two or more parts of a program (called threads) for maximum CPU utilization.
A thread is a lightweight subprocess – the smallest unit of processing.
Multithreading enables parallelism in programs.
Example (Concept):
A text editor can:
o Run spell check,
o Save files automatically,
o Accept user typing — all at the same time.
2. Difference: Multithreading vs Multitasking
Feature Multitasking Multithreading
Running multiple programs Running multiple threads within
Definition
(processes) at the same time the same program
Level Process-level Thread-level
Resource
Heavyweight (separate memory) Lightweight (shared memory)
Usage
Running Chrome + MS Word A browser downloading files while
Example
simultaneously rendering a page
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 22
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
3. Thread Life Cycle
A thread in Java goes through different states:
1. New – Thread created but not started.
2. Runnable – Thread is ready to run but waiting for CPU.
3. Running – Thread currently executing.
4. Blocked/Waiting – Thread temporarily inactive.
5. Terminated (Dead) – Thread has finished execution.
4. Creating Threads in Java
There are two ways to create a thread:
(A) By Extending Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class ThreadExample1 {
public static void main(String[] args) {
MyThread t1 = new MyThread(); // create thread object
t1.start(); // start thread
}
}
Output:
Thread is running...
(B) By Implementing Runnable Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running using Runnable...");
}
}
public class ThreadExample2 {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable()); // pass runnable object
t1.start(); // start thread
}
}
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 23
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Output:
Thread is running using Runnable...
5. Thread Priorities
Each thread has a priority (1 to 10).
Default priority = 5.
JVM thread scheduler uses priorities as hints.
class PriorityDemo extends Thread {
public void run() {
System.out.println("Running thread: " + Thread.currentThread().getName() +
" Priority: " + Thread.currentThread().getPriority());
}
}
public class ThreadPriorityTest {
public static void main(String[] args) {
PriorityDemo t1 = new PriorityDemo();
PriorityDemo t2 = new PriorityDemo();
t1.setPriority(Thread.MIN_PRIORITY); // 1
t2.setPriority(Thread.MAX_PRIORITY); // 10
t1.start();
t2.start();
}
}
Output (order may vary):
Running thread: Thread-0 Priority: 1
Running thread: Thread-1 Priority: 10
Summary
Multithreading → multiple threads inside one program.
Multitasking → multiple programs running at once.
Thread lifecycle → New → Runnable → Running → Waiting → Terminated.
Ways to create threads → extend Thread class or implement Runnable.
Thread priorities help scheduler decide execution order.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 24
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Synchronizing Threads in Java
1. Why Synchronization?
In multithreading, multiple threads may try to access a shared resource at
the same time.
This can cause data inconsistency (called a race condition).
Synchronization ensures that only one thread accesses a shared resource at a
time.
2. How to Achieve Synchronization?
1. Synchronized Method
o Declare a method with synchronized keyword.
o Only one thread can execute it at a time.
Example
class Table {
synchronized void printTable(int n)
{ // synchronized method
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try { Thread.sleep(500); } catch (Exception e) {}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t) { this.t = t; }
public void run() { t.printTable(5); }
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t) { this.t = t; }
public void run() { t.printTable(100); }
}
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 25
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
public class SyncMethodExample
{
public static void main(String[] args) {
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
Output (without mixing):
5
10
15
20
25
100
200
300
400
500
Without Synchronization
class Table
{
void printTable(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try { Thread.sleep(500); } catch (Exception e) {}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t) { this.t = t; }
public void run() { t.printTable(5); }
}
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 26
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t) { this.t = t; }
public void run() { t.printTable(100); }
}
public class SyncMethodExample1 {
public static void main(String[] args) {
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
2. Synchronized Block
o Instead of synchronizing the whole method, only synchronize the critical
section.
Example
class Display
{
void show(String message) {
// Only this part is synchronized
synchronized(this) {
for (int i = 1; i <= 3; i++) {
System.out.println(message + " - " + i);
try { Thread.sleep(500); } catch (Exception e) {}
}
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 27
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
}
}
}
public class SimpleSyncBlock {
public static void main(String[] args) {
Display d = new Display();
Thread t1 = new Thread(() -> d.show("Hello"));
Thread t2 = new Thread(() -> d.show("World"));
t1.start();
t2.start();
}
}
Possible Output (No Mixing)
Hello - 1
Hello - 2
Hello - 3
World - 1
World - 2
World - 3
With synchronized(this), only one thread at a time can execute the block, so the
messages print in order.
Inter-thread Communication in Java
1. Why Inter-thread Communication?
When multiple threads share data, sometimes one thread must wait until
another thread finishes its work.
Example:
o A Producer thread generates data.
o A Consumer thread consumes it.
To coordinate, we use:
o wait() → makes a thread wait until it is notified.
o notify() → wakes up one waiting thread.
o notifyAll() → wakes up all waiting threads.
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 28
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
2. Simple Example – Producer & Consumer
class SharedData {
int number;
boolean hasValue = false;
synchronized void produce(int num) {
while (hasValue) {
try { wait(); } catch (Exception e) {}
}
number = num;
System.out.println("Produced: " + number);
hasValue = true;
notify(); // wake up consumer
}
synchronized void consume() {
while (!hasValue) {
try { wait(); } catch (Exception e) {}
}
System.out.println("Consumed: " + number);
hasValue = false;
notify(); // wake up producer
}
}
public class InterThreadDemo {
public static void main(String[] args) {
SharedData data = new SharedData();
// Producer thread
Thread producer = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
data.produce(i);
try { Thread.sleep(500); } catch (Exception e) {}
}
});
// Consumer thread
Thread consumer = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
data.consume();
try { Thread.sleep(500); } catch (Exception e) {}
}
});
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 29
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
producer.start();
consumer.start();
}
}
Output (Orderly Execution)
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
3. Key Rules
wait(), notify(), and notifyAll() must be called inside a synchronized
block/method.
wait() → releases lock and pauses thread until notified.
notify() → wakes up one waiting thread.
notifyAll() → wakes up all waiting threads.
1. Thread Groups
A ThreadGroup represents a group of threads.
Helps organize multiple threads into one unit.
Useful for managing many threads at once (e.g., starting/stopping them
together).
Example – ThreadGroup
public class ThreadGroupDemo {
public static void main(String[] args) {
// Create a ThreadGroup
ThreadGroup tg = new ThreadGroup("MyGroup");
// Create threads inside the group
Thread t1 = new Thread(tg, () -> {
System.out.println(Thread.currentThread().getName() + " is running");
}, "Thread-1");
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 30
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Thread t2 = new Thread(tg, () -> {
System.out.println(Thread.currentThread().getName() + " is running");
}, "Thread-2");
t1.start();
t2.start();
// Print group details
System.out.println("Thread Group Name: " + tg.getName());
tg.list(); // prints details of threads in the group
}
}
Sample Output
Thread-1 is running
Thread-2 is running
Thread Group Name: MyGroup
java.lang.ThreadGroup[name=MyGroup,maxpri=10]
Thread[Thread-1,5,MyGroup]
Thread[Thread-2,5,MyGroup]
2. Daemon Threads
A Daemon thread runs in the background and provides services to user
threads.
JVM automatically ends daemon threads when all user threads finish.
Example: Garbage Collector is a daemon thread.
Example – Daemon Thread
public class DaemonThreadDemo extends Thread {
public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println("Daemon thread running...");
} else {
System.out.println("User thread running...");
}
}
public static void main(String[] args) {
DaemonThreadDemo t1 = new DaemonThreadDemo();
DaemonThreadDemo t2 = new DaemonThreadDemo();
t1.setDaemon(true); // make t1 daemon
t1.start();
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 31
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
t2.start();
}
}
Sample Output
Daemon thread running...
User thread running...
Summary
Thread Groups → Used to manage multiple threads as a single unit.
Daemon Threads → Background helper threads (end automatically when user
threads finish).
Enumerations, Autoboxing, Annotations, and Generics in Java
1. Enumerations (enum)
An enum is a special type in Java used to define a collection of constants.
Enums improve readability and type-safety.
Example – Enum for Days
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }
public class EnumDemo
{
public static void main(String[] args) {
Day d = Day.MONDAY;
System.out.println("Today is: " + d);
for (Day day : Day.values()) {
System.out.println(day);
}
}
}
Output:
Today is: MONDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 32
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
2. Autoboxing and Unboxing
Autoboxing → Automatic conversion of primitive type → Wrapper object.
Unboxing → Automatic conversion of Wrapper object → primitive type.
Example
public class AutoBoxDemo {
public static void main(String[] args) {
int a = 10;
// Autoboxing: int → Integer
Integer obj = a;
System.out.println("Autoboxed: " + obj);
// Unboxing: Integer → int
int b = obj;
System.out.println("Unboxed: " + b);
}
}
Output:
Autoboxed: 10
Unboxed: 10
3. Annotations
Annotations are metadata added to Java code.
Examples: @Override, @Deprecated, @SuppressWarnings.
Example
class Parent {
void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
@Override
void display() { // ensures overriding
System.out.println("Child display");
}
}
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 33
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
public class AnnotationDemo
{
public static void main(String[] args)
{
Child c = new Child();
c.display();
}
}
Output:
Child display
Generics
Java Generics are a powerful feature that allows you to write type-safe, reusable, and
flexible code. Let’s break it down in a way that’s both practical and classroom-friendly
What Are Java Generics?
Generics let you define classes, interfaces, and methods with type parameters.
Instead of hardcoding types like int, String, or Object, you use placeholders like <T>,
<E>, or <K, V>.
Why Use Generics?
Type Safety: Errors caught at compile time, not runtime
Code Reusability: One class/method works with many types
Cleaner Code: No need for casting
Example: Generic Class
class Box<T> {
private T value;
public void set(T value) { this.value = value; }
public T get() { return value; }
}
public class GenericDemo
{
public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
intBox.set(100);
System.out.println("Integer Value: " + intBox.get());
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 34
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-3
Box<String> strBox = new Box<>();
strBox.set("Hello SSIT");
System.out.println("String Value: " + strBox.get());
}
}
Output:
Integer Value: 100
String Value: Hello SSIT
Common Generic Types
Placeholder Meaning
<T> Type (general)
<E> Element (used in collections)
<K, V> Key and Value (used in maps)
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 35