MODULE 3 – Java Packages,
Multithreading & Exception Handling
1. Introduction to Java Packages
💡 What is a Package?
A package in Java is a collection of related classes, interfaces, and sub-packages.
It’s used to organize code and avoid naming conflicts.
Think of packages like folders on your computer — they keep files (classes) organized and easy
to find.
Example:
└── root
└── mypack
└── [Link]
📦 Types of Packages in Java
There are two types:
1. Built-in Packages (Java API Packages)
These are predefined packages provided by Java.
2. User-defined Packages
These are created by programmers to organize custom classes.
🧩 Common Built-in Java Packages
Package Description Example Classes
[Link] Contains fundamental Math, String, System
classes essential to Java.
Automatically imported.
[Link] For Input/Output FileReader, BufferedReader,
operations (files, console, FileWriter
streams).
[Link] Utility classes like data ArrayList, HashMap, Date,
structures, dates, Scanner
collections, and Scanner.
[Link] For network operations Socket, URL,
(communication between URLConnection
computers).
[Link] Used for database Connection, Statement,
connectivity using JDBC. ResultSet
[Link] & [Link] Used for building GUI JFrame, JButton, Label,
(Graphical User Interfaces). Panel
🛠️ Importing Packages
To use a class from a package, you need to import it.
1. Import a specific class:
import [Link];
2. Import the entire package:
import [Link].*;
🧑💻 Creating User-Defined Packages
1. Create a directory structure matching the package name.
2. Use the package keyword at the top of your Java file.
3. Compile the program inside its directory.
4. Import and use it in another file.
Example:
📁 Folder structure:
mypack/
[Link]
[Link]
[Link]
package mypack;
public class MyPackageClass {
public void showMessage() {
[Link]("This is my user-defined package!");
[Link]
import [Link];
public class TestPackage {
public static void main(String[] args) {
MyPackageClass obj = new MyPackageClass();
[Link]();
✅ Output: This is my user-defined package!
🎯 Benefits of Packages
Avoid naming conflicts (same class name in different packages).
e.g., [Link] and [Link].
Easier code organization.
Improves maintainability and readability.
Access control — helps define visibility (public, protected, private).
2. Multithreading in Java
💡 What is Multithreading?
Multithreading is a Java feature that allows multiple parts of a program (called threads) to
run simultaneously.
Each thread runs independently, but shares the same memory.
Example:
Downloading a file while still being able to scroll or click buttons in an app — both tasks run in
parallel using threads.
🧠 Key Concepts
A process is a running program.
A thread is a small, lightweight sub-task of a process.
Threads share the same memory but execute independently.
⚙️ Advantages of Multithreading
1. Improved performance — multiple tasks can run at the same time.
2. Efficient CPU utilization — keeps CPU busy with parallel tasks.
3. Responsiveness — UI remains active while background tasks run.
4. Resource sharing — same memory area shared by threads.
5. Better user experience — smoother applications.
🌀 Thread Life Cycle
State Description
New Thread created but not started (Thread t =
new Thread();)
Runnable Thread ready to run or currently running
Waiting Waiting for another thread to perform an
action
Timed Waiting Waiting for a specified amount of time
Terminated Thread has finished execution or stopped
🧩 Creating Threads in Java
There are two ways:
1. By Extending the Thread class
class MyThread extends Thread {
public void run() {
[Link]("Thread running...");
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link](); // starts the thread
2. By Implementing the Runnable Interface
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread running using Runnable!");
}
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
[Link]();
Note: start() method automatically calls the run() method.
🧠 Common Thread Methods
Method Description
start() Starts thread execution, calls run() method
run() Code inside it is executed by the thread
sleep(ms) Pauses the thread for given milliseconds
interrupt() Interrupts a sleeping or waiting thread
isInterrupted() Checks if thread is interrupted
currentThread() Returns the currently running thread
setName() / getName() Sets or gets thread name
setPriority() / getPriority() Sets or gets thread priority
isAlive() Checks if thread is still running
yield() Gives other threads a chance to execute
🧮 Thread Priority in Java
Thread priority tells the thread scheduler how important a thread is.
Priority range: 1 → 10
Thread.MIN_PRIORITY = 1
Thread.NORM_PRIORITY = 5 (default)
Thread.MAX_PRIORITY = 10
Example:
class PriorityThread extends Thread {
public void run() {
[Link]("Thread: " + getName());
public class ThreadPriorityDemo {
public static void main(String[] args) {
PriorityThread t1 = new PriorityThread();
PriorityThread t2 = new PriorityThread();
PriorityThread t3 = new PriorityThread();
[Link]("HighPriorityThread");
[Link]("NormalPriorityThread");
[Link]("LowPriorityThread");
[Link](Thread.MAX_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]();
[Link]();
[Link]();
}
}
3. Exceptions and Exception Handling
💡 What is an Exception?
An exception is an unexpected event or error that disrupts the normal flow of a program.
Examples:
Division by zero
Accessing a file that doesn’t exist
Invalid user input
⚙️ Types of Exceptions
1. Built-in Exceptions
Predefined in Java libraries.
Two categories:
Checked Exceptions:
Checked at compile time (e.g., IOException, SQLException).
Unchecked Exceptions:
Occur at runtime (e.g., ArithmeticException, NullPointerException).
2. User-Defined Exceptions
Created by programmers to handle custom error conditions.
class MyException extends Exception {
MyException(String msg) {
super(msg);
🧩 Methods to Display Exception Details
Method Description
printStackTrace() Prints exception type, message, and stack
trace
toString() Prints exception type and description
getMessage() Prints only exception description
🛡️ Exception Handling — try, catch, finally
Syntax:
try {
// code that may cause exception
} catch (ExceptionType e) {
// code to handle exception
} finally {
// code that always executes
Example:
class Demo {
public static void main(String[] args) {
int n = 10, m = 0;
try {
int ans = n / m;
} catch (ArithmeticException e) {
[Link]("Error: Division by zero!");
} finally {
[Link]("This block always executes.");
}
[Link]("Program continues...");
🧠 Why use Exception Handling?
Prevents program crashes.
Helps maintain normal flow.
Makes debugging easier.
Improves program stability.
Module Summary
Topic Key Concept Example
Packages Organize classes and avoid package mypack;
name conflicts
Multithreading Run multiple tasks at once extends Thread /
implements Runnable
Thread Lifecycle New → Runnable → Waiting start(), sleep()
→ Timed Waiting →
Terminated
Thread Priority Range 1–10; scheduler setPriority()
preference
Exceptions Errors handled at runtime try-catch-finally
Checked vs Unchecked Compile-time vs Runtime IOException,
ArithmeticException