UNIT-4
Exception handling: Types of Java exception – checked and
unchecked exceptions; Usage of try-catch-finally blocks.
Multithreading: comparison of multithreading and multitasking; Life
cycle of a thread; two ways of creating thread – by extending the
Thread class and by implementing the Runnable Interface, Thread
synchronization. Advanced concepts: Collections in Java;
Introduction to JavaBeans and Java security manager, Importance of
generic programming in java with examples.
Exception Handling in Java
The process of converting system error messages into user friendly error
message is known as Exception handling. This is one of the powerful feature
of Java to handle run time error and maintain normal flow of java application.
Exception
It is an event, which occurs during the execution of a program, that disrupts
the normal flow of the program's Instructions.
Why use Exception Handling
Handling the exception is nothing but converting system error generated
message into user friendly error message. Whenever an exception occurs in
the java application, JVM will create an object of appropriate exception of sub
class and generates system error message, these system generated
messages are not understandable by user so need to convert it into user
friendly error message. You can convert system error message into user
friendly error message by using exception handling feature of java.
For Example: when you divide any number by zero then system generate /
by zero so this is not understandable by user so you can convert this
message into user friendly error message like Don't enter zero for
denominator.
Hierarchy of Exception classes
Type of Exception
Checked Exception
Un-Checked Exception
Checked Exception
Checked Exception are the exception which checked at compile-time. These
exception are directly sub-class of [Link] class.
Only for remember: Checked means checked by compiler so checked
exception are checked at compile-time.
Un-Checked Exception
Un-Checked Exception are the exception both identifies or raised at run time.
These exception are directly sub-class of [Link] class.
Note: In real time application mostly we can handle un-checked exception.
Only for remember: Un-checked means not checked by compiler so un-
checked exception are checked at run-time not compile time.
Difference between checked Exception and un-checked Exception
Checked Exception Un-Checked Exception
checked Exception are checked un-checked Exception are checked at
1
at compile time run time
3 e.g. e.g.
FileNotFoundException, ArithmeticException,
NumberNotFoundException NullPointerException,
etc. ArrayIndexOutOfBoundsException etc.
Difference between Error and Exception
Error Exception
1 Can't be handle. Can be handle.
Example: Example:
2 NoSuchMethodError ClassNotFoundException
OutOfMemoryError NumberFormateException
Handling the Exception
Handling the exception is nothing but converting system error generated
message into user friendly error message in others word whenever an
exception occurs in the java application, JVM will create an object of
appropriate exception of sub class and generates system error message,
these system generated messages are not understandable by user so need
to convert it into user-friendly error message. You can convert system error
message into user-friendly error message by using exception handling
feature of java.
Use Five keywords for Handling the Exception
try
catch
finally
throws
throw
Syntax for handling the exception
Syntax
try
{
// statements causes problem at run time
catch(type of exception-1 object-1)
// statements provides user friendly error message
catch(type of exception-2 object-2)
// statements provides user friendly error message
finally
// statements which will execute compulsory
Example without Exception Handling
Syntax
class ExceptionDemo
public static void main(String[] args)
int a=10, ans=0;
ans=a/0;
[Link]("Denominator not be zero");
}
Abnormally terminate program and give a message like below, this error
message is not understandable by user so we convert this error message
into user friendly error message, like "denominator not be zero".
Example of Exception Handling
Example
class ExceptionDemo
public static void main(String[] args)
int a=10, ans=0;
try
ans=a/0;
catch (Exception e)
[Link]("Denominator not be zero");
Output
Denominator not be zero
try and catch block
try block
Inside try block we write the block of statements which causes executions
at run time in other words try block always contains problematic statements.
Important points about try block
If any exception occurs in try block then CPU controls comes out to the
try block and executes appropriate catch block.
After executing appropriate catch block, even through we use run time
statement, CPU control never goes to try block to execute the rest of
the statements.
Each and every try block must be immediately followed by catch block
that is no intermediate statements are allowed between try and catch
block.
Syntax
try
.....
/* Here no other statements are allowed
between try and catch block */
catch()
....
Each and every try block must contains at least one catch block. But it
is highly recommended to write multiple catch blocks for generating
multiple user friendly error messages.
One try block can contains another try block that is nested or inner try
block can be possible.
Syntax
try
.......
try
.......
catch block
Inside catch block we write the block of statements which will generates
user friendly error messages.
catch block important points
Catch block will execute exception occurs in try block.
You can write multiple catch blocks for generating multiple user
friendly error messages to make your application strong. You can see
below example.
At a time only one catch block will execute out of multiple catch blocks.
in catch block you declare an object of sub class and it will be
internally referenced by JVM.
Example without Exception Handling
Example
class ExceptionDemo
public static void main(String[] args)
{
int a=10, ans=0;
ans=a/0;
[Link]("Denominator not be zero");
Abnormally terminate program and give a message like below, this error
message is not understandable by user so we convert this error message
into user friendly error message, like "denominator not be zero".
Example of Exception Handling
Example
class ExceptionDemo
public static void main(String[] args)
int a=10, ans=0;
try
ans=a/0;
catch (Exception e)
[Link]("Denominator not be zero");
}
Output
Denominator not be zero
Multiple catch block
You can write multiple catch blocks for generating multiple user friendly error
messages to make your application strong. You can see below example.
Example
import [Link].*;
class ExceptionDemo
public static void main(String[] args)
int a, b, ans=0;
Scanner s=new Scanner([Link]);
[Link]("Enter any two numbers: ");
try
a=[Link]();
b=[Link]();
ans=a/b;
[Link]("Result: "+ans);
catch(ArithmeticException ae)
[Link]("Denominator not be zero");
}
catch(Exception e)
[Link]("Enter valid number");
finally Block in Exception Handling
Inside finallyblock we write the block of statements which will relinquish
(released or close or terminate) the resource (file or database) where data
store permanently.
finally block important points
Finally block will execute compulsory
Writing finally block is optional.
You can write finally block for the entire java program
In some of the circumstances one can also write try and catch block in
finally block.
Discover more
Education
education
Educational Resources
Example
class ExceptionDemo
public static void main(String[] args)
{
int a=10, ans=0;
try
ans=a/0;
catch (Exception e)
[Link]("Denominator not be zero");
finally
[Link]("I am from finally block");
Output
Denominator not be zero
I am from finally block
Exception Classes in Java
Exception are mainly classified into two type checked exception and un-
checked exception.
Checked Exception Classes
FileNotFoundException
ClassNotFoundException
IOException
InterruptedException
Un-Checked Exception Classes
ArithmeticException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
NumberFormateException
NullPointerException
NoSuchMethodException
NoSuchFieldException
FileNotFoundException
If the given filename is not available in a specific location ( in file handling
concept) then FileNotFoundException will be raised. This exception will be
thrown by the FileInputStream, FileOutputStream, and RandomAccessFile
constructors.
ClassNotFoundException
If the given class name is not existing at the time of compilation or running
of program then ClassNotFoundException will be raised. In other words this
exception is occured when an application tries to load a class but no
definition for the specified class name could be found.
IOException
This is exception is raised whenever problem occurred while writing and
reading the data in the file. This exception is occurred due to following
reason;
When try to transfer more data but less data are present.
When try to read data which is corrupted.
When try to write on file but file is read only.
InterruptedException
This exception is raised whenever one thread is disturb the other thread. In
other words this exception is thrown when a thread is waiting, sleeping, or
otherwise occupied, and the thread is interrupted, either before or during the
activity.
ArithmeticException
This exception is raised because of problem in arithmetic operation like
divide by zero. In other words this exception is thrown when an exceptional
arithmetic condition has occurred. For example, an integer "divide by zero".
Example
class ExceptionDemo
public static void main(String[] args)
int a=10, ans=0;
try
ans=a/0;
catch (Exception e)
[Link]("Denominator not be zero");
ArrayIndexOutOfBoundsException
This exception will be raised whenever given index value of an array is out of
range. The index is either negative or greater than or equal to the size of the
array.
Example
int a[]=new int[5];
a[10]=100; //ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
This exception will be raised whenever given index value of string is out of
range. The index is either negative or greater than or equal to the size of the
array.
Example
String s="Hello";
[Link](3);
[Link](10); // Exception raised
chatAt() is a predefined method of string class used to get the individual
characters based on index value.
NullPointerException
A NullPointerException is thrown when an application is trying to use or
access an object whose reference equals to null.
Example
String s=null;
[Link]([Link]());//NullPointerException
Difference Between Throw and Throws Keyword
throw
throw is a keyword in java language which is used to throw any user defined
exception to the same signature of method in which the exception is raised.
Note: throw keyword always should exist within method body.
whenever method body contain throw keyword than the call method should
be followed by throws keyword.
Syntax
class className
returntype method(...) throws Exception_class
throw(Exception obj)
throws
throws is a keyword in java language which is used to throw the exception
which is raised in the called method to it's calling method throws keyword
always followed by method signature.
Example
returnType methodName(parameter)throws Exception_class....
.....
Difference between throw and throws
throw Throws
throws is a keyword which gives
an indication to the specific
throw is a keyword used for
method to place the common
hitting and generating the
1 exception methods as a part of
exception which are occurring
try and catch block for
as a part of method body
generating user friendly error
messages
The place of using throw The place of using throws is a
2 keyword is always as a part of keyword is always as a part of
method body. method heading
When we use throw keyword as When we write throws keyword
a part of method body, it is as a part of method heading, it
mandatory to the java is optional to the java
3
programmer to write throws programmer to write throw
keyword as a part of method keyword as a part of method
heading body.
Multithreading in Java
Multithreading in Java is a feature that enables a program to run multiple
threads simultaneously, allowing tasks to execute in parallel and utilize the
CPU more efficiently. A thread is a lightweight, independent unit of execution
inside a program (process).
Threads allow parallel execution of tasks.
A process can have multiple threads.
Each thread runs independently but shares the same memory.
Example: Imagine a restaurant kitchen. Multiple chefs (threads) are
preparing different dishes at the same time. This speeds up service and
utilizes all available resources (CPU).
Different Ways to Create Threads
Threads can be created by using two mechanisms:
1. Extending the Thread class
We create a class that extends Thread and override its run() method to
define the task. Then, we make an object of this class and call start(), which
automatically calls run() and begins the thread’s execution.
Example: Restaurant Kitchen (Extending Thread)
class CookingTask extends Thread {
private String task;
CookingTask(String task) {
[Link] = task;
public void run() {
[Link](task + " is being prepared by " +
[Link]().getName());
public class Restaurant {
public static void main(String[] args) {
Thread t1 = new CookingTask("Pasta");
Thread t2 = new CookingTask("Salad");
Thread t3 = new CookingTask("Dessert");
Thread t4 = new CookingTask("Rice");
[Link]();
[Link]();
[Link]();
[Link]();
Note: The order of thread execution may vary on each run because thread
scheduling is non-deterministic.
Output
Rice is being prepared by Thread-3
Pasta is being prepared by Thread-0
Dessert is being prepared by Thread-2
Salad is being prepared by Thread-1
Explanation:
We created multiple threads (t1–t4) using the CookingTask class.
Each thread represents a dish being prepared.
Calling start() creates a new thread with its own call stack and
internally invokes the run() method. This allows threads to run
concurrently with the main thread and each other.
2. Implementing the Runnable Interface
We create a new class which implements [Link] interface and
define the run() method there. Then we instantiate a Thread object and call
start() method on this object.
Example: Restaurant Kitchen (Runnable Interface)
class CookingJob implements Runnable {
private String task;
CookingJob(String task) {
[Link] = task;
}
public void run() {
[Link](task + " is being prepared by " +
[Link]().getName());
public class RestaurantRunnable {
public static void main(String[] args) {
Thread t1 = new Thread(new CookingJob("Soup"));
Thread t2 = new Thread(new CookingJob("Pizza"));
Thread t3 = new Thread(new CookingJob("Burger"));
[Link]();
[Link]();
[Link]();
Note: The order of thread execution may vary on each run because thread
scheduling is non-deterministic.
Output
Burger is being prepared by Thread-2
Pizza is being prepared by Thread-1
Soup is being prepared by Thread-0
Explanation:
Cookingob implements Runnable and overrides run().
We pass a Runnable object to the Thread constructor.
Calling start() creates a new thread with its own call stack and
internally invokes the run() method. This allows threads to run
concurrently with the main thread and each other.
Best Use Cases for Thread and Runnable
Use extends Thread: if your class does not extend any other class.
Use implements Runnable: if your class already extends another
class (preferred because Java doesn’t support multiple inheritance).
Advantages of Multithreading in Java
Improved Performance: Multiple tasks can run simultaneously,
reducing execution time.
Efficient CPU Utilization: Threads keep the CPU busy by running
tasks in parallel.
Responsiveness: Applications (like GUIs) remain responsive while
performing background tasks.
Resource Sharing: Threads within the same process share memory
and resources, avoiding duplication.
Better User Experience: Smooth execution of tasks like file
downloads, animations, and real-time updates.
Difference Between Multi-Tasking and Multi-Threading
Multi-tasking and multi-threading are core concepts in modern
operating systems that enhance efficiency and performance.
If we discuss in simpler terms, the main difference between multi-
tasking and multi-threading is that multi-tasking involves
running multiple independent processes or tasks, while
multi-threading involves dividing a single process into
multiple threads that can execute concurrently. Multi-tasking
is used to manage multiple processes, while multi-threading is used
to improve the performance of a single process.
Multitasking Multithreading
In multitasking, users are allowed While in multithreading, many
Multitasking Multithreading
threads are created from a
to perform many tasks by CPU. process through which computer
power is increased.
While in multithreading also,
Multitasking involves often
CPU switching is often involved
CPU switching between the tasks.
between the threads.
While in multithreading,
In multitasking, the processes
processes are allocated the
share separate memory.
same memory.
While the multithreading
The multitasking component
component does not involve
involves multiprocessing.
multiprocessing.
While in multithreading also, a
In multitasking, the CPU is provided
CPU is provided in order to
in order to execute many tasks at a
execute many threads from a
time.
process at a time.
In multitasking, processes don't
While in multithreading, each
share the same resources, each
process shares the same
process is allocated separate
resources.
resources.
Multitasking is slow compared to
While multithreading is faster.
multithreading.
Multitasking Multithreading
While in multithreading,
In multitasking, termination of a
termination of thread takes less
process takes more time.
time.
Isolation and memory protection Isolation and memory protection
exist in multitasking. does not exist in multithreading.
It helps in developing efficient It helps in developing efficient
programs. operating systems.
Involves dividing a single
Involves running multiple process into multiple threads
independent processes or tasks that can execute concurrently
Multiple threads within a single
Multiple processes or tasks run
process share the same memory
simultaneously, sharing the same
space and resources
processor and resources
Threads share the same memory
Each process or task has its own space and resources of the
memory space and resources parent process
Used to manage multiple
Used to manage multiple processes
processes and improve system
and improve system efficiency
efficiency
Multitasking Multithreading
Examples: splitting a video
Examples: running multiple
encoding task into multiple
applications on a computer,
threads, implementing a
running multiple servers on a
responsive user interface in an
network
application
Life Cycle of a Thread
Threads, the smallest unit of a process, follow a structured progression called
the lifecycle and states of a thread in Java. This lifecycle includes six main
states that a thread can occupy at any point in time:
1. New
A thread is in this state when you've created an instance of the Thread class
but haven't invoked the start() method yet. It remains in this state until the
program starts the thread.
2. Active
This state consists of two sub-states, Runnable and Running. Runnable
implies that the thread is ready for execution and is waiting for resource
allocation by the thread scheduler. Running means the thread scheduler has
selected the thread and is currently executing its run() method.
3. Blocked / Waiting
A thread enters this state when it is temporarily inactive and waiting for a
signal to proceed due to reasons like waiting for a resource to become
available (Blocked) or waiting for another thread to perform a specific action
(Waiting).
4. Timed Waiting
In this state, a thread is waiting for a specified period. A thread might enter
this state through methods like [Link](long millis) or [Link](long
timeout) where it waits for a particular duration before resuming its
activities.
5. Terminated
This is the final state in the thread life cycle. The thread arrives here when it
has completed its execution, i.e., its run() method has been completed, or it
has been abruptly terminated due to an unhandled exception. Once in this
state, the thread cannot be resumed.
Here, We Explain the Life Cycle of Thread In Java with Diagram
Thread Synchronization
When we start two or more threads within a program, there may be a
situation when multiple threads try to access the same resource and finally
they can produce unforeseen result due to concurrency issues. For example,
if multiple threads try to write within a same file then they may corrupt the
data because one of the threads can override data or while one thread is
opening the same file at the same time another thread might be closing the
same file.
So there is a need to synchronize the action of multiple threads and make
sure that only one thread can access the resource at a given point in time.
This is implemented using a concept called monitors. Each object in Java is
associated with a monitor, which a thread can lock or unlock. Only one
thread at a time may hold a lock on a monitor.
Thread Synchronization in Java
Java programming language provides a very handy way of creating threads
and synchronizing their task by using synchronized blocks. You keep shared
resources within this block. Following is the general form of the synchronized
statement
Synchronized block
Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
Here, the objectidentifier is a reference to an object whose lock associates
with the monitor that the synchronized statement represents. Now we are
going to see two examples, where we will print a counter using two different
threads. When threads are not synchronized, they print counter value which
is not in sequence, but when we print counter by putting inside
synchronized() block, then it prints counter very much in sequence for both
the threads.
Synchronized Method
To use a synchronized method in Java, you simply add the synchronized
keyword to the method's declaration signature. This ensures that only one
thread can execute that method at a time on a given object instance,
preventing data inconsistency and race conditions. [
How Synchronized Methods Work
When a thread calls an instance synchronized method, it automatically
acquires the intrinsic lock (or monitor lock) of that specific object instance.
Other threads trying to invoke any synchronized method on the same object
will block and wait until the first thread finishes executing and releases the
lock. [1, 2, 3, 4]
Code Example: Ticket Booking System
class TicketBookingApp {
private int availableSeats = 10;
// The 'synchronized' keyword locks this instance method
public synchronized void bookSeat(int seats, String
customerName)
if (availableSeats >= seats) {
[Link](customerName + " successfully booked " + seats
+ " seats.");
availableSeats -= seats;
[Link]("Seats remaining: " + availableSeats);
}}
The Java Collections Framework
The Java Collections Framework provides a set of interfaces (like List, Set,
and Map) and a set of classes (ArrayList, HashSet, HashMap, etc.) that
implement those interfaces.
All of these are part of the [Link] package.
They are used to store, search, sort, and organize data more easily - all using
standardized methods and patterns.
Core Interfaces in the Collections Framework
Here are some common interfaces, along with their classes:
Interface Common Classes Description
List ArrayList, LinkedList Ordered collection that
allows duplicates
Set HashSet, TreeSet, LinkedHashSet Collection of unique
elements
Map HashMap, TreeMap, LinkedHashMap Stores key-value pairs
with unique keys
Overview of Classes
The table below gives an overview of the common data structure classes and
their characteristics:
Interface Class Description
List ArrayList Resizable array that maintains order and
allows duplicates
LinkedList List with fast insert and remove operations
Set HashSet Unordered collection of unique elements
TreeSet Sorted set of unique elements (natural
order)
LinkedHashSet Maintains the order in which elements
were inserted
Map HashMap Stores key/value pairs with no specific
order
TreeMap Sorted map based on the natural order of
keys
LinkedHashMap Maintains the order in which keys were
inserted
Use List classes when you care about order, you may have duplicates,
and want to access elements by index.
Use Set classes when you need to store unique values only.
Use Map classes when you need to store pairs of keys and values, like
a name and its phone number.
Java Security Manager
The Java Security Manager is a built-in Java security feature that enforces
permissions at runtime. In plain terms, it acts like a gatekeeper between Java
code and sensitive operations such as file access, network connections,
property reads, class loading, and process execution.
When code tries to do something restricted, the Security Manager checks
whether that action is allowed under the current security policy. If the code
does not have permission, the JVM throws a security exception and blocks
the action. That is the core model behind java security manager behavior.
This is especially useful when you need to distinguish trusted
code from untrusted code. Trusted code might be your core service layer.
Untrusted code might be a plugin, a script, or a module from a third party. In
a hardened design, both can run inside the same JVM, but they do not
receive the same privileges.
File system control: prevent reading sensitive configuration or
writing outside approved directories.
Network control: limit which hosts or ports code can contact.
System property control: stop code from reading environment
details it should not see.
Runtime control: block operations such as classloader changes or
process execution.
Historically, this was a major part of Java application security and defensive
programming. Oracle’s official Java documentation on security and the Java
platform’s permission model explains the original intent: enforce policy-
based boundaries inside the runtime rather than assuming every class in the
JVM deserves the same level of trust. For developers who work with legacy
systems, that history still matters.
How Java Security Manager Works
The Java Security Manager works through runtime enforcement. That
means permission checks happen when code attempts a restricted action,
not only when the application starts. If a class tries to open a file, connect to
a server, or read a protected property, the JVM evaluates the request
immediately.
Here is the basic flow. The code makes a request. The JVM consults the active
security policy. The Security Manager evaluates the code source, the granted
permissions, and the context of the request. If the request fits the policy,
execution continues. If not, the JVM denies the action and raises
a SecurityException or a related access error.
1. The application or library calls a sensitive API.
2. The JVM intercepts the operation through a permission check.
3. The Security Manager compares the request against policy rules.
4. The request is allowed or blocked based on the granted permissions.
This matters because runtime checks defend against both accidental misuse
and malicious behavior. A buggy library might try to write to the wrong
directory. A compromised plugin might attempt outbound connections or
read secret values. In both cases, the Security Manager can stop the action
before damage spreads.
Key Benefits of Using Java Security Manager
The biggest benefit of the Java Security Manager is stronger runtime
containment. If a component is buggy or compromised, its damage is
limited by the permissions it was granted. That is particularly valuable in
systems that load third-party code or support plugins.
It also supports custom security design. Different modules can live in the
same JVM but still operate under different rules. That is useful when one part
of the system handles internal data while another interacts with external
users or partner systems.
Reduced data exposure: sensitive files and properties stay out of
reach unless explicitly allowed.
Smaller attack surface: code cannot use functions it does not need.
Better isolation: one module’s compromise does not automatically
expose the whole process.
Audit-friendly policy: security rules are explicit and reviewable.
Architecture alignment: trust boundaries can be represented in
code and policy.
INTRODUCTION TO JAVA BEANS
INTRODUCTION TO JAVA BEANS
Software components are self-contained software units developed according
to the motto “Developed them once, run and reused them everywhere”. Or
in other words, reusability is the main concern behind the component model.
A software component is a reusable object that can be plugged into any
target software application. You can develop software components using
various programming languages, such as C, C++, Java, and Visual Basic. A
“Bean” is a reusable software component model based on sun’s java bean
specification that can be manipulated visually in a builder tool. The term
software component model describes how to create and use reusable
software components to build an application Builder tool is nothing but an
application development tool which lets you both to create new beans or use
existing beans to create an application. To enrich the software systems by
adopting component technology JAVA came up with the concept called Java
Beans. Java provides the facility of creating some user defined components
by means of Bean programming. We create simple components using java
beans. We can directly embed these beans into the software.
Advantages of Java Beans:
The java beans posses the property of “Write once and run anywhere”.
Beans can work in different local platforms.
Beans have the capability of capturing the events sent by other
objects and vice versa enabling object communication.
The properties, events and methods of the bean can be controlled by
the application developer.(ex. Add new properties)
Beans can be configured with the help of auxiliary software during
design time.(no hassle at runtime)
The configuration setting can be made persistent.(reused)
Configuration setting of a bean can be saved in persistent storage and
restored later. What can we do/create by using JavaBean: There is no
restriction on the capability of a Bean.
It may perform a simple function, such as checking the spelling of a
document, or a complex function, such as forecasting the performance
of a stock portfolio. A Bean may be visible to an end user. One
example of this is a button on a graphical user interface.
Software to generate a pie chart from a set of data points is an
example of a Bean that can execute locally.
Bean that provides real-time price information from a stock or
commodities exchange.
Features of a JavaBean Support for “introspection” so that a builder
tool can analyze how a bean works. Support for “customization” to
allow the customisation of the appearance and behaviour of a bean.
Support for “events” as a simple communication metaphor than can
be used to connect up beans. Support for “properties”, both for
customization and for programmatic use. Support for “persistence”,
so that a bean can save and restore its customized state.