[Go to site: main page, start]

0% found this document useful (0 votes)
18 views57 pages

Java Packages, Applets, Threads & Exceptions

Uploaded by

singhmadhvi2222
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)
18 views57 pages

Java Packages, Applets, Threads & Exceptions

Uploaded by

singhmadhvi2222
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

Packages: Java API packages, creating packages, accessing packages, adding a class to packages.

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.

What is Package in Java?

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.

Using packages while coding offers a lot of advantages like:

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

Types of Packages in Java

Based on whether the package is defined by the user or not, packages are divided into two categories:

1. Built-in Packages

2. User Defined 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 {

6 public static void main(String[] args) {

7
8 ArrayList<Integer> myList = new ArrayList<>(3);

10 [Link](3);

11 [Link](2);

12 [Link](1);

13

14 [Link]("The elements of list are: " + myList);

15 }

16 }

Output:

1 The elements of list are: [3, 2, 1]

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

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

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.

Including a Class in Java Package

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;

3 public class Compare {

4 int num1, num2;

6 Compare(int n, int m) {
7 num1 = n;

8 num2 = m;

9 }

10 public void getmax(){

11 if ( num1 > num2 ) {

12 [Link]("Maximum value of two numbers is " + num1);

13 }

14 else {

15 [Link]("Maximum value of two numbers is " + num2);

16 }

17 }

18

19

20 public static void main(String args[]) {

21 Compare current[] = new Compare[3];

22

23 current[1] = new Compare(5, 10);

24 current[2] = new Compare(123, 120);

25

26 for(int i=1; i < 3 ; i++)

27 {

28 current[i].getmax();

29 }

30 }

31 }

Output:

1 Maximum value of two numbers is 10

2 Maximum value of two numbers is 123

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?

Creating a class inside package while importing another package


Well, it’s quite simple. You just need to import it. Once it is imported, you can access it by its name. Here’s a
sample program demonstrating the concept.

1 package Edureka;

2 import [Link];

4 public class Demo{

5 public static void main(String args[]) {

6 int n=10, m=10;

7 Compare current = new Compare(n, m);

8 if(n != m) {

9 [Link]();

10 }

11 else {

12 [Link]("Both the values are same");

13 }

14 }

15 }

Output:

1 Both the values are same

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.

Programming & Frameworks Training

Using 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;

2 public class Demo{

3 public static void main(String args[]) {

4 int n=10, m=11;

5 //Using fully qualified name instead of import

6 [Link] current = new [Link](n, m);


7 if(n != m) {

8 [Link]();

9 }

10 else {

11 [Link]("Both the values are same");

12 }

13 }

14 }

Output:

1 Maximum value of two numbers is 11

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 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;

2 import static [Link].*; //static import

3 import static [Link].*;// static import

4 public class StaticImportDemo {

5 public static void main(String args[]) {

6 double val = 64.0;

7 double sqroot = sqrt(val); // Access sqrt() method directly

8 [Link]("Sq. root of " + val + " is " + sqroot);

9 //We don't need to use '[Link]

10 }

11 }

Output:

1 Sq. root of 64.0 is 8.0

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.

Access Protection in Java 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

• Non-subclasses in the same package

• Sub-classes in different packages

• Classes that are neither in the same package nor sub-classes

The table below gives a real picture of which type access is possible and which is not when using packages in
Java:

Private No Modifier Protected Public

Same Class Yes Yes Yes Yes

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

We can simplify the data in the above table as follows:

1. Anything declared public can be accessed from anywhere

2. Anything declared private can be seen only within that class

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];

// HelloWorld class extends Applet


public class HelloWorld extends Applet {

// Overriding paint() method


@Override public void paint(Graphics g)
{
[Link]("Hello World", 20, 20);
}
}
Explanation:
1. The above java program begins with two import statements. The first import statement imports the
Applet class from applet package. Every AWT-based(Abstract Window Toolkit) applet that you create
must be a subclass (either directly or indirectly) of Applet class. The second statement import
the Graphics class from AWT package.
2. The next line in the program declares the class HelloWorld. This class must be declared as public
because it will be accessed by code that is outside the program. Inside HelloWorld, paint( ) is
declared. This method is defined by the AWT and must be overridden by the applet.
3. Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method
outputs a string beginning at the specified X,Y location. It has the following general form:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is location
0,0. The call to drawString( ) in the applet causes the message "Hello World" to be displayed beginning at
location 20,20.
Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not begin
execution at main( ). In fact, most applets don’t even have a main( ) method. Instead, an applet begins
execution when the name of its class is passed to an applet viewer or to a network browser.
Running the HelloWorld Applet
After you enter the source code for [Link], compile in the same way that you have been
compiling java programs (using javac command). However, running HelloWorld with the java command will
generate an error because it is not an application.
java HelloWorld
Error: Main method not found in class HelloWorld, please define the main method as:
public static void main(String[] args)
There are two standard ways in which you can run an applet:
1. Executing the applet within a Java-compatible web browser.
2. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer executes your
applet in a window. This is generally the fastest and easiest way to test your applet.
Each of these methods is described next.
1. Using java enabled web browser
• To execute an applet in a web browser we have to write a short HTML text file that contains a tag
that loads the applet.
• We can use APPLET or OBJECT tag for this purpose
• Using APPLET, here is the HTML file that executes HelloWorld
<applet code="HelloWorld" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used by the applet. The APPLET
tag contains several other options. After you create this html file, you can use it to execute the applet.
Note: Chrome and Firefox no longer supports NPAPI (technology required for Java applets).
2. Using appletviewer
• This is the easiest way to run an applet.
• To execute HelloWorld with an applet viewer, you may also execute the HTML file shown earlier.
• For example, if the preceding HTML file is saved with [Link], then the following
command line will run HelloWorld.
appletviewer [Link]

3. appletviewer with Java Source File


If you include a comment at the head of your Java source code file that contains the APPLET tag then your
code is documented with a prototype of the necessary HTML statements, and you can run your compiled
applet merely by starting the applet viewer with your Java source code file. If you use this method, the
HelloWorld source file looks like this:
// A Hello World Applet
// Save file as [Link]
import [Link];
import [Link];

/*
<applet code="HelloWorld" width=200 height=60>
</applet>
*/

// HelloWorld class extends Applet


public class HelloWorld extends Applet
{
// Overriding paint() method
@Override
public void paint(Graphics g)
{
[Link]("Hello World", 20, 20);
}

}
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].*;

//to access showStatus()


import [Link].*;//Graphic

//class is available in this package


import [Link];

//to access Date object


public class GFG extends Applet
{
public void paint(Graphics g)
{

Date dt = new Date();


[Link]("Today is" + dt);

//in this line, super keyword is


// avoidable too.
}
}
Note: Here, we can see that if the screen is maximized or minimized we will get an updated time. This
shows that paint() is called again and again.
Features of Applets over HTML
• Displaying dynamic web pages of a web application.
• Playing sound files.
• Displaying documents
• Playing animations
Restrictions imposed on Java applets
Due to security reasons, the following restrictions are imposed on Java applets:
• An applet cannot load libraries or define native methods.
• An applet cannot ordinarily read or write files on the execution host.
• An applet cannot read certain system properties.
• An applet cannot make network connections except to the host that it came from.
• An applet cannot start any program on the host that’s executing it.

EITHER REFER OR FOR APPLETS.


APPLET:-
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application
because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application, including the
following −

An applet is a Java class that extends the [Link] class.

A main() method is not invoked on an applet, and an applet class will not define main().

Applets are designed to be embedded within an HTML page.

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].

A Simple Java Applet "Hello, World"


Following is a simple applet named [Link] −

import [Link].*;
import [Link].*;

public class HelloWorldApplet extends Applet {


public void paint (Graphics g) {
[Link] ("Hello World", 25, 50);
}
}
These import statements bring the classes into the scope of our applet class −

[Link]
[Link]
Without those import statements, the Java compiler would not recognize the classes Applet and Graphics,
which the applet class refers to.

The Applet Class


Every applet is an extension of the [Link] class. The base Applet class provides methods that a
derived Applet class may call to obtain information and services from the browser context.

These include methods that do the following −

• Get applet parameters


• Get the network location of the HTML file that contains the applet
• Get the network location of the applet class directory
• Print a status message in the browser
• Fetch an image
• Fetch an audio clip
• Play an audio clip
• Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains information
about the applet and controls the applet's execution. The viewer may −

• 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 codebase = "[Link] code = "[Link]"


width = "320" height = "120">
If an applet resides in a package other than the default, the holding package must be specified in the code
attribute using the period character (.) to separate package/class components. For example −

<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.

The following is a skeleton of [Link] −

import [Link].*;
import [Link].*;

public class CheckerApplet extends Applet {


int squareSize = 50; // initialized to default size
public void init() {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
Here are CheckerApplet's init() and private parseSquareSize() methods −

public void init () {


String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);

String colorParam = getParameter ("color");


Color fg = parseColor (colorParam);

setBackground ([Link]);
setForeground (fg);
}

private void parseSquareSize (String param) {


if (param == null) return;
try {
squareSize = [Link] (param);
} catch (Exception e) {
// Let default value remain
}
}
The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library
method [Link](), which parses a string and returns an integer. [Link]() throws an
exception whenever its argument is invalid.

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.

Application Conversion to Applets


It is easy to convert a graphical Java application (that is, an application that uses the AWT and that you can
start with the Java program launcher) into an applet that you can embed in a web page.

Following are the specific steps for converting an application to an applet.

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.

Connection Connectivity with other servers is It is unable to connect to other servers.


with servers possible.

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.

Lifecycle and States of a Thread in Java


A thread in Java can exist in any one of the following states at any given time. A thread lies only in
one of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram below represents various states of a thread at any instant:
Life Cycle of a Thread
There are multiple states of the thread in a lifecycle as mentioned below:
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet started to
run when the thread is in this state. When a thread lies in the new state, its code is yet to be run
and has not started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread
might actually be running or it might be ready to run at any instant of time. It is the responsibility of
the thread scheduler to give the thread, time to run. A multi-threaded program allocates a fixed
amount of time to each individual thread. Each and every thread get a small amount of time to run.
After running for a while, a thread pauses and gives up the CPU so that other threads can run.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock
is acquired by the other thread. The thread will move from the blocked state to runnable state
when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It
will move to the runnable state when other thread will notify or that thread will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out
parameter. A thread lies in this state until the timeout is completed or until a notification is
received. For example, when a thread calls sleep or a conditional wait, it is moved to a timed
waiting state.
6. Terminated State: A thread terminates because of either of the following reasons:

• 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]();
}

[Link]("State of bookingThread while mainThread is waiting: " +


[Link]());

try {

// Another timed waiting


[Link](100);
} catch (InterruptedException e) {
[Link]();
}
}
}

public class TicketSystem implements Runnable {


public static Thread mainThread;
public static TicketSystem ticketSystem;

@Override
public void run() {
TicketBooking booking = new TicketBooking();
Thread bookingThread = new Thread(booking);

[Link]("State after creating bookingThread: " + [Link]());

[Link]();
[Link]("State after starting bookingThread: " + [Link]());

try {
[Link](100);
} catch (InterruptedException e) {
[Link]();
}

[Link]("State after sleeping bookingThread: " + [Link]());

try {

// Moves mainThread to waiting state


[Link]();
} catch (InterruptedException e) {
[Link]();
}

[Link]("State after bookingThread finishes: " + [Link]());


}

public static void main(String[] args) {


ticketSystem = new TicketSystem();
mainThread = new Thread(ticketSystem);

[Link]("State after creating mainThread: " + [Link]());

[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.

Importance of Thread Synchronization in Java


Thread synchronization in Java is important for managing shared resources in a multithreaded
environment. It ensures that only one thread can access a shared resource at a time, which enhances the
overall system performance and prevents race conditions and data corruption.
Why is Thread Synchronization Important?
In a multithreaded environment, threads may compete for shared resources i.e. files, memory, etc. Without
synchronization, simultaneous access can lead
• Race Conditions: Multiple Threads interchanging shared data at the same time and it results an
unpredictable output.
• Data Corruption: Incomplete or corrupted data when multiple threads modify the same resource
simultaneously.
Real-world Example:
Imagine multiple computers connected to a single printer:
• If two computers send print jobs simultaneously, the printer might mix their outputs and that leads
to invalid results.
• Similarly, threads accessing the same resource without coordination can produce inconsistent data.
Thread Priorities
In Java, thread priorities determine the execution order, allowing higher-priority threads to preempt lower
ones and access resources first. However, when threads of equal priority compete for the same resource,
conflicts can lead to inconsistent or erroneous outcomes.
Mechanisms for Thread Synchronization
Thread synchronization basically refers to The concept of one thread execute at a time and the rest of the
threads are in waiting state. This process is known as thread synchronization. It prevents the thread
interference and inconsistency problem.
Synchronization is build using locks or monitor. In Java, a monitor is an object that is used as a mutually
exclusive lock. Only a single thread at a time has the right to own a monitor. When a thread gets a lock then
all other threads will get suspended which are trying to acquire the locked monitor. So, other threads are
said to be waiting for the monitor, until the first thread exits the monitor. In a simple way, when a thread
request a resource then that resource gets locked so that no other thread can work or do any modification
until the resource gets released.
Types of Thread Synchronization
Thread synchronization are of two types:
• Mutual Exclusion
• Inter-Thread Communication

Java Thread Priority in Multithreading


Java being Object-Oriented works within a Multithreading environment in which the thread
scheduler assigns the processor to a thread based on the priority of the thread. Whenever we create a
thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating
the thread or it can be given by the programmer explicitly.
Priorities in Threads
Priorities in Threads in Java is a concept where each thread has a priority in layman’s language one can say
every object has priority here which is represented by numbers ranging from 1 to 10 and the constant
defined can help to implement which are mentioned below.

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].*;

class Thread1 extends Thread {

// 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());
}

public static void main(String[] args)


{
// Creating random threads with the help of above class
Thread1 t1 = new Thread1();
Thread1 t2 = new Thread1();
Thread1 t3 = new Thread1();

// Display the priority of above threads using getPriority() method


[Link]("t1 thread priority: " + [Link]());
[Link]("t2 thread priority: " + [Link]());
[Link]("t3 thread priority: " + [Link]());

// Setting priorities of above threads by passing integer arguments


[Link](2);
[Link](5);
[Link](8);

// Error will be thrown in this case [Link](21);

// Last Execution as the Priority is low


[Link]("t1 thread priority: " + [Link]());

// Will be executed before t1 and after t3


[Link]("t2 thread priority: " + [Link]());

// First Execution as the Priority is High


[Link]("t3 thread priority: " + [Link]());

// Now Let us Demonstrate how it will work According to it's Priority


[Link]();
[Link]();
[Link]();
}
}
Output:
t1 thread priority: 5
t2 thread priority: 5
t3 thread priority: 5
t1 thread priority: 2
t2 thread priority: 5
t3 thread priority: 8
Thread-1 is running with priority 5
Thread-2 is running with priority 8
Thread-0 is running with priority 2
Explanation:
• Thread1 extends Thread and overrides run(), which prints the thread’s name and priority.
• Threads have default priority 5, which can be changed between 1–10 using setPriority().
• The code sets t1=2, t2=5, t3=8 and prints their priorities.
• On calling start(), each thread runs concurrently; higher priority may get preference, but actual
order depends on the OS thread scheduler.
If multiple threads have the same priority, their execution order is decided by the thread scheduler. The
example below demonstrates this, followed by an explanation of the output for better conceptual and
practical understanding.
Example 2: Threads with the Same Priority
import [Link].*;

// Extending Thread class


class ThreadDemo extends Thread
{
// run() method for the thread that is invoked as threads are started
public void run()
{
[Link]("Inside run method");
}

public static void main(String[] args)


{
// Main Thread Priority set to 6
[Link]().setPriority(6);

// Print and display main thread priority using getPriority() method of Thread class
[Link]("Main thread priority: "
+ [Link]().getPriority());

// Creting Thread inside Main Thread


ThreadDemo t1 = new ThreadDemo();
// t1 thread is child of main thread so t1 thread will also have priority 6

[Link]("t1 thread priority: " + [Link]());


}
}

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).

Blocking Methods in Java


Blocking methods in java are the particular set of methods that block the thread until its operation is
complete. So, they will have to block the current thread until the condition that fulfills their task is satisfied.
Since, in nature, these methods are blocking so-called blocking methods. For example,
the InputStream read() method blocks until all InputStream data has been completely read. Here are some
of the most common Java blocking methods:
1. InvokeAndWait(): Wait for the Event Dispatcher thread to execute code.
2. [Link](): It blocks until input data is available, throws an exception, or detects the end of
the stream.
3. [Link](): Listen to inbound Java socket connection and blocks until a connection has
been made.
4. [Link](): Cause the current thread to wait until the latch counts to zero unless the
thread is interrupted.
There are several disadvantages of blocking methods:
• Blocking techniques pose a significant threat to system scalability. A classic blocking solution
consists of ways to mitigate blocking, using multiple threads to serve multiple customers.
• Design is the most important aspect since even if a multi-threaded system cannot reach beyond a
certain point, a poorly designed system can only support several hundred or thousands of threads
because of the limited number of JVM threads.
Implementation:
Here in the below example, following the execution of the first print statement, the program will be
blocked by a second print statement until some characters are entered in the console. Then click enter
because read() blocks the method until some input is readable.
Example 1:
// Java Program to illsutare Blocking methods

// Importing all input output classes


import [Link].*;

// Class
class GFG {

// main driver method


public static void main(String args[]) throws FileNotFoundException, IOException

{
// 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 {

// Main driver method


public static void main(String args[])
throws InterruptedException
{
// Let us create task that is going to wait
// for five threads before it starts
CountDownLatch latch = new CountDownLatch(4);

// Creating threads of Person type


// Custom parameter inputs
Person p1 = new Person(1500, latch, "PERSON-1");
Person p2 = new Person(2500, latch, "PERSON-2");
Person p3 = new Person(3500, latch, "PERSON-3");
Person p4 = new Person(4500, latch, "PERSON-4");
Person p5 = new Person(5500, latch, "PERSON-5");

// Starting the thread


// using the start() method
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();

// Waiting for the four threads


// using the [Link]() method
[Link]();

// Main thread has started


[Link]([Link]().getName()
+ " has finished his work");
}
}

// 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;

// Method of this class


public Person(int delay, CountDownLatch latch,
String name)
{
// super refers to parent class
super(name);

// This keyword refers to current object itself


[Link] = delay;
[Link] = latch;
}
@Override public void run()
{
// Try block to check for exceptions
try {
[Link](delay);
[Link]();

// Print the current thread by getting its name


// using the getName() method
// of whose work is completed
[Link](
[Link]().getName()
+ " has finished his work");
}

// Catch block to handle the exception


catch (InterruptedException e) {
// Print the line number where exception occurred
// using the printStackTrace() method
[Link]();
}
}
}

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).

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]();
}
}

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;
}

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]();
}
}

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.

What is Exception Handling in Java?: try, catch, throw, finally


What is an Exception in Java?
In Java, exceptions are unexpected events or errors that disrupt the normal flow of a program's execution.
Even if your code compiles successfully and looks error-free, some problems may only appear when the
program runs. These are known as runtime errors, and Java handles them using [Link] an
exception occurs, the program stops executing and displays an error message unless the exception is
properly handled
Example of Exception in Java
class ExceptionExample {
public static void main(String args[]) {
[Link]("Welcome to ScholarHat");
int a = 30;
int b = 0;
[Link](a / b);
[Link]("Welcome to the ScholarHat's Java Programming tutorial.");
[Link]("Enjoy your learning");
}
}
In the above code, at the 4th line, an integer is divided by 0, which is not possible, and the JVM(Java Virtual
Machine) raises an exception. In this case, the programmer does not handle the exception, which will halt
the program in between by throwing the exception, and the rest of the lines of code won't be executed.

Output
Welcome to ScholarHat
Exception in thread
Exception in thread "main" [Link]: / by zero
at [Link]([Link])

"main" [Link]: / by zero


at [Link]([Link])
What is Exception Handling in Java?
Exception Handling is a way of handling errors that occur during runtime and compile time. It maintains
your program flow despite runtime errors in the code and, thus, prevents unanticipated crashes. It
facilitates troubleshooting by providing error details, cutting down on development time, and improving
user happiness.
Exception Hierarchy in Java
In Java, Exception and Error are direct subclasses of the Throwable class, which is the root of the exception
hierarchy. An Exception represents conditions that a program should catch and handle, such as invalid input
or file not found. An Error, however, indicates serious problems that occur in the Java Virtual Machine
(JVM), like Stack Over flow Error or Out Of Memory Error, and usually cannot be handled by the application
code.
The hierarchy is divided into two branches:
• Errors: An error is a serious issue that occurs at runtime and is typically irrecoverable. It halts the
normal execution of the program and cannot be handled by the programmer. Errors belong to the
java. lang. Error class and include problems like Out Of Memory Error and Stack Over flow Error.
• Exceptions: Exceptions are events that a programmer can catch and handle within the code. When
an exception occurs, Java creates an exception object that holds details such as the exception's
name, message, and the program's state at the time. Exceptions allow the program to respond
gracefully to unexpected situations.
We'll look at the types of exceptions below:
Types of Exceptions in Java
There are mainly two types of exceptions: user-defined and built-in.

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

Belongs to the java. lang. Error


defined in java. lang Exception package
class

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.

Exceptions can be handled using exception-handling


Errors are irrecoverable
mechanisms

Why Do Exceptions Occur in Java?


Exceptions in Java occur due to unexpected events that prevent the program from running smoothly. These
issues are usually not visible at the time of writing or compiling the code, but they show up during program
execution (runtime).
Here are some common reasons why exceptions may occur in Java:
• User’s Invalid Input- If a user enters input that the program is not expecting (e.g., entering a string
when a number is expected), it can lead to exceptions like Number Format Exception.
• Database Connection Error- When the program cannot connect to the database (due to incorrect
URL, credentials, or server issues), it may throw a SQLException.
• System Failure- Hardware issues such as disk failure or insufficient memory can cause unexpected
exceptions during program execution.
• Network Problems- If your Java application depends on internet or server connections and the
network is unavailable, exceptions like IO Exception or Socket Exception may occur.
• Security Compromises- When code tries to access a restricted resource without permission, a
Security Exception can be thrown.
• Errors in Code (Logical or Runtime)- Mistakes in code, such as dividing by zero or accessing null
references, are common causes of exceptions like Arithmetic Exception or Null Pointer Exception.
Physical Limitations- Running out of memory or file storage space can trigger exceptions such as Out Of
Memory Error or IO Exception.
Java Exception Handling Keywords
Java consists of five keywords to handle various kinds of custom exceptions. They are:

Keyword Description

try The "try" keyword specifies an exception block.

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

throws The "throws" keyword declares 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

public class MultipleCatchBlock {

public static void main(String[] args) {

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

finally is the block in Java


final is a keyword and access finalize is the method in Java
Exception Handling to
modifier, which is used to apply that is used to perform clean-
execute the important code
restrictions on a class, method, up processing just before an
whether the exception
or variable. object is garbage collected.
occurs or not.

The final keyword is used with Finally, the block is always


finalize() method is used with
the classes, methods, and related to the try-catch
the objects.
variables. block in exception handling.

It is used with variables, It is with the try-catch


Used with objects
methods, and classes. block in exception handling.

Once declared, the final variable


becomes constant and can't be finally block cleans up all finalize method performs the
modified. A sub-class can neither the resources used in the cleaning concerning the object
override a final method nor can try block before its destruction
the final class be inherited.

finally block executes as


soon as the execution of the finalize method is executed
final method is executed only
try-catch block is completed just before the object is
when we call it
without depending on the destroyed
exception

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

throw new exception_class("error message");


Example of Exception Handling using Java throw

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);
}
}

public static void main(String[] args) {


try {
// Trying to check a negative number
checkNumber(-5);
} catch (IllegalArgumentException e) {
// Handling the thrown exception
[Link]("Caught an exception: " + [Link]());
}
}
}
Run Code >>
In the main method, the exception is captured and handled using a try-catch block, showing the exception
message if the input is negative. This Java class, ThrowExample, contains a method check Number that
throws an Illegal Argument Exception if the input number is negative.
Output
Caught an exception: Number cannot be negative
5. throws
The throws keyword is used in the method signature to indicate that a method in Java can throw particular
exceptions. This notifies the method that it must manage or propagate these exceptions to the caller.

import [Link];

public class ThrowsExample {

public static void main(String[] args) {


try {
methodWithException();
} catch (IOException e) {
[Link]("Caught IOException: " + [Link]());
}
}

public static void methodWithException() throws IOException {


// Simulate an IOException
throw new IOException("This is an IOException");
}
}
Run Code >>
In the above code, the method methodWithException is declared with throws IOException, indicating that
it may throw an IOException. The catch block catches the IOException in the main method.

Read More: Method Overloading in Java

Output
Caught IOException: This is an IOException
throw Vs. throws in Java

throw throws

The throw keyword is used to


Java throws keyword is used in method or function
explicitly throw an exception inside
signature to declare an exception that the method may
any block of code or function in the
throw while execution of code
program.

throw keyword can be used to throw


throws keyword can be used only with checked
both checked and unchecked
exceptions.
exceptions

throw is used within the method. throws is used within the method signature

Syntax: throw new


Syntax: void method() throws ArithmeticException
exception_class("error message");

We can throw only one exception at a We can declare multiple exceptions using the throws
time keyword that the method can throw

Common Scenarios of Java Exceptions


1. ArithmeticException
This exception is raised by JVM when the programmer tries to perform any arithmetic operation that is not
possible in mathematics. One of the frequently occurring arithmetic exceptions is when we divide any
number with zero.

int a=30/0; //ArithmeticException


2. NullPointerException
This occurs when a user tries to access a variable that stores null values. For example, if a variable stores a
null value and the user tries to perform any operation on that variable, a NullPointerException will be
thrown.

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.

int a[]=new int[6];


a[10]=80; //ArrayIndexOutOfBoundsException
5. StringIndexOutOfBoundsException
It is the same as ArrayIndexOutOfBoundsException but it is for strings instead of arrays. Here if the length
of a string is less than what we are trying to access there occurs the StringIndexOutOfBoundsException.
String s = "I am learning Java on ScholarHat.";
[Link]("String length is:" + [Link]());
[Link]("Length of substring is:" + [Link](40)); //StringIndexOutOfBoundsException
How Does JVM Handle an Exception?
When you run a program and an exception occurs, the JVM (Java Virtual Machine) takes care of it in a
systematic way. Here's what happens in simple terms:
1. Creating the Exception Object: When an exception happens, the JVM creates an exception object.
This object contains information like the error name, a description, and the program state at that
moment. This step is called throwing an exception.
2. Call Stack: Imagine that your program has a list of methods that have been called. This ordered list
is called the call stack. The JVM checks the call stack to find where the exception came from.
3. Searching for the Handler: The JVM looks for an exception handler by searching the call stack. It
starts from the method where the exception happened and moves backward through the call stack.
4. Passing the Exception: If a handler is found, the exception is passed to it to handle.
5. Default Handler: If no handler is found, the JVM's default exception handler takes over.
Wouldn't it be helpful if you knew how to handle exceptions in your own code? Let's dive into an example.
Example Program
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an exception
} catch (ArithmeticException e) {
[Link]("Oops! Something went wrong: " + [Link]());
}
}
}
Try it Yourself >>
Output

Oops! Something went wrong: / by zero


Explanation
In this example, we deliberately created an exception (division by zero). The JVM handles it by searching
for the handler (the catch block) and then outputs a user-friendly message instead of crashing the program.
This process helps ensure your program runs smoothly even when unexpected errors occur.
So, whenever you encounter exceptions in your programs, remember that the JVM is doing its job in the
background, helping you track down the issue while keeping your program from failing unexpectedly. Isn’t
that awesome?
How Programmer Handles an Exception?
In Java, programmers use an exception handling mechanism to prevent programs from crashing during
unexpected events. Java provides five key keywords to manage exceptions effectively: try, catch, throw,
throws, and finally. Here's how each one works:
• try block: Wraps code that might throw an exception. It's used to test a block of code for errors.
• catch block: Handles the exception if one occurs in the try block. It catches specific exceptions and
defines how to respond to them.
• throw keyword: Used to manually throw an exception in situations where the code detects an error
and wants to signal it.
• throws keyword: Declares exceptions a method might throw, warning the calling method to handle
or propagate them.
• finally block: Executes regardless of whether an exception occurs or not. It is commonly used to
release resources like closing files or database connections.
Tip: Understanding the control flow in the try-catch-finally block is key to mastering exception handling.
Let’s see how this works in practice through an example.
Example Program

public class Main {


public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an exception
} catch (ArithmeticException e) {
[Link]("Oops! Division by zero is not allowed: " + [Link]());
} finally {
[Link]("This block always runs.");
}
}
}
Try it Yourself >>
Output

Oops! Division by zero is not allowed: / by zero


This block always runs.
Explanation
In this example, we deliberately created an exception (division by zero). The try block contains the code
that might throw an exception. When the exception occurs, the catch block handles it by printing a
message. No matter what happens, the finally block always runs to ensure any necessary clean-up
happens.
Using the try-catch-finally mechanism, you can handle exceptions in a controlled way, making sure your
program continues to run smoothly even in the face of errors. Isn’t that a neat way to keep your code
robust and user-friendly?
Advantages of Exception Handling in Java
• Identifies the Type of Error: Helps in detecting the exact type of error that occurred during program
execution.
• Ensures Program Completion: Allows the program to continue running even after encountering an
exception.
• Prevents Program Disruption: Maintains the normal flow of the application by handling exceptions
smoothly.
• Catches Specific Exceptions: Enables the programmer to catch and handle specific exceptions for
better error control.
• Promotes Cleaner Code: Encourages writing clean, organized code with proper error handling logic.
• Improves Debugging: Makes it easier for developers to identify bugs and apply fixes effectively.

You might also like