0% found this document useful (0 votes)
3 views126 pages

67c6d8f369c6c JAVA - Notes

The document provides comprehensive notes on Java programming, covering topics such as Object-Oriented Programming (OOP), multithreading, exception handling, and applets. It details the history of Java, its features, and the differences between Java's compiler and interpreter. Additionally, it explains key OOP concepts like classes, objects, inheritance, polymorphism, abstraction, and encapsulation, along with practical examples and advantages over procedural programming.
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)
3 views126 pages

67c6d8f369c6c JAVA - Notes

The document provides comprehensive notes on Java programming, covering topics such as Object-Oriented Programming (OOP), multithreading, exception handling, and applets. It details the history of Java, its features, and the differences between Java's compiler and interpreter. Additionally, it explains key OOP concepts like classes, objects, inheritance, polymorphism, abstraction, and encapsulation, along with practical examples and advantages over procedural programming.
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
You are on page 1/ 126

Java Programming

DIGITAL NOTES
ON
JAVA PROGRAMMING

TOPIC COVERED
 Object Oriented Programming Structure
 Overview of Advance Java

MICROTEK COLLEGE OF MANAGEMENT & TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE

PREPARED BY: SHUBHANSHU KUSHWAHA

1|Page
Java Programming

INDEX
1. OOPs Concept 03 – 54
2. Multithreading 55 - 66
3. Exception Handling 67 - 72
4. AWT 73 - 91
5. Applet 92 - 105
6. Servlets 106 - 110
7. JSP 111 - 126

Java
2|Page
Java Programming
Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling
and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).

James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects.
The language, initially called Oak after an oak tree that stood outside Gosling's office, also went by the name
Green and ended up later being renamed as Java, from a list of random words.

Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.

…………………….

Java is:

 Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.

 Platform independent: Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform
it is being run.

 Simple:Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be
easy to master.

 Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.

 Architectural-neutral :Java compiler generates an architecture-neutral object file format which makes the
compiled code to be executable on many processors, with the presence of Java runtime system.

 Portable:Being architectural-neutral and having no implementation dependent aspects of the specification


makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a
POSIX subset.

 Robust:Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time
error checking and runtime checking.

 Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks
simultaneously. This design feature allows developers to construct smoothly running interactive
applications.

3|Page
Java Programming

 Interpreted:Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an incremental and
light weight process.

 High Performance: With the use of Just-In-Time compilers, Java enables high performance.

 Distributed:Java is designed for the distributed environment of the internet.

 Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry extensive amount of run-time information that can be used to verify
and resolve accesses to objects on run-time.

What is Java source code

Before knowing about compiler and Interpreter we should know about source code.
 Java source code is code that you write in the Java programming language.
 File name ends with ".java" extension.
 Ex: Your_class_name.java
 Java source code is converted to Java bytecode by the Java compiler.
 File name ends with ".class" extension.
 Ex: Your_class_name.class

What is Java Compiler

 Machine

 Phone Number

 Class File

 Compiler

 Editor Html

 Html Editor

 Java compiler refers to a program which translates Java language source code into the Java Virtual Machine (JVM)

bytecodes.

What is Java Interpreter

 "Interpreted" means that the computer looks at the language, and then turns it into native machine language.

4|Page
Java Programming

 The term Java interpreter refers to a program which implements the JVM specification and actually executes the bytecodes

by running your program.

Compiler versus Interpreter

 Compiling happens when the writing of the program is finished like calling javac.

 Example: Trough command line
 JAVAC Your_class_name.java

 Compilation of java file will generate class file like (ex: Your_class_name.class)
 Interpretation happens at runtime(which means while running the Java program),
 Example: Trough command line
 JAVA Your_class_name

 This will take Your_class_name class file (i.e Your_class_name.class) to execute

OOPs (Object Oriented Programming System) Concept

5|Page
Java Programming

Object means a real word entity such as pen,


chair, table etc.Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies the software development and maintenance by providing some
concepts:

 Object
 Classlst
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

6|Page
Java Programming

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convense the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.n

In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.

7|Page
Java Programming

Advantage of OOPs over Procedure-oriented programming language

1)OOPs makes development and maintenance easier where as in Procedure-oriented


programming[]]{}””””””””””””””””””””””’’’’’’”{
g language it is not easy to manage if code grows as project size grows.

2)OOPs provides data hiding whereas in Procedure-oriented prgramming language a global data can
be accessed from anywhere.

3)OOPs provides ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.

What is difference between object-oriented programming language and object-


based programming language?

Object based programming language follows all the features of OOPs except Inheritance. JavaScript
and VBScript are examples of object based programming languages.

Object and Class in Java

8|Page
Java Programming

In this page, we will learn about java objects and classes. In object-oriented programming technique,
we design a program using objects and classes.

Object is the physical as well as logical entity whereas class is the logical entity only.

Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc.
It can be physical or logical (tengible and intengible). The example of integible object is banking
system.

An object has three characteristics:

 state: represents data (value) of an object.


 behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But,it is used internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.

9|Page
Java Programming

Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which
objects are created.

A class in java can contain:

 data member
 method
 constructor
 block
 class and interface

Syntax to declare a class:


1. class <class_name>{
2. data member;
3. method;
4. }

Instance variable in Java

A variable that is created inside the class but outside the method, is known as instance
variable.Instance variable doesn't get memory at compile time.It gets memory at runtime when
object(instance) is created.That is why, it is known as instance variable.

Method in Java

In java, a method is like function i.e. used to expose behaviour of an object.

Advantage of Method

 Code Reusability
 Code Optimization

new keyword

The new keyword is used to allocate memory at runtime.

10 | P a g e
Java Programming

11 | P a g e
Java Programming

Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

12 | P a g e
Java Programming

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to expose behaviour of
object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you don't Method is not provided by compiler in a
have any constructor. case.

Constructor name must be same as the class name. Method name may or may not be same
class name.

Java Copy Constructor


There is no copy constructor in java. But, we can copy the values of one object to another like copy
constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

 By constructor
 By assigning the values of one object into another

13 | P a g e
Java Programming

Java static keyword


The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than
instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

1) Java static variable


If you declare any variable as static, it is known static variable.

 The static variable can be used to refer the common property of all objects (that is not unique
for each object) e.g. company name of employees,college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

2) Java static method


If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than object of a class.


o A static method can be invoked without the need for creating an instance of a class.
o static method can access static data member and can change the value of it.

14 | P a g e
Java Programming

Abstract class in Java


A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract
and non-abstract methods (method with body).

Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.

Another way, it shows only important things to the user and hides the internal details for example
sending sms, you just type the text and send the message. You don't know the internal processing
about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstaction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class that is declared as abstract is known as abstract class. It needs to be extended and its method
implemented. It cannot be instantiated.

Example abstract class


1. abstract class A{}

abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.

15 | P a g e
Java Programming

Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.

The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and multiple
inheritance in Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

 It is used to achieve fully abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method and public, static and final
keywords before data members.

In other words, Interface fields are public, static and final bydefault, and methods are public and
abstract.

16 | P a g e
Java Programming

Understanding relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.

17 | P a g e
Java Programming

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:

18 | P a g e
Java Programming

 An applet is a Java class that extends the java.applet.Applet 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:


Four methods in the Applet class give 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 java.awt.
19 | P a g e
Java Programming

A "Hello, World" Applet:


The following is a simple applet named HelloWorldApplet.java:

import java.applet.*;

import java.awt.*;

public class HelloWorldApplet extends Applet

public void paint (Graphics g)

g.drawString ("Hello World", 25, 50);

These import statements bring the classes into the scope of our applet class:

 java.applet.Applet.

 java.awt.Graphics.

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 java.applet.Applet 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

20 | P a g e
Java Programming

 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. Below is an
example that invokes the "Hello, World" applet:

<html>

<title>The Hello, World Applet</title>

<hr>

<applet code="HelloWorldApplet.class" width="320" height="120">

If your browser was Java-enabled, a "Hello, World"

message would appear here.

21 | P a g e
Java Programming

</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 a </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="http://amrood.com/applets"

code="HelloWorldApplet.class" 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 code="mypackage.subpackage.TestApplet.class"

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.

22 | P a g e
Java Programming

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. (Applet.init() is implemented to
do nothing.) Override the default implementation to insert custom initialization code.

The Applet.getParameter() 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 CheckerApplet.java:

import java.applet.*;

import java.awt.*;

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 (Color.black);

setForeground (fg);

private void parseSquareSize (String param)

23 | P a g e
Java Programming

if (param == null) return;

try {

squareSize = Integer.parseInt (param);

catch (Exception e) {

// Let default value remain

The applet calls parseSquareSize() to parse the squareSize parameter.


parseSquareSize() calls the library method Integer.parseInt(), which parses a string
and returns an integer. Integer.parseInt() 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
works.

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.

<html>

<title>Checkerboard Applet</title>

<hr>

<applet code="CheckerApplet.class" width="480" height="320">

<param name="color" value="blue">

<param name="squaresize" value="30">

</applet>

<hr>

</html>

24 | P a g e
Java Programming

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.

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

 Make an HTML page with the appropriate tag to load the applet code.

 Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot
be loaded.

 Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.

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

 Remove the call to setSize; for applets, sizing is done with the width and height parameters
in the HTML file.

 Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when


the browser exits.

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

 Don't call setVisible(true). The applet is displayed automatically.

Event Handling:
Applets inherit a group of event-handling methods from the Container class. The
Container class defines several methods, such as processKeyEvent and
processMouseEvent, for handling particular types of events, and then one catch-all
method called processEvent.

In order to react an event, an applet must override the appropriate event-specific


method.
25 | P a g e
Java Programming

import java.awt.event.MouseListener;

import java.awt.event.MouseEvent;

import java.applet.Applet;

import java.awt.Graphics;

public class ExampleEventHandling extends Applet

implements MouseListener {

StringBuffer strBuffer;

public void init() {

addMouseListener(this);

strBuffer = new StringBuffer();

addItem("initializing the apple ");

public void start() {

addItem("starting the applet ");

public void stop() {

addItem("stopping the applet ");

public void destroy() {

addItem("unloading the applet");

void addItem(String word) {

System.out.println(word);

strBuffer.append(word);

repaint();

26 | P a g e
Java Programming

public void paint(Graphics g) {

//Draw a Rectangle around the applet's display area.

g.drawRect(0, 0,

getWidth() - 1,

getHeight() - 1);

//display the string inside the rectangle.

g.drawString(strBuffer.toString(), 10, 20);

public void mouseEntered(MouseEvent event) {

public void mouseExited(MouseEvent event) {

public void mousePressed(MouseEvent event) {

public void mouseReleased(MouseEvent event) {

public void mouseClicked(MouseEvent event) {

addItem("mouse clicked! ");

Now, let us call this applet as follows:

<html>

<title>Event Handling</title>

<hr>

<applet code="ExampleEventHandling.class"

width="300" height="300">

</applet>

<hr>

</html>

27 | P a g e
Java Programming

Initially, the applet will display "initializing the applet. Starting the applet." Then once
you click inside the rectangle "mouse clicked" will be displayed as well.

Displaying Images:
An applet can display images of the format GIF, JPEG, BMP, and others. To display an
image within the applet, you use the drawImage() method found in the
java.awt.Graphics class.

Following is the example showing all the steps to show images:

import java.applet.*;

import java.awt.*;

import java.net.*;

public class ImageDemo extends Applet

private Image image;

private AppletContext context;

public void init()

context = this.getAppletContext();

String imageURL = this.getParameter("image");

if(imageURL == null)

imageURL = "java.jpg";

try

URL url = new URL(this.getDocumentBase(), imageURL);

image = context.getImage(url);

}catch(MalformedURLException e)

e.printStackTrace();

// Display in browser status bar

context.showStatus("Could not load image!");

28 | P a g e
Java Programming

public void paint(Graphics g)

context.showStatus("Displaying image");

g.drawImage(image, 0, 0, 200, 84, null);

g.drawString("www.javalicense.com", 35, 100);

Now, let us call this applet as follows:

<html>

<title>The ImageDemo applet</title>

<hr>

<applet code="ImageDemo.class" width="300" height="200">

<param name="image" value="java.jpg">

</applet>

<hr>

</html>

Playing Audio:
An applet can play an audio file represented by the AudioClip interface in the
java.applet package. The AudioClip interface has three methods, including:

 public void play(): Plays the audio clip one time, from the beginning.

 public void loop(): Causes the audio clip to replay continually.

 public void stop(): Stops playing the audio clip.

To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet
class. The getAudioClip() method returns immediately, whether or not the URL resolves
to an actual audio file. The audio file is not downloaded until an attempt is made to
play the audio clip.

Following is the example showing all the steps to play an audio:

import java.applet.*;

29 | P a g e
Java Programming

import java.awt.*;

import java.net.*;

public class AudioDemo extends Applet

private AudioClip clip;

private AppletContext context;

public void init()

context = this.getAppletContext();

String audioURL = this.getParameter("audio");

if(audioURL == null)

audioURL = "default.au";

try

URL url = new URL(this.getDocumentBase(), audioURL);

clip = context.getAudioClip(url);

}catch(MalformedURLException e)

e.printStackTrace();

context.showStatus("Could not load audio file!");

public void start()

if(clip != null)

clip.loop();

public void stop()

if(clip != null)

30 | P a g e
Java Programming

clip.stop();

Now, let us call this applet as follows:

<html>

<title>The ImageDemo applet</title>

<hr>

<applet code="ImageDemo.class" width="0" height="0">

<param name="audio" value="test.wav">

</applet>

<hr>

</html>

31 | P a g e
Java Programming

Method Overloading in Java


If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of
the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments,
if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then
it may be difficult for you as well as other programmers to understand the behaviour of the method
because its name differs. So, we perform method overloading to figure out the program quickly.

Advantage of method overloading?

Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In java, Methood Overloading is not possible by changing the return type of the method.

1)Example of Method Overloading by changing the no. of arguments

In this example, we have created two overloaded methods, first sum method performs addition of two
numbers and second sum method performs addition of three numbers.

1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
11. }
32 | P a g e
Java Programming
Test it Now

Output:30
40

2)Example of Method Overloading by changing data type of argument

In this example, we have created two overloaded methods that differs in data type. The first sum method
receives two integer arguments and second sum method receives two double arguments.

1. class Calculation2{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation2 obj=new Calculation2();
7. obj.sum(10.5,10.5);
8. obj.sum(20,20);
9.
10. }
11. }
Test it Now

Output:21.0
40

Que) Why Method Overloaing is not possible by changing the return type of method?

In java, method overloading is not possible by changing the return type of the method because there
may occur ambiguity. Let's see how ambiguity may occur:

because there was problem:

1. class Calculation3{
2. int sum(int a,int b){System.out.println(a+b);}
3. double sum(int a,int b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation3 obj=new Calculation3();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10. }
Test it Now

33 | P a g e
Java Programming

int result=obj.sum(20,20); //Here how can java determine which sum() method should be called

Can we overload main() method?

Yes, by method overloading. You can have any number of main methods in a class by method overloading.
Let's see the simple example:

1. class Overloading1{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
10. }
Test it Now

Output:main() method invoked


10

Method Overloading and TypePromotion

One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept
by the figure given below:

34 | P a g e
Java Programming

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short
datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float
or double and so on.

Example of Method Overloading with TypePromotion


1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9.
10. }
11. }
Test it Now

Output:40
60

35 | P a g e
Java Programming

Example of Method Overloading with TypePromotion if matching found

If there are matching type arguments in the method, type promotion is not performed.

1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
Test it Now

Output:int arg method invoked

Example of Method Overloading with TypePromotion in case ambiguity

If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.

1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Test it Now

Output:Compile Time Error

36 | P a g e
Java Programming

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.

In other words, If subclass provides the specific implementation of the method that has been provided
by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is already provided
by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Test it Now

Output:Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is why we
use method overriding.

37 | P a g e
Java Programming

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method is same and there is IS-A
relationship between the classes, so there is method overriding.

1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }
Test it Now

Output:Bike is running safely

Real example of Java Method Overriding


Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest
varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate
of interest.

1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.

38 | P a g e
Java Programming
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test2{
17. public static void main(String args[]){
18. SBI s=new SBI();
19. ICICI i=new ICICI();
20. AXIS a=new AXIS();
21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
24. }
25. }
Test it Now

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it
later.

Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object. Static belongs
to class area and instance belongs to heap area.

Can we override java main method?

No, because main is a static method.

39 | P a g e
Java Programming

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only. We will have detailed learning
of these. Let's first learn the basics of final keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){

40 | P a g e
Java Programming
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now

Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

Example of final method


1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now

Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

Example of final class


1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda();
8. honda.run();
9. }
10. }
Test it Now

Output:Compile Time Error

41 | P a g e
Java Programming

Q) Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now

Output:running...

Q) What is blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as blank final variable.

If you want to create a variable that is initialized at the time of creating object and once initialized may
not be changed, it is useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable


1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }

42 | P a g e
Java Programming
12. }
Test it Now

Output:70

static blank final variable

A static final variable that is not initialized at the time of declaration is known as static blank final variable.
It can be initialized only in static block.

Example of static blank final variable


1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Test it Now

Output:Compile Time Error

43 | P a g e
Java Programming

String
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming
language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings:
The most direct way to create a string is to write:

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case,
"Hello world!'.

As with any other object, you can create String objects by using the new keyword and a constructor. The String
class has eleven constructors that allow you to provide the initial value of the string using different sources, such
as an array of characters.

public class StringDemo{

public static void main(String args[]){

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};

String helloString = new String(helloArray);

System.out.println( helloString );

This would produce the following result:

hello.

Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a
necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String
Builder Classes.

44 | P a g e
Java Programming

String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor method that
you can use with strings is the length() method, which returns the number of characters contained in the string
object.

After the following two lines of code have been executed, len equals 17:

public class StringDemo {

public static void main(String args[]) {

String palindrome = "Dot saw I was Tod";

int len = palindrome.length();

System.out.println( "String Length is : " + len );

This would produce the following result:

String Length is : 17

Concatenating Strings:
The String class includes a method for concatenating two strings:

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method
with string literals, as in:

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in:

"Hello," + " world" + "!"

which results in:

"Hello, world!"

Let us look at the following example:

45 | P a g e
Java Programming

public class StringDemo {

public static void main(String args[]) {

String string1 = "saw I was ";

System.out.println("Dot " + string1 + "Tod");

This would produce the following result:

Dot saw I was Tod

Creating Format Strings:


You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent
class method, format(), that returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a
one-time print statement. For example, instead of:

System.out.printf("The value of the float variable is " +

"%f, while the value of the integer " +

"variable is %d, and the string " +

"is %s", floatVar, intVar, stringVar);

you can write:

String fs;

fs = String.format("The value of the float variable is " +

"%f, while the value of the integer " +

"variable is %d, and the string " +

"is %s", floatVar, intVar, stringVar);

System.out.println(fs);

String Methods:
Here is the list of methods supported by String class:

SN Methods with Description

46 | P a g e
Java Programming

1
char charAt(int index)

Returns the character at the specified index.

public char charAt(int index)

3
int compareTo(String anotherString)

Compares two strings lexicographically.

int compareTo(String anotherString)

5
String concat(String str)

Concatenates the specified string to the end of this string.

public String concat(String s)

10
boolean equals(Object anObject)

Compares this string to the specified object.

public boolean equals(Object anObject)

11
boolean equalsIgnoreCase(String anotherString)

Compares this String to another String, ignoring case considerations.

public boolean equalsIgnoreCase(String anotherString)

47 | P a g e
Java Programming

16
int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified character.

public int indexOf(char ch, int fromIndex)

23
int lastIndexOf(Char ch)

Returns the index within this string of the rightmost occurrence of the specified substring.

public int lastIndexOf(char ch, int fromIndex)

25
int length()

Returns the length of this string.

public int length()

29
String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.

30
String replaceAll(String regex, String replacement

Replaces each substring of this string that matches the given regular expression with the
given replacement.

32
String[] split(String regex)

Splits this string around matches of the given regular expression.

48 | P a g e
Java Programming

33
String[] split(String regex, int limit)

Splits this string around matches of the given regular expression.

37
String substring(int beginIndex)

Returns a new string that is a substring of this string.

38
String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

39
char[] toCharArray()

Converts this string to a new character array.

40
String toLowerCase()

Converts all of the characters in this String to lower case using the rules of the default
locale.

42
String toString()

This object (which is already a string!) is itself returned.

43
String toUpperCase()

Converts all of the characters in this String to upper case using the rules of the default
locale.

44
String toUpperCase(Locale locale)

Converts all of the characters in this String to upper case using the rules of the given
Locale.

49 | P a g e
Java Programming

45
String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

50 | P a g e
Java Programming

Methods
A Java method is a collection of statements that are grouped together to perform an
operation. Ex:- System.out.println()

Creating Method:
Considering the following example to explain the syntax of a method:

public static int methodName(int a, int b) {

// body

Here,

 public static : modifier.

 int: return type

 methodName: name of the method

 a, b: formal parameters

 int a, int b: list of parameters

Method definition consists of a method header and a method body. The same is shown
below:

modifier returnType nameOfMethod ( Parameter List) {

// method body

The syntax shown above includes:

 modifier: It defines the access type of the method and it is optional to use.

 returnType: Method may return a value.

 nameOfMethod: This is the method name. The method signature consists of the method
name and the parameter list.

51 | P a g e
Java Programming

 Parameter List: The list of parameters, it is the type, order, and number of parameters of
a method. These are optional, method may contain zero parameters.

 method body: The method body defines what the method does with statements.

Method Calling:
For using a method, it should be called. There are two ways in which a method is called
i.e. method returns a value or returning nothing (no return value).

The process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then returns
control to the caller in two conditions, when:

 return statement is executed.

 reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Lets consider an


example:

System.out.println("This is tutorialspoint.com!");

The method returning value can be understood by the following example:

int result = sum(6, 9);

52 | P a g e
Java Programming

Access Modifiers in java


There are two types of modifiers in java: access modifiers andnon-access modifiers.

The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or
class.

There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public

1) private access modifier


The private access modifier is accessible only within class.

2) default access modifier


If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible
only within package.

3) protected access modifier


The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.

4) public access modifier


The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

53 | P a g e
Java Programming

Access Modifier within class within package outside outside package


package by
subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

54 | P a g e
Java Programming

Multithreading
Java is a multi-threaded programming language which means we can develop multi
threaded program using Java. A multi threaded program contains two or more parts
that can run concurrently and each part can handle different task at the same time
making optimal use of the available resources specially when your computer has
multiple CPUs.

By definition multitasking is when multiple processes share common processing


resources such as a CPU. Multi threading extends the idea of multitasking into
applications where you can subdivide specific operations within a single application into
individual threads. Each of the threads can run in parallel. The OS divides processing
time not only among different applications, but also among each thread within an
application.

Multi threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.

Life Cycle of a Thread:


A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. Following diagram shows complete life cycle of a thread.

Above-mentioned stages are explained here:

55 | P a g e
Java Programming

 New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.

 Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.

 Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.

 Timed waiting: A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.

 Terminated ( Dead ): A runnable thread enters the terminated state when it completes its
task or otherwise terminates.

Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order
in which threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot
guarantee the order in which threads execute and very much platform dependent.

Create Thread by Implementing Runnable Interface:


If your class is intended to be executed as a thread then you can achieve this by
implementing Runnable interface. You will need to follow three basic steps:

Step 1:
As a first step you need to implement a run() method provided by Runnableinterface.
This method provides entry point for the thread and you will put you complete business
logic inside this method. Following is simple syntax of run() method:

public void run( )

56 | P a g e
Java Programming

Step 2:
At second step you will instantiate a Thread object using the following constructor:

Thread(Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements the Runnableinterface


and threadName is the name given to the new thread.

Step 3
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:

void start( );

Example:
Here is an example that creates a new thread and starts it running:

class RunnableDemo implements Runnable {


private Thread t;
private String threadName;

RunnableDemo( String name){


threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}

57 | P a g e
Java Programming
System.out.println("Thread " + threadName + " exiting.");
}

public void start ()


{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

public class TestThread {


public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");


R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}

This would produce the following result:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2

58 | P a g e
Java Programming
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Create Thread by Extending Thread Class:


The second way to create a thread is to create a new class that extendsThread class
using the following two simple steps. This approach provides more flexibility in handling
multiple threads created using available methodsin Thread class.

Step 1
You will need to override run( ) method available in Thread class. This method
provides entry point for the thread and you will put you complete business logic inside
this method. Following is simple syntax of run() method:

public void run( )

Step 2
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:

void start( );

Example:
Here is the preceding program rewritten to extend Thread:

class ThreadDemo extends Thread {


private Thread t;
private String threadName;

ThreadDemo( String name){


threadName = name;

59 | P a g e
Java Programming
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start ()


{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

public class TestThread {


public static void main(String args[]) {

ThreadDemo T1 = new ThreadDemo( "Thread-1");


T1.start();

60 | P a g e
Java Programming
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}

This would produce the following result:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Thread Methods:
Following is the list of important methods available in the Thread class.

SN Methods with Description

1 public void start()

Starts the thread in a separate path of execution, then invokes the run()
method on this Thread object.

2 public void run()

61 | P a g e
Java Programming

If this Thread object was instantiated using a separate Runnable target, the
run() method is invoked on that Runnable

object.

3 public final void setName(String name)


Changes the name of the Thread object. There is also a getName() method
for retrieving the name.

4 public final void setPriority(int priority)


Sets the priority of this Thread object. The possible values are between 1 and
10.

5 public final void setDaemon(boolean on)


A parameter of true denotes this Thread as a daemon thread.

6 public final void join(long millisec)


The current thread invokes this method on a second thread, causing the
current thread to block until the second thread terminates or the specified
number of milliseconds passes.

7 public void interrupt()


Interrupts this thread, causing it to continue execution if it was blocked for
any reason.

8 public final boolean isAlive()


Returns true if the thread is alive, which is any time after the thread has been
started but before it runs to completion.

The previous methods are invoked on a particular Thread object. The


following methods in the Thread class are static. Invoking one of the
staticmethods performs the operation on the currently running thread.

SN Methods with Description

1 public static void yield()

62 | P a g e
Java Programming

Causes the currently running thread to yield to any other threads of the same
priority that are waiting to be scheduled.

2 public static void sleep(long millisec)


Causes the currently running thread to block for at least the specified number
of milliseconds.

3 public static boolean holdsLock(Object x)


Returns true if the current thread holds the lock on the given Object.

4 public static Thread currentThread()


Returns a reference to the currently running thread, which is the thread that
invokes this method.

5 public static void dumpStack()


Prints the stack trace for the currently running thread, which is useful when
debugging a multithreaded application.

Example:
The following ThreadClassDemo program demonstrates some of thesemethods of the
Thread class. Consider a class DisplayMessage which implements Runnable:

// File Name : DisplayMessage.java


// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{

63 | P a g e
Java Programming
System.out.println(message);
}
}
}

Following is another class which extends Thread class:

// File Name : GuessANumber.java


// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ " guesses " + guess);
counter++;
}while(guess != number);
System.out.println("** Correct! " + this.getName()
+ " in " + counter + " guesses.**");
}
}

Following is the main program which makes use of above defined classes:

// File Name : ThreadClassDemo.java


public class ThreadClassDemo

64 | P a g e
Java Programming
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();

Runnable bye = new DisplayMessage("Goodbye");


Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();

System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);

thread4.start();
System.out.println("main() is ending...");
}
}

65 | P a g e
Java Programming

This would produce the following result. You can try this example again and again and
you would get different result every time.

Starting hello thread...


Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......

66 | P a g e
Java Programming

Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.

What is exception handling


Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote
etc.

Hierarchy of Java Exception classes

Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked
exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

67 | P a g e
Java Programming

Difference between checked and unchecked exceptions

1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time rather they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur


There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.

2) Scenario where NumberFormatException occurs


The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable
that have characters, converting this variable into digit will occur NumberFormatException.

3) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws

Java try-catch
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.

68 | P a g e
Java Programming
Java try block must be followed by either catch or finally block.
Syntax of java try-catch
Try
{
//code that may throw exception
}
catch(Exception_class_Name ref)
{}

Syntax of try-finally block


Try
{
//code that may throw exception
}
finally{}

Java catch block


Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.

public class Testtrycatch2


{
public static void main(String args[])
{
Try
{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}

Java Multi catch block


If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch
block.
public class TestMultipleCatchBlock

69 | P a g e
Java Programming
{
public static void main(String args[]){
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("task 2 completed");
}
catch(Exception e)
{
System.out.println("common task completed");
}
System.out.println("rest of the code...");
}
}

Java finally block


Java finally block is a block that is used to execute important code such as closing connection, stream
etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
class TestFinallyBlock
{
public static void main(String args[])
{
Try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
Finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Java throw exception


70 | P a g e
Java Programming

Java throw keyword


The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is
mainly used to throw custom exception. We will see custom exceptions later.
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to the programmer
that there may occur an exception so it is better for the programmer to provide the exception handling
code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up before
the code being used.
Syntax of java throws
return_type method_name() throws exception_class_name{ //method code }

import java.io.IOException;
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
Try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");

71 | P a g e
Java Programming
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

Java Custom Exception


If you are creating your own Exception that is known as custom exception or user-defined exception.
Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
class InvalidAgeException extends Exception
{
InvalidAgeException(String s){
super(s);
}
}

class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
Try
{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}

AWT

72 | P a g e
Java Programming
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-
based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system. AWT is heavy weight i.e. its components are using the resources of underlying
operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.

Components

All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there
are classes for each component as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.

73 | P a g e
Java Programming

Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels
etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.

Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another
window for creating a window.

Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like
button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.

Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default false.

Java AWT Example


To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame
in AWT.

1. By extending Frame class (inheritance)


2. By creating the object of Frame class (association)

74 | P a g e
Java Programming

AWT Example by Inheritance


AWTExample1.java

// importing Java AWT class


import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


b.setBounds(30,100,80,30);

// adding button into frame


add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample1 f = new AWTExample1();
}
}
Note: The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example
that sets the position of the awt button.

Output:
75 | P a g e
Java Programming

AWT Example by Association


AWTExample2.java

// importing Java AWT class


import java.awt.*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

// creating a Frame
Frame f = new Frame();

// creating a Label
Label l = new Label("Employee id:");

// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 120, 80, 30);
b.setBounds(100, 120, 80, 30);

// adding components into frame


f.add(b);
f.add(l);
76 | P a g e
Java Programming
f.add(t);

// frame size 300 width and 300 height


f.setSize(400,300);

// setting the title of frame


f.setTitle("Employee info");

// no layout
f.setLayout(null);

// setting visibility of frame


f.setVisible(true);
}

// main method
public static void main(String args[]) {
AWTExample2 awt_obj = new AWTExample2();
}
} Output:

Event
Change in the state of an object is known as event i.e. event describes the change in state of source. Events
are generated as result of user interaction with the graphical user interface components.

Types of Event
The events can be broadly classified into two categories:
 Foreground Events - Those events which require the direct interaction of user.They are generated as
consequences of a person interacting with the graphical components in Graphical User Interface. For
example, clicking on a button, moving the mouse, entering a character through keyboard,selecting
an item from list, scrolling the page etc.

77 | P a g e
Java Programming
 Background Events - Those events that require the interaction of end user are known as background
events. Operating system interrupts, hardware or software failure, timer expires, an operation
completion are the example of background events.

Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs.
This mechanism have the code which is known as event handler that is executed when an event occurs. The
Delegation Event Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
 Listener - It is also known as event handler.Listener is responsible for generating response to an
event. From java implementation point of view the listener is also an object. Listener waits until it
receives an event. Once the event is received , the listener process the event an then returns.

Event classes and Listener interfaces:


Event Classes Listener Interfaces

78 | P a g e
Java Programming

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:


1. Implement the Listener interface and overrides its methods
2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registration methods. For
example:

o Button
public void addActionListener(ActionListener a){}
o
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
79 | P a g e
Java Programming
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Event Handling Codes:

We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class

Example of event handling within class:


import java.awt.*;
import java.awt.event.*;

class AEvent extends Frame implements ActionListener


{
TextField tf;
AEvent()
{

tf=new TextField();
tf.setBounds(60,50,170,20);

80 | P a g e
Java Programming
Button b=new Button("click me");
b.setBounds(100,120,80,30);

b.addActionListener(this);

add(b);add(tf);

setSize(300,300);
setLayout(null);
setVisible(true);

public void actionPerformed(ActionEvent e){


tf.setText("Welcome");
}

public static void main(String args[]) {


AEvent awt_obj = new AEvent();
}
}

AWT Layout Manager


Layout means the arrangement of components within the container. In other way we can say that
placing the components at a particular position within the container. The task of layouting the controls
is done automatically by the Layout Manager.

81 | P a g e
Java Programming

Layout Manager
The layout manager automatically positions all the components within the container. If we do not use
layout manager then also the components are positioned by the default layout manager. It is possible
to layout the controls by hand but it becomes very difficult because of the following two reasons.
 It is very tedious to handle a large number of controls within the container.
 Oftenly the width and height information of a component is not given when we need to arrange
them.
Java provide us with various layout manager to position the controls. The properties like size,shape
and arrangement varies from one layout manager to other layout manager. When the size of the
applet or the application window changes the size, shape and arrangement of the components also
changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the
application window.
The layout manager is associated with every Container object. Each layout manager is an object of
the class that implements the LayoutManager interface.
Following are the interfaces defining functionalities of Layout Managers.

Sr. Interface & Description


No.

1
LayoutManager
The LayoutManager interface declares those methods which need to be
implemented by the class whose object will act as a layout manager.

2
LayoutManager2
The LayoutManager2 is the sub-interface of the LayoutManager.This
interface is for those classes that know how to layout containers based on
layout constraint object.

AWT Layout Manager Classes:


Following is the list of commonly used controls while designed GUI using AWT.

Sr. LayoutManager & Description


No.

82 | P a g e
Java Programming

1
BorderLayout
The borderlayout arranges the components to fit in the five regions: east,
west, north, south and center.

2
CardLayout
The CardLayout object treats each component in the container as a card.
Only one card is visible at a time.

3
FlowLayout
The FlowLayout is the default layout.It layouts the components in a
directional flow.

4
GridLayout
The GridLayout manages the components in form of a rectangular grid.

5
GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout
aligns the component vertically,horizontally or along their baseline without
requiring the components of same size.

BorderLayout Manager
When you add a component to the layout, you must specify which area to place it in. BorderLayout
is one of the more unusual layouts provided. It is the default layout for Window, along with its
children, Frame and Dialog. BorderLayout provides 5 areas to hold components. These areas are
named after the four different borders of the screen, North, South, East, and West, with any

83 | P a g e
Java Programming
remaining space going into the Center area. The order in which components are added to the
screen is not important, although you can have only one component in each area. The following
shows a BorderLayout that has one button in each area, before and after resizing.

import java.awt.*;

import java.awt.event.*;

public class BLExample

public static void main(String[] args)

Frame frame= new Frame("BorderLayout Frame");

frame.add(pa);

Panel pa= new Panel();

pa.setLayout(new BorderLayout());
pa.add(new Button("India"), BorderLayout.NORTH);
pa.add(new Button("USA"), BorderLayout.SOUTH);
pa.add(new Button("Japan"), BorderLayout.EAST);
pa.add(new Button("China"), BorderLayout.WEST);
pa.add(new Button("Countries"), BorderLayout.CENTER);

frame.setSize(300,300);

frame.setVisible(true);

});

Output

84 | P a g e
Java Programming

USA

Displaying Image in Applet AWT


Applet is mostly used in games and animation. For this purpose image is required to be displayed.
The java.awt.Graphics class provide a method drawImage() to display the image.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax:

public Image getImage(URL u, String image){}


Other required methods of Applet class to display image:
1. public URL getDocumentBase(): is used to return the URL of the document in which applet is
embedded.
2. public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:


import java.awt.*;
import java.applet.*;

85 | P a g e
Java Programming
public class DisplayImage extends Applet
{
Image picture;
public void init()
{
picture = getImage(getDocumentBase(),"desktop.jpg");
}
public void paint(Graphics g)
{
g.drawImage(picture, 30,30, this);
}
}

In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument
of drawImage() method of is ImageObserver object. The Component class implements ImageObserver
interface. So current class object would also be treated as ImageObserver because Applet class indirectly
extends the Component class.

myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

Output :

86 | P a g e
Java Programming

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width
and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default
color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used
to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the specified font.

Example of Graphics in applet:


import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);

87 | P a g e
Java Programming
g.fillArc(270,150,30,30,0,180);

}
}

myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

Output:

Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be moved.

Example of animation in applet:


import java.awt.*;
import java.applet.*;
public class AppletAnimationDemo extends Applet {

Image picture;

public void init() {


picture =getImage(getDocumentBase(),"bike_1.gif");
}

88 | P a g e
Java Programming
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);

try{Thread.sleep(100);}catch(Exception e){}
}
}
}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument
of drawImage() method of is ImageObserver object. The Component class implements ImageObserver
interface. So current class object would also be treated as ImageObserver because Applet class indirectly
extends the Component class.

myapplet.html
<html>
<body>
<applet code=" AppletAnimationDemo.class" width="300" height="300">
</applet>
</body>
</html>

Output

89 | P a g e
Java Programming

Play sound using Applet?

demonstrates how to play a sound using an applet image using getAudioClip(), play() & stop()
methods of AudioClip() class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class AppletSoundDemo extends Applet implements ActionListener {


Button play,stop;
AudioClip audioClip;

public void init() {


play = new Button(" Play in Loop ");
add(play);
play.addActionListener(this);
stop = new Button(" Stop ");
add(stop);
stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(), "Sound.wav");
}
public void actionPerformed(ActionEvent ae) {
Button source = (Button)ae.getSource();
if (source.getLabel() == " Play in Loop ") {
audioClip.play();
} else if(source.getLabel() == " Stop "){
audioClip.stop();
}
}
}
The above code sample will produce the following result in a java enabled web browser.
View in Browser.

HTML Page

Output
<html>
<body>
<applet code="AppletSoundDemo.class" width="300" height="300">
</applet>
</body>
</html>

90 | P a g e
Java Programming

91 | P a g e
Java Programming

Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content.
It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac
Os etc.

Drawback of Applet
 Plugin is required at client browser to execute applet.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which
is the subclass of Component.

Lifecycle of Java Applet


1. Applet is initialized.

92 | P a g e
Java Programming
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object
that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

93 | P a g e
Java Programming

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

Note: class must be public because its object is created by Java Plugin software that resides
on the browser.

myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and
compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing
purpose only.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }

94 | P a g e
Java Programming
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

………………………………………………………………………………………………………………………………….

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with
the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with
the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between
the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

Example of Graphics in applet:


import java.applet.Applet;
import java.awt.*;

95 | P a g e
Java Programming
public class GraphicsDemo extends Applet{

public void paint(Graphics g){


g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

……………………………………………………………………………………………………………..

Displaying Image in Applet


Applet is mostly used in games and animation. For this purpose image is required to be displayed. The
java.awt.Graphics class provide a method drawImage() to display the image.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax:

1. public Image getImage(URL u, String image){}

Other required methods of Applet class to display image:


1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.

96 | P a g e
Java Programming

2. public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:


import java.awt.*;
import java.applet.*;

public class DisplayImage extends Applet {

Image picture;

public void init() {


picture = getImage(getDocumentBase(),"sonoo.jpg");
}

public void paint(Graphics g) {


g.drawImage(picture, 30,30, this);
}

}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th
argument of drawImage() method of is ImageObserver object. The Component class implements
ImageObserver interface. So current class object would also be treated as ImageObserver because
Applet class indirectly extends the Component class.

myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

………………………………………………………………………………………………………..

Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be moved.

97 | P a g e
Java Programming

Example of animation in applet:


import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {

Image picture;

public void init() {


picture =getImage(getDocumentBase(),"bike_1.gif");
}

public void paint(Graphics g) {


for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);

try{Thread.sleep(100);}catch(Exception e){}
}
}
}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th
argument of drawImage() method of is ImageObserver object. The Component class implements
ImageObserver interface. So current class object would also be treated as ImageObserver because
Applet class indirectly extends the Component class.

myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

……………………………………………………………………………………………………………………

JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The
JApplet class extends the Applet class.

Example of EventHandling in JApplet:


import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
98 | P a g e
Java Programming
JButton b;
JTextField tf;
public void init(){

tf=new JTextField();
tf.setBounds(30,40,150,20);

b=new JButton("Click");
b.setBounds(80,150,70,40);

add(b);add(tf);
b.addActionListener(this);

setLayout(null);
}

public void actionPerformed(ActionEvent e){


tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is invoked only
once.

myapplet.html
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>

………………………………………………………………………………………………………………….

Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.

Example of Painting in Applet:


1. import java.awt.*;
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet implements MouseMotionListener{
5.
6. public void init(){
7. addMouseMotionListener(this);
8. setBackground(Color.red);

99 | P a g e
Java Programming
9. }
10.
11. public void mouseDragged(MouseEvent me){
12. Graphics g=getGraphics();
13. g.setColor(Color.white);
14. g.fillOval(me.getX(),me.getY(),5,5);
15. }
16. public void mouseMoved(MouseEvent me){}
17.
18. }
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis
and y-axis. The getGraphics() method of Component class returns the object of Graphics.

myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

……………………………………………………………………………………

Digital clock in Applet


Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's see the simple
example:

Example of Digital clock in Applet:


1. import java.applet.*;
2. import java.awt.*;
3. import java.util.*;
4. import java.text.*;
5.
6. public class DigitalClock extends Applet implements Runnable {
7.
8. Thread t = null;
9. int hours=0, minutes=0, seconds=0;
10. String timeString = "";
11.
12. public void init() {
13. setBackground( Color.green);
14. }
15.
100 | P a g e
Java Programming
16. public void start() {
17. t = new Thread( this );
18. t.start();
19. }
20.
21.
22. public void run() {
23. try {
24. while (true) {
25.
26. Calendar cal = Calendar.getInstance();
27. hours = cal.get( Calendar.HOUR_OF_DAY );
28. if ( hours > 12 ) hours -= 12;
29. minutes = cal.get( Calendar.MINUTE );
30. seconds = cal.get( Calendar.SECOND );
31.
32. SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
33. Date date = cal.getTime();
34. timeString = formatter.format( date );
35.
36. repaint();
37. t.sleep( 1000 ); // interval given in milliseconds
38. }
39. }
40. catch (Exception e) { }
41. }
42.
43.
44. public void paint( Graphics g ) {
45. g.setColor( Color.blue );
46. g.drawString( timeString, 50, 50 );
47. }
48. }
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis
and y-axis. The getGraphics() method of Component class returns the object of Graphics.

myapplet.html
1. <html>
2. <body>
3. <applet code="DigitalClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

……………………………………………………………………

Analog clock in Applet


101 | P a g e
Java Programming

Analog clock can be created by using the Math class. Let's see the simple example:

Example of Analog clock in Applet:


1. import java.applet.*;
2. import java.awt.*;
3. import java.util.*;
4. import java.text.*;
5.
6. public class MyClock extends Applet implements Runnable {
7.
8. int width, height;
9. Thread t = null;
10. boolean threadSuspended;
11. int hours=0, minutes=0, seconds=0;
12. String timeString = "";
13.
14. public void init() {
15. width = getSize().width;
16. height = getSize().height;
17. setBackground( Color.black );
18. }
19.
20. public void start() {
21. if ( t == null ) {
22. t = new Thread( this );
23. t.setPriority( Thread.MIN_PRIORITY );
24. threadSuspended = false;
25. t.start();
26. }
27. else {
28. if ( threadSuspended ) {
29. threadSuspended = false;
30. synchronized( this ) {
31. notify();
32. }
33. }
34. }
35. }
36.
37. public void stop() {
38. threadSuspended = true;
39. }
40.
41. public void run() {
42. try {
43. while (true) {
44.
45. Calendar cal = Calendar.getInstance();
46. hours = cal.get( Calendar.HOUR_OF_DAY );
47. if ( hours > 12 ) hours -= 12;
48. minutes = cal.get( Calendar.MINUTE );

102 | P a g e
Java Programming
49. seconds = cal.get( Calendar.SECOND );
50.
51. SimpleDateFormat formatter
52. = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
53. Date date = cal.getTime();
54. timeString = formatter.format( date );
55.
56. // Now the thread checks to see if it should suspend itself
57. if ( threadSuspended ) {
58. synchronized( this ) {
59. while ( threadSuspended ) {
60. wait();
61. }
62. }
63. }
64. repaint();
65. t.sleep( 1000 ); // interval specified in milliseconds
66. }
67. }
68. catch (Exception e) { }
69. }
70.
71. void drawHand( double angle, int radius, Graphics g ) {
72. angle -= 0.5 * Math.PI;
73. int x = (int)( radius*Math.cos(angle) );
74. int y = (int)( radius*Math.sin(angle) );
75. g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
76. }
77.
78. void drawWedge( double angle, int radius, Graphics g){
79. angle -= 0.5 * Math.PI;
80. int x = (int)( radius*Math.cos(angle) );
81. int y = (int)( radius*Math.sin(angle) );
82. angle += 2*Math.PI/3;
83. int x2 = (int)( 5*Math.cos(angle) );
84. int y2 = (int)( 5*Math.sin(angle) );
85. angle += 2*Math.PI/3;
86. int x3 = (int)( 5*Math.cos(angle) );
87. int y3 = (int)( 5*Math.sin(angle) );
88. g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
89. g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
90. g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
91. }
92.
93. public void paint( Graphics g ) {
94. g.setColor( Color.gray );
95. drawWedge( 2*Math.PI * hours / 12, width/5, g );
96. drawWedge( 2*Math.PI * minutes / 60, width/3, g );
97. drawHand( 2*Math.PI * seconds / 60, width/2, g );
98. g.setColor( Color.white );
99. g.drawString( timeString, 10, height-10 );
100. }
101. }

103 | P a g e
Java Programming

myapplet.html
1. <html>
2. <body>
3. <applet code="MyClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

…………………………………………………………………………………………….

Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class provides
a method named getParameter(). Syntax:

1. public String getParameter(String parameterName)

Example of using parameter in Applet:

1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>

…………………………………………………………………………………………………………….

104 | P a g e
Java Programming

Applet Communication
java.applet.AppletContext class provides the facility of communication between applets. We provide the
name of applet through the HTML file. It provides getApplet() method that returns the object of Applet.
Syntax:

1. public Applet getApplet(String name){}

Example of Applet Communication


1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class ContextApplet extends Applet implements ActionListener{
5. Button b;
6.
7. public void init(){
8. b=new Button("Click");
9. b.setBounds(50,50,60,50);
10.
11. add(b);
12. b.addActionListener(this);
13. }
14.
15. public void actionPerformed(ActionEvent e){
16.
17. AppletContext ctx=getAppletContext();
18. Applet a=ctx.getApplet("app2");
19. a.setBackground(Color.yellow);
20. }
21. }
myapplet.html
1. <html>
2. <body>
3. <applet code="ContextApplet.class" width="150" height="150" name="app1">
4. </applet>
5.
6. <applet code="First.class" width="150" height="150" name="app2">
7. </applet>
8. </body>
9. </html>

105 | P a g e
Java Programming

Servlets
Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a request coming from a Web browser or other HTTP client and
databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in comparison
with the CGI.
 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software via the sockets and RMI mechanisms that you
have seen already.

Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.

Servlets Tasks:
Servlets perform the following major tasks:
 Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes telling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
106 | P a g e
Java Programming

Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports
the Java Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.httppackages,
which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of writing
this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any other Java class. After you
install the servlet packages and add them to your computer's Classpath, you can
compile servlets with the JDK's Java compiler or any other current compiler.

Servlet Life Cycle


can be defined as the entire process from its creation till the destruction. The following
are the paths followed by a servlet
 The servlet is initialized by calling the init () method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.

The init() method :


The init method is designed to be called only once. It is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time
initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.
107 | P a g e
Java Programming
Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGe,
doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with
service() method but you override either doGet() or doPost() depending on what type
of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service
request. Here is the signature of these two methods.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has
no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() method :


The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this:
public void destroy() {
// Finalization code...
}

108 | P a g e
Java Programming

Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.
 First the HTTP requests coming to the server are delegated to the servlet container.
 The servlet container loads the servlet before invoking the service() method.
 Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
Servlets are Java classes which service HTTP requests and implement
thejavax.servlet.Servlet interface. Web application developers typically
writeservlets that extend javax.servlet.http.HttpServlet, an abstract class that
implements the Servlet interface and is specially designed to handle HTTP requests.

Sample Code for Hello World:


Following is the sample source code structure of a servlet example to write Hello World:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException


{
// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy()


{
// do nothing.
}
}

109 | P a g e
Java Programming

Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel
(Windows) or /usr/ServletDevel (Unix) then you would need to add these directories
as well in CLASSPATH.
Assuming your environment is setup properly, go in ServletDevel directory and
compile HelloWorld.java as follows:
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on
your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not
using any other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work
properly, you have to include the location of the Java SDK that you are using in the
PATH environment variable.
If everything goes fine, above compilation would produce HelloWorld.class file in the
same directory. Next section would explain how a compiled servlet would be deployed
in production.

Servlet Deployment:
By default, a servlet application is located at the path <Tomcat-installation-
directory>/webapps/ROOT and the class file would reside in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet
class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes and create following entries
inweb.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in web.xml
file. There could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-installation-
directory>\bin\startup.bat (on windows) or <Tomcat-installation-
directory>/bin/startup.sh (on Linux/Solaris etc.) and finally
typehttp://localhost:8080/HelloWorld in browser's address box. If everything
goes fine, you would get following result:

110 | P a g e
Java Programming

JSP
JavaServer Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based applications.
JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases.

avaServer Pages (JSP) is a technology for developing web pages that support dynamic
content which helps developers insert java code in HTML pages by making use of special
JSP tags, most of which start with <% and end with %>.

A JavaServer Pages component is a type of Java servlet that is designed to fulfill the
role of a user interface for a Java web application. Web developers write JSPs as text
files that combine HTML or XHTML code, XML elements, and embedded JSP actions and
commands.

Advantages of JSP:
Following is the list of other advantages of using JSP over other technologies:

 vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part
is written in Java, not Visual Basic or other MS specific language, so it is more powerful and
easier to use. Second, it is portable to other operating systems and non-Microsoft Web
servers.

 vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML.

 vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for
"real" programs that use form data, make database connections, and the like.

 vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image
processing etc.

 vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.

111 | P a g e
Java Programming

Architecture
The web server needs a JSP engine ie. container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes use
of Apache which has built-in JSP container to support JSP pages development.

A JSP container works with the Web server to provide the runtime environment and
other services a JSP needs. It knows how to understand the special elements that are
part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web
Application.

JSP Processing:
The following steps explain how the web server creates the web page using JSP:

 As with a normal page, your browser sends an HTTP request to the web server.

 The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.

 The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and
all JSP elements are converted to Java code that implements the corresponding dynamic
behavior of the page.

112 | P a g e
Java Programming

 The JSP engine compiles the servlet into an executable class and forwards the original request
to a servlet engine.

 A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format, which the servlet engine
passes to the web server inside an HTTP response.

 The web server forwards the HTTP response to your browser in terms of static HTML content.

 Finally web browser handles the dynamically generated HTML page inside the HTTP response
exactly as if it were a static page.

All the above mentioned steps can be shown below in the following diagram:

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists
and whether the modification date on the JSP is older than the servlet. If the JSP is
older than its generated servlet, the JSP container assumes that the JSP hasn't changed
and that the generated servlet still matches the JSP's contents. This makes the process
more efficient than with other scripting languages (such as PHP) and therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having to
be a Java programming wiz. Except for the translation phase, a JSP page is handled
exactly like a regular servlet

Life cycle
113 | P a g e
Java Programming

The key to understanding the low-level functionality of JSP is to understand the simple
life cycle they follow.

A JSP life cycle can be defined as the entire process from its creation till the destruction
which is similar to a servlet life cycle with an additional step which is required to compile
a JSP into servlet.

The following are the paths followed by a JSP

 Compilation

 Initialization

 Execution

 Cleanup

The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they
are as follows:

JSP Compilation:

114 | P a g e
Java Programming

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified
since it was last compiled, the JSP engine compiles the page.

The compilation process involves three steps:

 Parsing the JSP.

 Turning the JSP into a servlet.

 Compiling the servlet.

JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override the jspInit()
method:

public void jspInit(){

// Initialization code...

Typically initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the
jspInit method.

JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.

Whenever a browser requests a JSP and the page has been loaded and initialized, the
JSP engine invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and


anHttpServletResponse as its parameters as follows:

void _jspService(HttpServletRequest request,

HttpServletResponse response)

// Service handling code...

115 | P a g e
Java Programming

The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also responsible for
generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.

JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy when you need to perform any cleanup, such as releasing database
connections or closing open files.

The jspDestroy() method has the following form:

public void jspDestroy()

// Your cleanup code goes here.

JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code
later in the JSP file. You must declare the variable or method before you use it in the
JSP file.

Following is the syntax of JSP Declarations:

<%! declaration; [ declaration; ]+ ... %>

You can write XML equivalent of the above syntax as follows:

<jsp:declaration>

code fragment

</jsp:declaration>

Following is the simple example for JSP Declarations:

116 | P a g e
Java Programming

<%! int i = 0; %>

<%! int a, b, c; %>

<%! Circle a = new Circle(2.0); %>

JSP Expression:
A JSP expression element contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file.

Because the value of an expression is converted to a String, you can use an expression
within a line of text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java
Language Specification but you cannot use a semicolon to end an expression.

Following is the syntax of JSP Expression:

<%= expression %>

You can write XML equivalent of the above syntax as follows:

<jsp:expression>

expression

</jsp:expression>

Following is the simple example for JSP Expression:

<html>

<head><title>A Comment Test</title></head>

<body>

<p>

Today's date: <%= (new java.util.Date()).toLocaleString()%>

</p>

</body>

</html>

This would generate following result:

Today's date: 11-Sep-2010 21:24:25

117 | P a g e
Java Programming

JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out" part of your JSP page.

Following is the syntax of JSP comments:

<%-- This is JSP comment --%>

Following is the simple example for JSP Comments:

<html>

<head><title>A Comment Test</title></head>

<body>

<h2>A Test of Comments</h2>

<%-- This comment will not be visible in the page source --%>

</body>

</html>

This would generate following result:

A Test of Comments

There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially. Here's a summary:

Syntax Purpose

<%-- comment --%> A JSP comment. Ignored by the JSP engine.

<!-- comment --> An HTML comment. Ignored by the browser.

<\% Represents static <% literal.

118 | P a g e
Java Programming

%\> Represents static %> literal.

\' A single quote in an attribute that uses single quotes.

\" A double quote in an attribute that uses double quotes.

JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the
following form:

<%@ directive attribute="value" %>

There are three types of directive tag:

Directive Description

<%@ page ... %> Defines page-dependent attributes, such as scripting


language, error page, and buffering requirements.

<%@ include ... %> Includes a file during the translation phase.

<%@ taglib ... %> Declares a tag library, containing custom actions, used in
the page

We would explain JSP directive in separate chapter JSP - Directives

JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine.
You can dynamically insert a file, reuse JavaBeans components, forward the user to
another page, or generate HTML for the Java plugin.

There is only one syntax for the Action element, as it conforms to the XML standard:

<jsp:action_name attribute="value" />

Action elements are basically predefined functions and there are following JSP actions
available:
119 | P a g e
Java Programming

Syntax Purpose

jsp:include Includes a file at the time the page is requested

jsp:useBean Finds or instantiates a JavaBean

jsp:setProperty Sets the property of a JavaBean

jsp:getProperty Inserts the property of a JavaBean into the output

jsp:forward Forwards the requester to a new page

jsp:plugin Generates browser-specific code that makes an OBJECT


or EMBED tag for the Java plugin

jsp:element Defines XML elements dynamically.

jsp:attribute Defines dynamically defined XML element's attribute.

jsp:body Defines dynamically defined XML element's body.

jsp:text Use to write template text in JSP pages and documents.

We would explain JSP actions in separate chapter JSP - Actions

JSP Implicit Objects:


JSP supports nine automatically defined variables, which are also called implicit objects.
These variables are:

Objects Description

request This is the HttpServletRequest object associated with


the request.

120 | P a g e
Java Programming

response This is the HttpServletResponse object associated with


the response to the client.

out This is the PrintWriter object used to send output to the


client.

session This is the HttpSession object associated with the


request.

application This is the ServletContext object associated with


application context.

config This is the ServletConfig object associated with the


page.

pageContext This encapsulates use of server-specific features like


higher performance JspWriters.

page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.

Exception The Exception object allows the exception data to be


accessed by designated JSP.

We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.

Control-Flow Statements:
JSP provides full power of Java to be embedded in your web application. You can use
all the APIs and building blocks of Java in your JSP programming including decision
making statements, loops etc.

Decision-Making Statements:
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at
each line with HTML text included between Scriptlet tags.

<%! int day = 3; %>

<html>

121 | P a g e
Java Programming

<head><title>IF...ELSE Example</title></head>

<body>

<% if (day == 1 | day == 7) { %>

<p> Today is weekend</p>

<% } else { %>

<p> Today is not weekend</p>

<% } %>

</body>

</html>

This would produce following result:

Today is not weekend

Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside Scriptletas:

<%! int day = 3; %>

<html>

<head><title>SWITCH...CASE Example</title></head>

<body>

<%

switch(day) {

case 0:

out.println("It\'s Sunday.");

break;

case 1:

out.println("It\'s Monday.");

break;

case 2:

out.println("It\'s Tuesday.");

break;

case 3:

out.println("It\'s Wednesday.");

122 | P a g e
Java Programming

break;

case 4:

out.println("It\'s Thursday.");

break;

case 5:

out.println("It\'s Friday.");

break;

default:

out.println("It's Saturday.");

%>

</body>

</html>

This would produce following result:

It's Wednesday.

Loop Statements:
You can also use three basic types of looping blocks in Java: for, while,and
do…while blocks in your JSP programming.

Let us look at the following for loop example:

<%! int fontSize; %>

<html>

<head><title>FOR LOOP Example</title></head>

<body>

<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>

<font color="green" size="<%= fontSize %>">

JSP Tutorial

</font><br />

<%}%>

</body>

123 | P a g e
Java Programming

</html>

This would produce following result:

JSP Tutorial

JSP Tutorial

JSP Tutorial

Above example can be written using while loop as follows:

<%! int fontSize; %>

<html>

<head><title>WHILE LOOP Example</title></head>

<body>

<%while ( fontSize <= 3){ %>

<font color="green" size="<%= fontSize %>">

JSP Tutorial

</font><br />

<%fontSize++;%>

<%}%>

</body>

</html>

This would also produce following result:

JSP Tutorial

JSP Tutorial

124 | P a g e
Java Programming

JSP Tutorial

JSP Operators:
JSP supports all the logical and arithmetic operators supported by Java. Following table
give a list of all the operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom.

Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

125 | P a g e
Java Programming

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

JSP Literals:
The JSP expression language defines the following literals:

 Boolean: true and false

 Integer: as in Java

 Floating point: as in Java

 String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped
as \\.

 Null: null

126 | P a g e

You might also like