0% found this document useful (0 votes)
7 views10 pages

Java Packages, Multithreading & Exceptions

Module 3 covers Java Packages, Multithreading, and Exception Handling. It explains the organization of code using packages, the concept of multithreading for concurrent task execution, and how to handle exceptions to maintain program stability. Key concepts include types of packages, thread life cycle, and methods for exception handling.

Uploaded by

shreyasharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views10 pages

Java Packages, Multithreading & Exceptions

Module 3 covers Java Packages, Multithreading, and Exception Handling. It explains the organization of code using packages, the concept of multithreading for concurrent task execution, and how to handle exceptions to maintain program stability. Key concepts include types of packages, thread life cycle, and methods for exception handling.

Uploaded by

shreyasharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

Common questions

Powered by AI

Multithreading enhances user experience by keeping the user interface responsive even while background tasks are running. This leads to smoother applications as tasks can be executed concurrently, improving performance through efficient CPU utilization and sharing of resources like memory among threads .

Extending the Thread class in Java requires inheriting from the Thread class and overriding the run() method, which might limit inheritance from other classes. In contrast, implementing the Runnable interface involves implementing the run() method in a separate class, promoting better design flexibility as the class can still extend other classes .

Java exceptions are classified into built-in and user-defined. Built-in exceptions further divide into checked exceptions, which are verified at compile time (e.g., IOException), and unchecked exceptions that occur at runtime (e.g., ArithmeticException).

Common thread methods in Java include start() (initiates thread execution), run() (contains the code to be executed), sleep(ms) (pauses the thread), interrupt() (interrupts a sleeping or waiting thread), and isAlive() (checks if a thread is still running). These methods facilitate effective thread lifecycle management and interaction .

Java's built-in packages like java.util, java.io, and java.net provide ready-made classes for common functionalities such as data structuring, input/output operations, and network communication, respectively. For example, java.util's ArrayList helps manage collections, and java.net's Socket class supports network operations, thereby streamlining application development .

In Java, a try-catch-finally block is used to handle exceptions by wrapping the risky code in a try block, catching exceptions with a catch block, and allowing a finally block to execute code that must run regardless of exceptions, ensuring program stability and preventing crashes .

User-defined exceptions in Java allow developers to create exceptions tailored to specific error conditions within their application, thereby improving error handling and making the application more robust by providing clear, bespoke error messages and specialized error resolution paths .

Thread priority in Java, ranging from 1 to 10, indicates a thread's importance to the thread scheduler. Higher priority threads may be scheduled to run before lower priority ones, potentially influencing the order of execution and responsiveness of tasks, although actual execution order may depend on the JVM .

A thread in Java goes through several states: New (created but not started), Runnable (ready and may be running), Waiting (waiting for another thread's action), Timed Waiting (waiting for a specified time), and Terminated (finished execution). Transition between these states is managed by methods like start() and interrupt().

Packages in Java prevent naming conflicts by grouping classes and interfaces into namespaces, thus allowing the same class name to be used in different packages without conflict. They also improve code organization by functioning like a directory structure (e.g., rootmypack) which enhances maintainability and readability, and provides access control by defining class visibility .

You might also like