Java Packages, Applets, Threads & Exceptions
Java Packages, Applets, Threads & Exceptions
Import statement:
Introduction & implementation of import statement. Applets: Introduction to Applets & Application, how applets
application are different creating An applet. Applets life cycle, designing a web page, creating an executable applet,
running the applet, applet tags, passing a parameter to an applet, HTML tag, Converting applet to application.
Threads: Overview of threads, single & multiple threads, lift cycle of threads, stopping & blocking threads, working
with threads, priority to thread, synchronization. Exceptions & Errors: Introduction, types of error, exception, syntax
of exception, handling techniques, exception for Debugging.
Java package is a mechanism of grouping similar type of classes, interfaces, and sub-classes collectively based
on functionality. When software is written in the Java programming language, it can be composed of hundreds or
even thousands of individual classes. It makes sense to keep things organized by placing related classes and
interfaces into packages.
o Re-usability: The classes contained in the packages of another program can be easily reused
o Name Conflicts: Packages help us to uniquely identify a class, for example, we can
have [Link] and [Link] classes
o Controlled Access: Offers access protection such as protected classes, default classes and private
class
o Data Encapsulation: They provide a way to hide classes, preventing other programs from accessing
classes that are meant for internal use only
o Maintainance: With packages, you can organize your project better and easily locate related classes
Based on whether the package is defined by the user or not, packages are divided into two categories:
1. Built-in Packages
Built-in Packages
Built-in packages or predefined packages are those that come along as a part of JDK (Java Development Kit)
to simplify the task of Java programmer. They consist of a huge number of predefined classes and interfaces that are
a part of Java API’s. Some of the commonly used built-in packages are [Link], [Link], [Link], [Link], etc.
Here’s a simple program using a built-in package.
1 package Edureka;
2 import [Link];
4 class BuiltInPackage {
7
8 ArrayList<Integer> myList = new ArrayList<>(3);
10 [Link](3);
11 [Link](2);
12 [Link](1);
13
15 }
16 }
Output:
The ArrayList class belongs to [Link] package. To use it, we have to import the package using the import
statement. The first line of the code import [Link] imports the [Link] package and uses ArrayList
class which is present in the sub package util.
User-defined packages are those which are developed by users in order to group related classes, interfaces
and sub packages. With the help of an example program, let’s see how to create packages, compile Java programs
inside the packages and execute them.
Creating a package in Java is a very easy task. Choose a name for the package and include
a package command as the first statement in the Java source file. The java source file can contain the classes,
interfaces, enumerations, and annotation types that you want to include in the package. For example, the following
statement creates a package named MyPackage.
1 package MyPackage;
The package statement simply specifies to which package the classes defined belongs to..
Note: If you omit the package statement, the class names are put into the default package, which has no
name. Though the default package is fine for short programs, it is inadequate for real applications.
To create a class inside a package, you should declare the package name as the first statement of your
program. Then include the class as part of the package. But, remember that, a class can have only one package
declaration. Here’s a simple program to understand the concept.
1 package MyPackage;
6 Compare(int n, int m) {
7 num1 = n;
8 num2 = m;
9 }
13 }
14 else {
16 }
17 }
18
19
22
25
27 {
28 current[i].getmax();
29 }
30 }
31 }
Output:
As you can see, I have declared a package named MyPackage and created a class Compare inside that
package. Java uses file system directories to store packages. So, this program would be saved in a file
as [Link] and will be stored in the directory named MyPackage. When the file gets compiled, Java will create
a .class file and store it in the same directory. Remember that name of the package must be same as the directory
under which this file is saved.
You might be wondering how to use this Compare class from a class in another package?
1 package Edureka;
2 import [Link];
8 if(n != m) {
9 [Link]();
10 }
11 else {
13 }
14 }
15 }
Output:
I have first declared the package Edureka, then imported the class Compare from the package MyPackage.
So, the order when we are creating a class inside a package while importing another package is,
• Package Declaration
• Package Import
Well, if you do not want to use the import statement, there is another alternative to access a class file of the
package from another package. You can just use fully qualified name while importing a class.
Here’s an example to understand the concept. I am going to use the same package that I have declared
earlier in the blog, MyPackage.
1 package Edureka;
8 [Link]();
9 }
10 else {
12 }
13 }
14 }
Output:
In the Demo class, instead of importing the package, I have used the fully qualified name such
as [Link] to create the object of it. Since we are talking about importing packages, you might as well
check out the concept of static import in Java.
Static import feature was introduced in Java from version 5. It facilitates the Java programmer to access any
static member of a class directly without using the fully qualified name.
1 package MyPackage;
10 }
11 }
Output:
Though using static import involves less coding, overusing it might make program unreadable and
unmaintainable. Now let’s move on to the next topic, access control in packages.
You might be aware of various aspects of Java’s access control mechanism and its access specifiers. Packages
in Java add another dimension to access control. Both classes and packages are a means of data encapsulation. While
packages act as containers for classes and other subordinate packages, classes act as containers for data and code.
Because of this interplay between packages and classes, Java packages addresses four categories of visibility for class
members:
• Sub-classes in the same package
The table below gives a real picture of which type access is possible and which is not when using packages in
Java:
Same Package
No Yes Yes Yes
Subclasses
Same Package
No Yes Yes Yes
Non-Subclasses
Different
No No Yes Yes
Packages Subclasses
Different
Packages Non- No No No Yes
Subclasses
3. If access specifier is not mentioned, an element is visible to subclasses as well as to other classes in the same
package
4. Lastly, anything declared protected element can be seen outside your current package, but only to classes
that subclass your class directly
This way, Java packages provide access control to the classes. Well, this wraps up the concept of packages in
Java. Here are some points that you should keep in mind when using packages in Java.
Points to Remember
• Every class is part of some package. If you omit the package statement, the class names are put into the
default package
• A class can have only one package statement but it can have more than one import package statements
• The name of the package must be the same as the directory under which the file is saved
• When importing another package, package declaration must be the first statement, followed by package
import
Applets:
Java Applets was once a very popular feature of web applications. Java Applets were small programs
written in Java that ran inside a web browser. Learning about Applet helps us understand how Java has
evolved and how it handles graphics.
Note: [Link] package has been deprecated in Java 9 and later versions, as applets are no longer widely
used on the web.
Java Applets
A Java Applet is a Java program that runs inside a web browser. An Applet is embedded in an HTML file
using <applet> or <objects> tags. Applets are used to make the website more dynamic and entertaining.
Applets are executed in a sandbox for security, restricting access to local system resources.
Key Points:
• Applet Basics: Every applet is a child/subclass of the [Link] class.
• Not Standalone: Applets don’t run on their own like regular Java programs. They need a web
browser or a special tool called the applet viewer (which comes with Java).
• No main() Method: Applets don't start with main() method.
• Display Output: Applets don't use [Link]() for displaying the output, instead they use
graphics methods like drawString() from the AWT (Abstract Window ToolKit).
Java Applet Life Cycle
The below diagram demonstrates the life cycle of Java Applet:
It is important to understand the order in which the various methods shown in the above image are called.
• When an applet begins, the following methods are called, in this sequence:
o init( )
o start( )
o paint( )
• When an applet is terminated, the following sequence of method calls takes place:
o stop( )
o destroy( )
Let’s look more closely at these methods.
1. init( ): The init( ) method is the first method to be called. This is where you should initialize variables. This
method is called only once during the run time of your applet.
2. start( ): The start( ) method is called after init( ). It is also called to restart an applet after it has been
stopped.
Note: init( ) is called once i.e. when the first time an applet is loaded whereas start( ) is called each time an
applet’s HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet
resumes execution at start( )
3. paint( ): The paint( ) method is called each time an AWT-based applet’s output must be redrawn. This
situation can occur for several reasons. For example, the window in which the applet is running may be
overwritten by another window and then uncovered. Or the applet window may be minimized and then
restored.
• paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet
must redraw its output, paint( ) is called.
• The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics
context, which describes the graphics environment in which the applet is running. This context is
used whenever output to the applet is required.
• paint() is the only method among all the methods mention above (which is parameterized).
This method is crucial for updating or redrawing the visual content of the applet.
Example:
public void paint(Graphics g)
{
// Drawing a string on the applet window
// g is an object reference of class Graphic.
[Link]("Hello, Applet!", 50, 50);
}
Now the below Question Arises:
In the prototype of paint() method, we have created an object reference without creating its object. But
how is it possible to create object reference without creating its object?
Ans. Whenever we pass object reference in arguments then the object will be provided by its caller itself. In
this case the caller of paint() method is browser, so it will provide an object. The same thing happens when
we create a very basic program in normal Java programs. For Example:
public static void main(String []args) {
}
Here we have created an object reference without creating its object but it still runs because it’s caller, i.e.
JVM will provide it with an object.
4. stop( ): The stop( ) method is called when a web browser leaves the HTML document containing the
applet, when it goes to another page.
For example: When stop( ) is called, the applet is probably running. You should use stop( ) to suspend
threads that don’t need to run when the applet is not visible. You can restart them when start( ) is called if
the user returns to the page.
5. destroy( ): The destroy( ) method is called when the environment determines that your applet needs to
be removed completely from memory. At this point, you should free up any resources the applet may be
using. The stop( ) method is always called before destroy( ).
Key Packages for Java Applets
• [Link]: Base class for applets.
• [Link]: Used for drawing on the applet screen.
• [Link]: Provides GUI components and event-handling mechanisms.
Creating Hello World Applet
Let’s begin with the HelloWorld applet :
import [Link];
import [Link];
/*
<applet code="HelloWorld" width=200 height=60>
</applet>
*/
}
With this approach, first compile [Link] file and then simply run the below command to run
applet :
appletviewer HelloWorld
To prove above mentioned point,i.e paint is called again and again.
To prove this, let’s first study what is “Status Bar” in Applet?
• Status Bar”is available in the left bottom window of an applet. To use the status bar and write
something in it, we use method showStatus() whose prototype is public void showStatus(String)
• By default status bar shows “Applet Started”
• By default background color is white.
To prove paint() method is called again and again, here is the code:
Note: This code is with respect to Netbeans IDE.
Example:
//Code to illustrate paint
//method gets called again
//and again
import [Link].*;
There are some important differences between an applet and a standalone Java application, including the
following −
A main() method is not invoked on an applet, and an applet class will not define main().
When a user views an HTML page that contains an applet, the code for the applet is downloaded to the
user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate
runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes various methods during
the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of an applet is often
referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that
must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
Life Cycle of an Applet in Java
Four methods in the Applet class gives you the framework on which you build any serious applet −
• init − This method is intended for whatever initialization is needed for your applet. It is called after
the param tags inside the applet tag have been processed.
• start − This method is automatically called after the browser calls the init method. It is also called
whenever the user returns to the page containing the applet after having gone off to other pages.
• stop − This method is automatically called when the user moves off the page on which the applet
sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally. Because applets are
meant to live on an HTML page, you should not normally leave resources behind after a user leaves
the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the applet needs to repaint
itself in the browser. The paint() method is actually inherited from the [Link].
import [Link].*;
import [Link].*;
[Link]
[Link]
Without those import statements, the Java compiler would not recognize the classes Applet and Graphics,
which the applet class refers to.
• Request information about the author, version, and copyright of the applet
• Request a description of the parameters the applet recognizes
• Initialize the applet
• Destroy the applet
• Start the applet's execution
• Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those implementations may
be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.
Invoking an Applet
An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet
viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that invokes
the "Hello, World" applet −
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "[Link]" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Note − You can refer to HTML Applet Tag to understand more about calling applet from HTML.
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and height are
also required to specify the initial size of the panel in which an applet runs. The applet directive must be
closed with an </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding <param> tags between
<applet> and </applet>. The browser ignores text and other tags between the applet tags.
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that appears
between the tags, not related to the applet, is visible in non-Java-enabled browsers.
The viewer or browser looks for the compiled Java code at the location of the document. To specify
otherwise, use the codebase attribute of the <applet> tag as shown −
<applet = "[Link]"
width = "320" height = "120">
Getting Applet Parameters
• The following example demonstrates how to make an applet respond to setup parameters specified
in the document. This applet displays a checkerboard pattern of black and a second color.
• The second color and the size of each square may be specified as parameters to the applet within
the document.
• CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint()
method. However, getting the values and saving the settings once at the start of the applet, instead
of at every refresh, is convenient and efficient.
• The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init()
once, immediately after loading the applet. ([Link]() is implemented to do nothing.) Override
the default implementation to insert custom initialization code.
• The [Link]() method fetches a parameter given the parameter's name (the value of a
parameter is always a string). If the value is numeric or other non-character data, the string must be
parsed.
import [Link].*;
import [Link].*;
setBackground ([Link]);
setForeground (fg);
}
Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad input.
The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a series of
string comparisons to match the parameter value to the name of a predefined color. You need to
implement these methods to make this applet work.
Specifying Applet Parameters
The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML file specifies
both parameters to the applet by means of the <param> tag.
Example
<html>
<title>Checkerboard Applet</title>
<hr>
<applet code = "[Link]" width = "480" height = "320">
<param name = "color" value = "blue">
<param name = "squaresize" value = "30">
</applet>
<hr>
</html>
Note − Parameter names are not case sensitive.
1. Make an HTML page with the appropriate tag to load the applet code.
2. Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot be
loaded.
3. Eliminate the main method in the application. Do not construct a frame window for the application.
Your application will be displayed inside the browser.
4. Move any initialization code from the frame window constructor to the init method of the applet.
You don't need to explicitly construct the applet object. The browser instantiates it for you and calls
the init method.
5. Remove the call to setSize; for applets, sizing is done with the width and height parameters in the
HTML file.
6. Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the
browser exits.
7. If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars. (You
can, of course, title the web page itself, using the HTML title tag.)
8. Don't call setVisible(true). The applet is displayed automatically.
The difference between Application and Applet:
Parameters Java Application Java Applet
Definition Applications are just like a Java program Applets are small Java programs that are designed
that can be executed independently to be included with the HTML web document. They
without using the web browser. require a Java-enabled web browser for execution.
main () method The application program requires a The applet does not require the main() method for
main() method for its execution. its execution instead init() method is required.
Compilation The "javac" command is used to compile Applet programs are compiled with the "javac"
application programs, which are then command and run using either the "appletviewer"
executed using the "java" command. command or the web browser.
File access Java application programs have full Applets don't have local disk and network access.
access to the local file system and
network.
Access level Applications can access all kinds of Applets can only access browser-specific services.
resources available on the system. They don't have access to the local system.
Installation First and foremost, the installation of a The Java applet does not need to be installed
Java application on the local computer is beforehand.
required.
Execution Applications can execute the programs Applets cannot execute programs from the local
from the local system. machine.
Program An application program is needed to An applet program is needed to perform small tasks
perform some tasks directly for the user. or part of them.
Run It cannot run on its own; it needs JRE to It cannot start on its own, but it can be executed
execute. using a Java-enabled web browser.
Read and Write It supports the reading and writing of It does not support the reading and writing of files
Operation files on the local computer. on the local computer.
Security Application can access the system's data Executed in a more restricted environment with
and resources without any security tighter security. They can only use services that are
limitations. exclusive to their browser.
Restrictions Java applications are self-contained and Applet programs cannot run on their own,
require no additional security because necessitating the maximum level of security.
they are trusted.
What is a Thread in Java?
A thread in Java is the direction or path that is taken while a program is being executed. Generally,
all the programs have at least one thread, known as the main thread, that is provided by the JVM or Java
Virtual Machine at the starting of the program’s execution. At this point, when the main thread is provided,
the main() method is invoked by the main thread.
A thread is an execution thread in a program. Multiple threads of execution can be run concurrently
by an application running on the Java Virtual Machine. The priority of each thread varies. Higher priority
threads are executed before lower priority threads.
Thread is critical in the program because it enables multiple operations to take place within a single
method. Each thread in the program often has its own program counter, stack, and local variable.
Thread in Java enables concurrent execution, dividing tasks for improved performance. It's essential
for handling operations like I/O and network communication efficiently. Understanding threads is crucial for
responsive Java applications. Enroll in a Java Course to master threading and create efficient multithreaded
programs.
Creating a Thread in Java
A thread in Java can be created in the following two ways:
• Extending [Link] class
In this case, a thread is created by a new class that extends the Thread class, creating an instance of
that class. The run() method includes the functionality that is supposed to be implemented by the Thread.
Below is an example to create a thread by extending [Link] class.
Output
Here, start() is used to create a new thread and to make it runnable. The new thread begins inside
the void run() method.
• Implementing Runnable interface
This is the easy method to create a thread among the two. In this case, a class is created to
implement the runnable interface and then the run() method.
The code for executing the Thread should always be written inside the run() method.
Here's a code to make you understand it.
Output
The start() method is used to call the void run() method. When start() is called, a new stack is given
to the thread, and run() is invoked to introduce a new thread in the program.
• Because it exits normally. This happens when the code of the thread has been entirely
executed by the program.
• Because there occurred some unusual erroneous event, like a segmentation fault or an
unhandled exception.
Thread States in Java
In Java, to get the current state of the thread, use [Link]() method to get the current state
of the thread. Java provides [Link] enum that defines the ENUM constants for the state of
a thread, as a summary of which is given below:
1. New
Thread state for a thread that has not yet started.
public static final [Link] NEW
2. Runnable
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual
machine but it may be waiting for other resources from the operating system such as a processor.
public static final [Link] RUNNABLE
3. Blocked
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting
for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after
calling [Link]().
public static final [Link] BLOCKED
4. Waiting
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following
methods:
• [Link] with no timeout
• [Link] with no timeout
• [Link]
public static final [Link] WAITING
5. Timed Waiting
Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state
due to calling one of the following methods with a specified positive waiting time:
• [Link]
• [Link] with timeout
• [Link] with timeout
• [Link]
• [Link]
public static final [Link] TIMED_WAITING
6. Terminated
Thread state for a terminated thread. The thread has completed execution.
public static final [Link] TERMINATED
Example of Demonstrating Thread States
Below is a real-world example of a ticket booking system that demonstrates different thread states:
Example:
// Java program to demonstrate thread states
// using a ticket booking scenario
class TicketBooking implements Runnable {
@Override
public void run() {
try {
// Timed waiting
[Link](200);
} catch (InterruptedException e) {
[Link]();
}
try {
@Override
public void run() {
TicketBooking booking = new TicketBooking();
Thread bookingThread = new Thread(booking);
[Link]();
[Link]("State after starting bookingThread: " + [Link]());
try {
[Link](100);
} catch (InterruptedException e) {
[Link]();
}
try {
[Link]();
[Link]("State after starting mainThread: " + [Link]());
}
}
Output:
Explanation:
• When a new thread is created, the thread is in the NEW state. When the start() method is called on
a thread, the thread scheduler moves it to the Runnable state.
• Whenever the join() method is called on a thread instance, the main thread goes to Waiting for the
booking thread to complete.
• Once the thread's run method completes, its state becomes Terminated.
Constant Description
public static int NORM_PRIORITY Sets the default priority for the Thread. (Priority: 5)
Constant Description
public static int MIN_PRIORITY Sets the Minimum Priority for the Thread. (Priority: 1)
public static int MAX_PRIORITY Sets the Maximum Priority for the Thread. (Priority: 10)
In case, we need to set Priority with a specific value(between 1-10) we will need some methods for it. Let
us discuss how to get and set the priority of a thread in Java.
• public final int getPriority(): [Link]() method returns the priority of the given
thread.
• public final void setPriority(int newPriority): [Link]() method changes the
priority of thread to the value newPriority. This method throws IllegalArgumentException if the
value of parameter newPriority goes beyond the minimum(1) and maximum(10) limit.
Example 1: Setting and Getting Thread Priorities
import [Link].*;
// run() method for the thread that is called as soon as start() is invoked for thread in main()
public void run()
{
[Link]([Link]().getName() + " is running with priority " +
[Link]().getPriority());
}
// Print and display main thread priority using getPriority() method of Thread class
[Link]("Main thread priority: "
+ [Link]().getPriority());
Output
Main thread priority: 6
t1 thread priority: 6
Explanation:
• The ThreadDemo class extends Thread and overrides the run() method to print a message.
• In main(), the main thread’s priority is explicitly set to 6.
• The main thread’s priority is printed using getPriority().
• A new thread t1 is created inside the main thread.
• Since t1 is created by the main thread, it inherits the main thread’s priority (6).
// Class
class GFG {
{
// Print statement
[Link]("MS");
int result;
result = [Link]();
// Print statement
[Link]("My Stuff");
}
}
Output
MS
My Stuff
Example 2:
Here in this example, [Link]() is used when a thread needs to wait for other threads
before starting its work. CountDown() method decreases count and wait() method blocks until count == 0.
// Java Program to illsutare Blocking methods
// Importing all input output classes
import [Link].*;
// Importing concurrent CountDownLatch class
// from [Link] package
import [Link];
// Class
class GFG {
// Class 2
// Helper class extending Thread class
// To represent threads for which the main thread waits
class Person extends Thread {
// Member variables of this class
private int delay;
private CountDownLatch latch;
Output
PERSON-1 has finished his work
PERSON-2 has finished his work
PERSON-3 has finished his work
PERSON-4 has finished his work
main has finished his work
PERSON-5 has finished his work
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).
• 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).
CookingTask(String task) {
[Link] = task;
}
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output
Salad is being prepared by Thread-1
Rice is being prepared by Thread-3
Dessert is being prepared by Thread-2
Pasta is being prepared by Thread-0
Explanation:
• We created multiple threads (t1–t4) using the CookingTask class.
• Each thread represents a dish being prepared.
• Calling start() runs them concurrently.
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;
}
[Link]();
[Link]();
[Link]();
}
}
Output
Burger is being prepared by Thread-2
Pizza is being prepared by Thread-1
Soup is being prepared by Thread-0
Explanation:
• CookingJob implements Runnable and overrides run().
• We pass a Runnable object to the Thread constructor.
• Calling start() runs them in parallel.
When to Use Which?
• 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
1. Improved Performance: Multiple tasks can run simultaneously, reducing execution time.
2. Efficient CPU Utilization: Threads keep the CPU busy by running tasks in parallel.
3. Responsiveness: Applications (like GUIs) remain responsive while performing background tasks.
4. Resource Sharing: Threads within the same process share memory and resources, avoiding
duplication.
5. Better User Experience: Smooth execution of tasks like file downloads, animations, and real-time
updates.
Output
Welcome to ScholarHat
Exception in thread
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
Built-in Exceptions
Built-in exceptions are the exceptions that are already defined in Java libraries. They are part of the Java
Exception Hierarchy and help handle common runtime errors, such as invalid input, division by zero, null
references, and array bounds violations.
There are two types of built-in exceptions in Java:
1. Checked Exception
Checked exceptions are exceptions that are checked by the compiler at compile-time. This means if your
code might throw a checked exception, Java will force you to either handle it using a try-catch block or
declare it using the throws keyword in the method signature.
2. Unchecked Exception
Unchecked exceptions are exceptions that are not checked by the compiler at compile-time. These
exceptions occur at runtime, and it's up to the programmer whether to handle them or not. They are also
called runtime exceptions because the Java Virtual Machine (JVM) detects them while the program is
running.
User-Defined Exceptions
User-defined exceptions are also known as custom exceptions derived from the Exception class from java.
lang package(Java package). The user creates these exceptions according to different situations. Such
exceptions are handled using five keywords: try, catch, throw, throws, and finally.
We'll learn how to use these keywords in the Exception Handling Keywords in Javasection below.
Errors Vs. Exceptions in Java
Errors Exceptions
Errors are of Unchecked type Exceptions can be both checked and unchecked.
Errors mainly occur during run- Only the unchecked exceptions are encountered in run-
time. time.
Keyword Description
catch specifies the code block to be executed if an exception occurs in the try block.
finally the finally block will always be executed whether an exception occurs or not
throw the "throw" keyword triggers an exception
1. try
• A try block consists of all the doubtful statements that may throw exceptions during program
execution.
• A try block cannot work alone; it must be followed by at least one catch block or a finally block.
• If an exception occurs, the control immediately transfers from the try block to the appropriate catch
block.
• The thrown exception object is caught by the catch block, which then handles the error as per the
defined statements, allowing the program to continue running smoothly.
Syntax
try
{
//Doubtful Statements.
}
2. catch
• The catch block handles the exception raised in the try block.
• The catch block or blocks follow every try block.
• The catch block catches the thrown exception as its parameter and executes the statements inside
it.
• The declared exception must be the parent class exception, the generated exception type in
the exception class hierarchy, or a user-defined exception.
Syntax
try
{
// code
}
catch(Exception e)
{
// code to handle exceptions
}
Examples IIlustrating Implementation of try-catch blocks for Java Exception Handling in Java Online
Compiler
1. single try-catch block
2.
3. class Main
4. {
5. public static void main(String[] args)
6. {
7. try
8. {
9. // code that generate exception
10. int divideByZero = 5 / 0;
11. [Link]("Rest of code in try block");
12. }
13. catch (ArithmeticException e) {
14. [Link]("ArithmeticException => " + [Link]());
15. }
16. }
}
Run Code >>
In the above code, we have put the "int divideByZero=5/0" in the try block because this statement must
not be executed if the denominator is 0. If the denominator is 0, the statements after this statement in the
try block are skipped. The catch block catches the thrown exception as its parameter and executes the
statements inside it.
Output
ArithmeticException => / by zero
17. Multiple catch Blocks
We can use multiple catch statements for different kinds of exceptions that can occur from a single block of
code in the try block.
Syntax
try {
// code to check exceptions
}
catch (exception1) {
// code to handle the exception
}
catch (exception2) {
// code to handle the exception
}
.
.
.
catch (exception n) {
// code to handle the exception
}
Example
try {
int x[] = new int[5];
x[5] = 40 / 0;
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
[Link]("Parent Exception occurs");
}
[Link]("The program ends here");
}
}
Run Code >>
Here, our program matches the type of exception that occurred in the try block with the catch statements.
If the exception that occurred matches any of the usual catch statements, that particular catch block gets
executed.
Output
Arithmetic Exception occurs
The program ends here
18. Nested try-catch
Here, we have a try-catch block inside a nested try block.
class NestingTry {
public static void main(String args[]) {
//main try-block
try {
//try-block2
try {
//try-block3
try {
int arr[] = {
10,
20,
30,
40
};
[Link](arr[10]);
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception");
[Link](" handled in try-block3");
}
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception");
[Link](" handled in try-block2");
}
} catch (ArithmeticException e3) {
[Link]("Arithmetic Exception");
[Link](" handled in main try-block");
} catch (ArrayIndexOutOfBoundsException e4) {
[Link]("ArrayIndexOutOfBoundsException");
[Link](" handled in main try-block");
} catch (Exception e5) {
[Link]("Exception");
[Link](" handled in main try-block");
}
}
}
Run Code >>
In the above code, the Array Index Out Of Bounds Exception occurred in the grandchild try-block3. Since
try-block3 is not handling this exception, the control then gets transferred to the parent try-block2. Since
try-block2 also does not handle that exception, the control gets transferred to the main try-block, where it
finds the appropriate catch block for an exception.
Output
ArrayIndexOutOfBoundsException handled in main try-block
3. finally
The finally block in Java always executes even if there are no exceptions. This is an optional block. It is used
to execute important statements such as closing statements, releasing resources, and releasing memory.
There could be one final block for every try block. This finally block executes after the try...catch block.
Syntax
try
{
//code
}
catch (ExceptionType1 e1)
{
// catch block
}
finally
{
// finally block always executes
}
Example of Java Exception Handling using finally block in Java Playground
class Main
{
public static void main(String[] args)
{
try
{
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{
[Link]("ArithmeticException => " + [Link]());
}
finally
{
[Link]("This is the finally block");
}
}
}
Run Code >>
In this Java example, trying to divide by zero results in an Arithmetic Exception that is caught and
accompanied by an error message. The "finally" block also always runs, printing "This is the finally block"
whether or not an exception was raised.
Output
ArithmeticException => / by zero
This is the finally block
final Vs. finally Vs. finalize in Java
final finally finalize
4. throw
• The throw keyword is used to explicitly throw a checked or an unchecked exception.
• The exception that is thrown needs to be of type Throwable or a subclass of Throwable.
• We can also define our own set of conditions for which we can throw an exception explicitly using
the throw keyword.
• The program's execution flow stops immediately after the throw statement is executed, and the
nearest try block is checked to see if it has a catch statement that matches the type of exception.
Syntax
class ThrowExample {
// Method to check if a number is negative
public static void checkNumber(int number) {
if (number < 0) {
// Throwing an IllegalArgumentException if the number is negative
throw new IllegalArgumentException("Number cannot be negative");
} else {
[Link]("Number is " + number);
}
}
import [Link];
Output
Caught IOException: This is an IOException
throw Vs. throws in Java
throw throws
throw is used within the method. throws is used within the method signature
We can throw only one exception at a We can declare multiple exceptions using the throws
time keyword that the method can throw
String s=null;
[Link]([Link]());//NullPointerException
3. NumberFormatException
If the formatting of any variable or number is mismatched, it may result in a NumberFormatException.
String s="ScholarHat";
int i=[Link](s);//NumberFormatException
4. ArrayIndexOutOfBoundsException
When an array exceeds its size, the ArrayIndexOutOfBoundsException occurs.