Download as pdf or txt
Download as pdf or txt
You are on page 1of 179

Unit-11

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs


in a single thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

o Each process has an address in memory. In other words, each process allocates
a separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

o Threads share the same address space.


o A thread is lightweight.
o Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate
path of execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and
one process can have multiple threads.

Note: At a time one thread is executed only.


Java Thread class
Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in
the new state, the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the
active state. The active state contains two states within it: one is runnable, and the
other is running.

o Runnable: A thread, that is ready to run is then moved to the runnable state. In
the runnable state, the thread may be running or may be ready to run at any
given instant of time. It is the duty of the thread scheduler to provide the thread
time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and when
that allocated time slice is over, the thread voluntarily gives up the CPU to the
other thread, so that the other threads can also run for their slice of time.
Whenever such a scenario occurs, all those threads that are willing to run,
waiting for their turn to run, lie in the runnable state. In the runnable state, there
is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the
running state. Generally, the most common change in the state of a thread is
from runnable to running and again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not
permanently) then, either the thread is in the blocked state or is in the waiting state.

For example, a thread (let's say its name is A) may want to print some data from the
printer. However, at the same time, the other thread (let's say its name is B) is using
the printer to print some data. Therefore, thread A has to wait for thread B to use the
printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable
to perform any execution and thus never consume any cycle of the Central Processing
Unit (CPU). Hence, we can say that thread A remains idle until the thread scheduler
reactivates thread A, which is in the waiting or blocked state.

When the main thread invokes the join() method then, it is said that the main thread
is in the waiting state. The main thread then waits for the child threads to complete
their tasks. When the child threads complete their job, a notification is sent to the main
thread, which again moves the thread from waiting to the active state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the
thread scheduler to determine which thread to choose and which one to reject, and
the chosen thread is then given the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing to leave that
critical section. In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting state is given to
thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait state. After the
time runs out, the thread wakes up and start its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead thread.

The following diagram shows the different states involved in the life cycle of a thread.
Implementation of Thread States
In Java, one can get the current state of a thread using the Thread.getState() method.
The java.lang.Thread.State class of Java provides the constants ENUM to represent
the state of a thread. These constants are:

1. public static final Thread.State NEW

It represents the first state of a thread that is the NEW state.

1. public static final Thread.State RUNNABLE

It represents the runnable state.It means a thread is waiting in the queue to run.

1. public static final Thread.State BLOCKED

It represents the blocked state. In this state, the thread is waiting to acquire a lock.

1. public static final Thread.State WAITING

It represents the waiting state. A thread will go to this state when it invokes the
Object.wait() method, or Thread.join() method with no timeout. A thread in the waiting
state is waiting for another thread to complete its task.

1. public static final Thread.State TIMED_WAITING

It represents the timed waiting state. The main difference between waiting and timed
waiting is the time constraint. Waiting has no time constraint, whereas timed waiting
has the time constraint. A thread invoking the following method reaches the timed
waiting state.
o sleep
o join with timeout
o wait with timeout
o parkUntil
o parkNanos

1. public static final Thread.State TERMINATED

It represents the final state of a thread that is terminated or dead. A terminated thread
means it has completed its execution.

class ABC implements Runnable


{
public void run()
{

// try-catch block
try
{
// moving thread t2 to the state timed waiting
Thread.sleep(100);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}

System.out.println("The state of thread t1 while it invoked the method join() o


n thread t2 -"+ ThreadState.t1.getState());

// try-catch block
try
{
1. Thread.sleep(200);
2. }
3. catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
// ThreadState class implements the interface Runnable
public class ThreadState implements Runnable
{
public static Thread t1;
public static ThreadState obj;

// main method
public static void main(String argvs[])
{
// creating an object of the class ThreadState

obj = new ThreadState();


t1 = new Thread(obj);

// thread t1 is spawned
// The thread t1 is currently in the NEW state.
System.out.println("The state of thread t1 after spawning it - " + t1.getState());

/ invoking the start() method on


// the thread t1
t1.start();

// thread t1 is moved to the Runnable state


System.out.println("The state of thread t1 after invoking the method start() on
it - " + t1.getState());
}

public void run()


{
ABC myObj = new ABC();
Thread t2 = new Thread(myObj);
// thread t2 is created and is currently in the NEW state.
System.out.println("The state of thread t2 after spawning it - "+ t2.getState());
t2.start();

// thread t2 is moved to the runnable state


System.out.println("the state of thread t2 after calling the method start() on it-
" + t2.getState());

/ try-catch block for the smooth flow of the program


try
{
// moving the thread t1 to the state timed waiting
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}

System.out.println("The state of thread t2 after invoking the method sleep() on


it - "+ t2.getState() );

// try-catch block for the smooth flow of the program


try
{
// waiting for thread t2 to complete its execution
t2.join();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 when it has completed it's execution - "
+ t2.getState());
}

}
Java Threads | How to create a thread in Java
There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on
a thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.

Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
1. public void run(): is used to perform action for a thread.

Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs
the following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class


FileName: Multi.java

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface


FileName: Multi3.java

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. t1.start();
10. }
11. }

Output:

thread is running...

If you are not extending the Thread class, your class object would not be treated as a
thread object. So you need to explicitly create the Thread class object. We are passing
the object of your class that implements Runnable so that your class run() method may
execute.

3) Using the Thread Class: Thread(String Name)


We can directly use the Thread class to spawn new threads using the constructors
defined above.

FileName: MyThread1.java

1. public class MyThread1


2. {
3. // Main method
4. public static void main(String argvs[])
5. {
6. // creating an object of the Thread class using the constructor Thread(String n
ame)
7. Thread t= new Thread("My first thread");
8.
9. // the start() method moves the thread to the active state
10. t.start();
11. // getting the thread name by invoking the getName() method
12. String str = t.getName();
13. System.out.println(str);
14. }
15. }

Output:

My first thread
4) Using the Thread Class: Thread(Runnable r, String name)
Observe the following program.

FileName: MyThread2.java

1. public class MyThread2 implements Runnable


2. {
3. public void run()
4. {
5. System.out.println("Now the thread is running ...");
6. }
7.
8. // main method
9. public static void main(String argvs[])
10. {
11. // creating an object of the class MyThread2
12. Runnable r1 = new MyThread2();
13.
14. // creating an object of the class Thread using Thread(Runnable r, String name
)
15. Thread th1 = new Thread(r1, "My new thread");
16.
17. // the start() method moves the thread to the active state
18. th1.start();
19.
20. // getting the thread name by invoking the getName() method
21. String str = th1.getName();
22. System.out.println(str);
23. }
24. }

Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to
any shared resource.Java Synchronization is better option where we want to allow only
one thread to access the shared resource.

Why use Synchronization?


The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every
object has a lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock
implementations.

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent. Let's see the
example:

TestSynchronization1.java

• class Table{
• void printTable(int n){//method not synchronized
• for(int i=1;i<=5;i++){
• System.out.println(n*i);
• try{
• Thread.sleep(400);
• }catch(Exception e){System.out.println(e);}
• }

• }
• }

• class MyThread1 extends Thread{
• Table t;
• MyThread1(Table t){
• this.t=t;
• }
• public void run(){
• t.printTable(5);
• }

• }
• class MyThread2 extends Thread{
• Table t;
• MyThread2(Table t){
• this.t=t;
• }
• public void run(){
• t.printTable(100);
• }
• }

• class TestSynchronization1{
• public static void main(String args[]){
• Table obj = new Table();//only one object
• MyThread1 t1=new MyThread1(obj);
• MyThread2 t2=new MyThread2(obj);
• t1.start();
• t2.start();
• }
• }

Java Synchronized Method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

TestSynchronization2.java

• //example of java synchronized method


• class Table{
• synchronized void printTable(int n){//synchronized method
• for(int i=1;i<=5;i++){
• System.out.println(n*i);
• try{
• Thread.sleep(400);
• }catch(Exception e){System.out.println(e);}
• }

• }
• }

• class MyThread1 extends Thread{
• Table t;
• MyThread1(Table t){
• this.t=t;
• }
• public void run(){
• t.printTable(5);
• }

• }
• class MyThread2 extends Thread{
• Table t;
• MyThread2(Table t){
• this.t=t;
• }
• public void run(){
• t.printTable(100);
• }
• }

• public class TestSynchronization2{
• public static void main(String args[]){
• Table obj = new Table();//only one object
• MyThread1 t1=new MyThread1(obj);
• MyThread2 t2=new MyThread2(obj);
• t1.start();
• t2.start();
• }
• }

• Thread Scheduler in Java


• A component of Java that decides which thread to run or execute and which
thread to wait is called a thread scheduler in Java. In Java, a thread is only
chosen by a thread scheduler if it is in the runnable state. However, if there is
more than one thread in the runnable state, it is up to the thread scheduler to
pick one of the threads and ignore the other ones. There are some criteria that
decide which thread will execute first. There are two factors for scheduling a
thread i.e. Priority and Time of arrival
• Priority: Priority of each thread lies between 1 to 10. If a thread has a higher
priority, it means that thread has got a better chance of getting picked up by
the thread scheduler.
• Time of Arrival: Suppose two threads of the same priority enter the runnable
state, then priority cannot be the factor to pick a thread from these two threads.
In such a case, arrival time of thread is considered by the thread scheduler. A
thread that arrived first gets the preference over the other threads.
• Thread Scheduler Algorithms
• On the basis of the above-mentioned factors, the scheduling algorithm is
followed by a Java thread scheduler.

First Come First Serve Scheduling:


• In this scheduling algorithm, the scheduler picks the threads thar arrive first in
the runnable queue. Observe the following table:

Threads Time of Arrival

t1 0

t2 1

t3 2

t4 3

• In the above table, we can see that Thread t1 has arrived first, then Thread t2,
then t3, and at last t4, and the order in which the threads will be processed is
according to the time of arrival of threads.


• Hence, Thread t1 will be processed first, and Thread t4 will be processed last.
• Time-slicing scheduling:
• Usually, the First Come First Serve algorithm is non-preemptive, which is bad as
it may lead to infinite blocking (also known as starvation). To avoid that, some
time-slices are provided to the threads so that after some time, the running
thread has to give up the CPU. Thus, the other waiting threads also get time to
run their job.

• In the above diagram, each thread is given a time slice of 2 seconds. Thus, after
2 seconds, the first thread leaves the CPU, and the CPU is then captured by
Thread2. The same process repeats for the other threads too.
• Preemptive
• -Priority Scheduling:
• The name of the scheduling algorithm denotes that the algorithm is related to
the priority of the threads.


• Suppose there are multiple threads available in the runnable state. The thread
scheduler picks that thread that has the highest priority. Since the algorithm is
also preemptive, therefore, time slices are also provided to the threads to avoid
starvation. Thus, after some time, even if the highest priority thread has not
completed its job, it has to release the CPU because of preemption.
• Working of the Java Thread Scheduler


• Let's understand the working of the Java thread scheduler. Suppose, there are
five threads that have different arrival times and different priorities. Now, it is
the responsibility of the thread scheduler to decide which thread will get the
CPU first.
• The thread scheduler selects the thread that has the highest priority, and the
thread begins the execution of the job. If a thread is already in runnable state
and another thread (that has higher priority) reaches in the runnable state, then
the current thread is pre-empted from the processor, and the arrived thread
with higher priority gets the CPU time.
• When two threads (Thread 2 and Thread 3) having the same priorities and arrival
time, the scheduling will be decided on the basis of FCFS algorithm. Thus, the
thread that arrives first gets the opportunity to execute first.

2. Producer-Consumer Problem
Producer and Consumer are two separate processes. Both processes
share a common buffer or queue. The producer continuously produces
certain data and pushes it onto the buffer, whereas the consumer
consumes those data from the buffer.
Let's review a diagram showing this simple scenario:

Inherently, this problem has certain complexities to deal with:

• Both producer and consumer may try to update the queue at the
same time. This could lead to data loss or inconsistencies.
• Producers might be slower than consumers. In such cases, the
consumer would process elements fast and wait.
• In some cases, the consumer can be slower than a producer. This
situation leads to a queue overflow issue.
• In real scenarios, we may have multiple producers, multiple
consumers, or both. This may cause the same message to be
processed by different consumers.

The diagram below depicts a case with multiple producers and multiple
consumers:
We need to handle resource sharing and synchronization to solve a few
complexities:

• Synchronization on queue while adding and removing data


• On queue empty, the consumer has to wait until the producer
adds new data to the queue
• When the queue is full, the producer has to wait until the
consumer consumes data and the queue has some empty buffer

Daemon Thread in Java


Daemon thread in Java is a service provider thread that provides services to the user
thread. Its life depend on the mercy of user threads i.e. when all the user threads dies,
JVM terminates this thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

You can see all the detail by typing the jconsole in the command prompt. The jconsole
tool provides information about the loaded classes, memory usage, running threads
etc.

Points to remember for Daemon Thread in Java


o It provides services to user threads for background supporting tasks. It has no
role in life than to serve user threads.
o Its life depends on user threads.
o It is a low priority thread.

Why JVM terminates the daemon thread if there is no user


thread?
The sole purpose of the daemon thread is that it provides services to user thread for
background supporting task. If there is no user thread, why should JVM keep running
this thread. That is why JVM terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description

1) public void is used to mark the


setDaemon(boolean current thread as
status) daemon thread or user
thread.

2) public boolean is used to check that


isDaemon() current is daemon.

Simple example of Daemon thread in java


File: MyThread.java

• public class TestDaemonThread1 extends Thread{


• public void run(){
• if(Thread.currentThread().isDaemon()){//checking for daemon thread
• System.out.println("daemon thread work");
• }
• else{
• System.out.println("user thread work");
• }
• }
• public static void main(String[] args){
• TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
• TestDaemonThread1 t2=new TestDaemonThread1();
• TestDaemonThread1 t3=new TestDaemonThread1();

• t1.setDaemon(true);//now t1 is daemon thread

• t1.start();//starting threads
• t2.start();
• t3.start();
• }
• }

Selfish Threads
Our ball threads were well-behaved and gave each other a chance to run. They did this by calling
the sleep method to wait their turns. The sleep method blocks the thread and gives the
other threads an opportunity to be scheduled. Even if a thread does not want to put itself to sleep
for any amount of time, it can call yield() whenever it does not mind being interrupted. A
thread should always call sleep or yield when it is executing a long loop, to ensure that it is
not monopolizing the system. A thread that does not follow this rule is called selfish.
The following program shows what happens when a thread contains a tight loop, a loop in which
it carries out a lot of work without giving other threads a chance. When you click on the "Selfish"
button, a blue ball is launched whose run method contains a tight loop.

class BallThread extends Thread

. . .

public void run()

try

for (int i = 1; i <= 1000; i++)

b.move();

if (selfish)
{

// busy wait for 5 milliseconds

long t = System.currentTimeMillis();

while (System.currentTimeMillis() < t + 5)

else

sleep(5);

catch (InterruptedException exception)

. . .

private boolean selfish;

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.

What is Exception in Java


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not
be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling in Java

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked


Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyword Description

try The "try" keyword is used to specify a block


where we should place an exception code.
It means we can't use try block alone. The
try block must be followed by either catch
or finally.

catch The "catch" block is used to handle the


exception. It must be preceded by try block
which means we can't use catch block
alone. It can be followed by finally block
later.

finally The "finally" block is used to execute the


necessary code of the program. It is
executed whether an exception is handled
or not.

throw The "throw" keyword is used to throw an


exception.
throws The "throws" keyword is used to declare
exceptions. It specifies that there may occur
an exception in the method. It doesn't
throw an exception. It is always used with
method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.

JavaExceptionExample.java

• public class JavaExceptionExample{


• public static void main(String args[]){
• try{
• //code that may raise exception
• int data=100/0;
• }catch(ArithmeticException e){System.out.println(e);}
• //rest code of the program
• System.out.println("rest of the code...");
• }
• }

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
o 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.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
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).

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.

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

• public void paint(Graphics g){
• g.drawString("welcome to applet",150,150);
• }

• }
• /*
• <applet code="First.class" width="300" height="300">
• </applet>
• */

HTML <applet> tag (Not supported in HTML5)


HTML <applet> tag was used to embed the Java applet in an HTML document. This
element has been deprecated in HTML 4.0 and instead of it we can use <object> and
newly added element <embed>.

The use of Java applet is also deprecated, and most browsers do not support the use
of plugins.

Note: The <applet> tag is deprecated in HTML4.0 and not supported in HTML5. So you
can use <object> tag or <embed> tag instead of <applet>.

Syntax

1. <applet code="URL" height="200" width="100">.............</applet>

Following are some specifications about <applet> tag

Display Block

Start tag/End tag Both Start tag and End tag

Usage Embed Applets

Example

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Applet Tag</title>
5. </head>
6. <body>
7. <p>Example of Applet Tag</p>
8. <applet code="Shapes.class" align="right" height="200" width="300">
9. <b>Sorry! you need Java to see this</b>
10. </applet>
11. </body>
12. </html>

Unit 3
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations

We can perform file handling in Java by Java I/O API.

Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with
the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:

OutputStream
Java application uses an output stream to write data to a destination; it may be a file,
an array, peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.

Let's understand the working of Java OutputStream and InputStream by the figure
given below.

OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing
an output stream of bytes. An output stream accepts output bytes and sends them to
some sink.

Useful methods of OutputStream

Method Description

1) public void is used to write a byte to


write(int)throws the current output stream.
IOException
2) public void is used to write an array of
write(byte[])throws byte to the current output
IOException stream.

3) public void flush()throws flushes the current output


IOException stream.

4) public void is used to close the current


close()throws IOException output stream.

OutputStream Hierarchy

InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an
input stream of bytes.

Useful methods of InputStream

Method Description

1) public abstract int reads the next byte of data


read()throws from the input stream. It
IOException returns -1 at the end of the file.

2) public int returns an estimate of the


available()throws number of bytes that can be
IOException read from the current input
stream.
3) public void is used to close the current
close()throws input stream.
IOException

InputStream Hierarchy

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can also
read character-stream data. But, for reading streams of characters, it is recommended
to use FileReader class.

Java FileInputStream class declaration


Let's see the declaration for java.io.FileInputStream class:

1. public class FileInputStream extends InputStream

Java FileInputStream class methods

Method Description
int available() It is used to return the estimated
number of bytes that can be read
from the input stream.

int read() It is used to read the byte of data from


the input stream.

int read(byte[] b) It is used to read up to b.length bytes


of data from the input stream.

int read(byte[] b, It is used to read up to len bytes of


int off, int len) data from the input stream.

long skip(long x) It is used to skip over and discards x


bytes of data from the input stream.

FileChannel It is used to return the unique


getChannel() FileChannel object associated with
the file input stream.

FileDescriptor It is used to return


getFD() the FileDescriptor object.

protected void It is used to ensure that the close


finalize() method is call when there is no more
reference to the file input stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single


character
1. import java.io.FileInputStream;
2. public class DataStreamExample {
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. int i=fin.read();
7. System.out.print((char)i);
8.
9. fin.close();
10. }catch(Exception e){System.out.println(e);}
11. }
12. }

Note: Before running the code, a text file named as "testout.txt" is required to be
created. In this file, we are having following content:

Welcome to javatpoint.

After executing the above program, you will get a single character from the file which
is 87 (in byte form). To see the text, you need to convert it into character.

Output:

Java FileInputStream example 2: read all characters


• package com.javatpoint;

• import java.io.FileInputStream;
• public class DataStreamExample {
• public static void main(String args[]){
• try{
• FileInputStream fin=new FileInputStream("D:\\testout.txt");
• int i=0;
• while((i=fin.read())!=-1){
• System.out.print((char)i);
• }
• fin.close();
• }catch(Exception e){System.out.println(e);}
• }
• }

Java FileOutputStream Class


Java FileOutputStream is an output stream used for writing data to a file.

If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream class.
But, for character-oriented data, it is preferred to use FileWriter than
FileOutputStream.
FileOutputStream class declaration
Let's see the declaration for Java.io.FileOutputStream class:

1. public class FileOutputStream extends OutputStream

FileOutputStream class methods

Method Description

protected void It is used to clean up the connection


finalize() with the file output stream.

void write(byte[] It is used to write ary.length bytes


ary) from the byte array to the file
output stream.

void write(byte[] It is used to write len bytes from the


ary, int off, int len) byte array starting at offset off to
the file output stream.

void write(int b) It is used to write the specified byte


to the file output stream.

FileChannel It is used to return the file channel


getChannel() object associated with the file
output stream.

FileDescriptor It is used to return the file descriptor


getFD() associated with the stream.

void close() It is used to closes the file output


stream.

Java FileOutputStream Example 1: write byte


1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11. }

Output:

Success...

The content of a text file testout.txt is set with the data A.

testout.txt

Java FileOutputStream example 2: write string


• import java.io.FileOutputStream;
• public class FileOutputStreamExample {
• public static void main(String args[]){
• try{
• FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
• String s="Welcome to javaTpoint.";
• byte b[]=s.getBytes();//converting string into byte array
• fout.write(b);
• fout.close();
• System.out.println("success...");
• }catch(Exception e){System.out.println(e);}
• }
• }

java.io.PrintStream class
The PrintStream class provides methods to write data to another stream. The
PrintStream class automatically flushes the data so there is no need to call flush()
method. Moreover, its methods don't throw IOException.
Commonly used methods of PrintStream class
There are many methods in PrintStream class. Let's see commonly used methods of PrintStream
class:
o public void print(boolean b): it prints the specified boolean value.
o public void print(char c): it prints the specified char value.
o public void print(char[] c): it prints the specified character array values.
o public void print(int i): it prints the specified int value.
o public void print(long l): it prints the specified long value.
o public void print(float f): it prints the specified float value.
o public void print(double d): it prints the specified double value.
o public void print(String s): it prints the specified string value.
o public void print(Object obj): it prints the specified object value.
o public void println(boolean b): it prints the specified boolean value and terminates the line
o public void println(char c): it prints the specified char value and terminates the line.
o public void println(char[] c): it prints the specified character array values and terminates the
line.
o public void println(int i): it prints the specified int value and terminates the line.
o public void println(long l): it prints the specified long value and terminates the line.
o public void println(float f): it prints the specified float value and terminates the line.
o public void println(double d): it prints the specified double value and terminates the line.
o public void println(String s): it prints the specified string value and terminates the line./li>
o public void println(Object obj): it prints the specified object value and terminates the line.
o public void println(): it terminates the line only.
o public void printf(Object format, Object... args): it writes the formatted string to the
current stream.
o public void printf(Locale l, Object format, Object... args): it writes the formatted string to
the current stream.
o public void format(Object format, Object... args): it writes the formatted string to the
current stream using specified format.
o public void format(Locale l, Object format, Object... args): it writes the formatted string
to the current stream using specified format.
Example of java.io.PrintStream class
In this example, we are simply printing integer and string values.
• import java.io.*;
• class PrintStreamTest{
• public static void main(String args[])throws Exception{
• FileOutputStream fout=new FileOutputStream("mfile.txt");
• PrintStream pout=new PrintStream(fout);
• pout.println(1900);
• pout.println("Hello Java");
• pout.println("Welcome to Java");
• pout.close();
• fout.close();
• }
• }
download this PrintStream example

Example of printf() method of java.io.PrintStream class:

Let's see the simple example of printing integer value by format specifier.
• class PrintStreamTest{
• public static void main(String args[]){
• int a=10;
• System.out.printf("%d",a);//Note, out is the object of PrintStream class

• }
• }

Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file
behaves like a large array of bytes. There is a cursor implied to the array called
file pointer, by moving the cursor we do the read write operations. If end-of-file is
reached before the desired number of byte has been read than EOFException
is thrown. It is a type of IOException.

Constructor
Constructor Description

RandomAccessFile(File Creates a random access


file, String mode) file stream to read from,
and optionally to write to,
the file specified by the
File argument.

RandomAccessFile(String Creates a random access


name, String mode) file stream to read from,
and optionally to write to,
a file with the specified
name.

Method

Modifier Method Method


and Type

void close() It closes this random access file stream and releases
any system resources associated with the stream.

FileChannel getChannel() It returns the unique FileChannel object associated


with this file.

int readInt() It reads a signed 32-bit integer from this file.

String readUTF() It reads in a string from this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
void writeDouble(double It converts the double argument to a long using the
v) doubleToLongBits method in class Double, and then
writes that long value to the file as an eight-byte
quantity, high byte first.

void writeFloat(float v) It converts the float argument to an int using the


floatToIntBits method in class Float, and then writes
that int value to the file as a four-byte quantity, high
byte first.

void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.

Example
• import java.io.IOException;
• import java.io.RandomAccessFile;

• public class RandomAccessFileExample {
• static final String FILEPATH ="myFile.TXT";
• public static void main(String[] args) {
• try {
• System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
• writeToFile(FILEPATH, "I love my country and my people", 31);
• } catch (IOException e) {
• e.printStackTrace();
• }
• }
• private static byte[] readFromFile(String filePath, int position, int size)
• throws IOException {
• RandomAccessFile file = new RandomAccessFile(filePath, "r");
• file.seek(position);
• byte[] bytes = new byte[size];
• file.read(bytes);
• file.close();
• return bytes;
• }
• private static void writeToFile(String filePath, String data, int position)
• throws IOException {
• RandomAccessFile file = new RandomAccessFile(filePath, "rw");
• file.seek(position);
• file.write(data.getBytes());
• file.close();
• }
• }

The myFile.TXT contains text "This class is used for reading and writing to random
access file."

after running the program it will contains

This class is used for reading I love my country and my peoplele.

• CharacterStream Classes in Java


• The java.io package provides CharacterStream classes to overcome the
limitations of ByteStream classes, which can only handle the 8-bit bytes and is
not compatible to work directly with the Unicode characters. CharacterStream
classes are used to work with 16-bit Unicode characters. They can perform
operations on characters, char arrays and Strings.
• However, the CharacterStream classes are mainly used to read characters from
the source and write them to the destination. For this purpose, the
CharacterStream classes are divided into two types of classes, I.e., Reader class
and Writer class.
• Reader Class
• Reader class is used to read the 16-bit characters from the input stream.
However, it is an abstract class and can't be instantiated, but there are various
subclasses that inherit the Reader class and override the methods of the Reader
class. All methods of the Reader class throw an IOException. The subclasses of
the Reader class are given in the following table.

SN Class Description

1. BufferedReader This class provides methods to read characters from the buffer.

2. CharArrayReader This class provides methods to read characters from the char array.

3. FileReader This class provides methods to read characters from the file.

4. FilterReader This class provides methods to read characters from the


underlying character input stream.

5 InputStreamReader This class provides methods to convert bytes to characters.

6 PipedReader This class provides methods to read characters from the connected
piped output stream.

7 StringReader This class provides methods to read characters from a string.

• The Reader class methods are given in the following table.

SN Method Description
1 int read() This method returns the integral representation of the next
character present in the input. It returns -1 if the end of the input
is encountered.

2 int read(char This method is used to read from the specified buffer. It returns
buffer[]) the total number of characters successfully read. It returns -1 if
the end of the input is encountered.

3 int read(char This method is used to read the specified nChars from the buffer
buffer[], int loc, int at the specified location. It returns the total number of characters
nChars) successfully read.

4 void mark(int This method is used to mark the current position in the input
nchars) stream until nChars characters are read.

5 void reset() This method is used to reset the input pointer to the previous set
mark.

6 long skip(long This method is used to skip the specified nChars characters from
nChars) the input stream and returns the number of characters skipped.

7 boolean ready() This method returns a boolean value true if the next request of
input is ready. Otherwise, it returns false.

8 void close() This method is used to close the input stream. However, if the
program attempts to access the input, it generates IOException.

• Writer Class
• Writer class is used to write 16-bit Unicode characters to the output stream. The
methods of the Writer class generate IOException. Like Reader class, Writer class
is also an abstract class that cannot be instantiated; therefore, the subclasses of
the Writer class are used to write the characters onto the output stream. The
subclasses of the Writer class are given in the below table.

SN Class Description

1 BufferedWriter This class provides methods to write characters to the


buffer.

2 FileWriter This class provides methods to write characters to the file.


3 CharArrayWriter This class provides methods to write the characters to the
character array.

4 OutpuStreamWriter This class provides methods to convert from bytes to


characters.

5 PipedWriter This class provides methods to write the characters to the


piped output stream.

6 StringWriter This class provides methods to write the characters to the


string.

• To write the characters to the output stream, the Write class provides various
methods given in the following table.

SN Method Description

1 void write() This method is used to write the data to the output stream.

2 void write(int This method is used to write a single character to the output stream.
i)

3 Void This method is used to write the array of characters to the output
write(char stream.
buffer[])

4 void This method is used to write the nChars characters to the character
write(char array from the specified location.
buffer [],int
loc, int
nChars)

5 void close () This method is used to close the output stream. However, this
generates the IOException if an attempt is made to write to the output
stream after closing the stream.

6 void flush () This method is used to flush the output stream and writes the waiting
buffered characters.

Java BufferedReader Class


Java BufferedReader class is used to read the text from a character-based input stream.
It can be used to read data line by line by readLine() method. It makes the performance
fast. It inherits Reader class.

Java BufferedReader class declaration


Let's see the declaration for Java.io.BufferedReader class:

1. public class BufferedReader extends Reader

Java BufferedReader class constructors

Constructor Description

BufferedReader(Reader It is used to create a buffered


rd) character input stream that
uses the default size for an
input buffer.

BufferedReader(Reader It is used to create a buffered


rd, int size) character input stream that
uses the specified size for an
input buffer.

Java BufferedReader Example


In this example, we are reading the data from the text file testout.txt using Java
BufferedReader class.

• package com.javatpoint;
• import java.io.*;
• public class BufferedReaderExample {
• public static void main(String args[])throws Exception{
• FileReader fr=new FileReader("D:\\testout.txt");
• BufferedReader br=new BufferedReader(fr);

• int i;
• while((i=br.read())!=-1){
• System.out.print((char)i);
• }
• br.close();
• fr.close();
• }
• }

Java BufferedWriter Class


Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for
providing the efficient writing of single arrays, characters, and strings.

Class declaraction
Let's see the declaration for Java.io.BufferedWriter class:

1. public class BufferedWriter extends Writer

Class constructors

Constructor Description

BufferedWriter(Writer It is used to create a buffered character output stream that


wrt) uses the default size for an output buffer.

BufferedWriter(Writer It is used to create a buffered character output stream that


wrt, int size) uses the specified size for an output buffer.

Class methods

Method Description

void newLine() It is used to add a new line by writing a line separator.


void write(int c) It is used to write a single character.

void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.

void write(String s, int off, int len) It is used to write a portion of a string.

void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream

Example of Java BufferedWriter


Let's see the simple example of writing the data to a text file testout.txt using Java
BufferedWriter.

• package com.javatpoint;
• import java.io.*;
• public class BufferedWriterExample {
• public static void main(String[] args) throws Exception {
• FileWriter writer = new FileWriter("D:\\testout.txt");
• BufferedWriter buffer = new BufferedWriter(writer);
• buffer.write("Welcome to javaTpoint.");
• buffer.close();
• System.out.println("Success");
• }
• }

Java PrintWriter class


Java PrintWriter class is the implementation of Writer class. It is used to print the
formatted representation of objects to the text-output stream.

Class declaration
Let's see the declaration for Java.io.PrintWriter class:
1. public class PrintWriter extends Writer

Methods of PrintWriter class

Method Description

void println(boolean x) It is used to print the boolean value.

void println(char[] x) It is used to print an array of characters.

void println(int x) It is used to print an integer.

PrintWriter append(char c) It is used to append the specified character to the writer.

PrintWriter It is used to append the specified character sequence to the


append(CharSequence ch) writer.

PrintWriter It is used to append a subsequence of specified character to the


append(CharSequence ch, writer.
int start, int end)

boolean checkError() It is used to flushes the stream and check its error state.

protected void setError() It is used to indicate that an error occurs.

protected void clearError() It is used to clear the error state of a stream.

PrintWriter format(String It is used to write a formatted string to the writer using specified
format, Object... args) arguments and format string.

void print(Object obj) It is used to print an object.

void flush() It is used to flushes the stream.

void close() It is used to close the stream.

Java PrintWriter Example


Let's see the simple example of writing the data on a console and in a text file
testout.txt using Java PrintWriter class.

• package com.javatpoint;

• import java.io.File;
• import java.io.PrintWriter;
• public class PrintWriterExample {
• public static void main(String[] args) throws Exception {
• //Data to write on Console using PrintWriter
• PrintWriter writer = new PrintWriter(System.out);
• writer.write("Javatpoint provides tutorials of all technology.");
• writer.flush();
• writer.close();
• //Data to write in File using PrintWriter
• PrintWriter writer1 =null;
• writer1 = new PrintWriter(new File("D:\\testout.txt"));
• writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");

• writer1.flush();
• writer1.close();
• }
• }

Serialization and Deserialization in Java


Serialization in Java is a mechanism of writing the state of an object into a byte-
stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is


converted into an object. The serialization and deserialization process is platform-
independent, it means you can serialize an object on one platform and deserialize it
on a different platform.

For serializing the object, we call the writeObject() method


of ObjectOutputStream class, and for deserialization we call the readObject() method
of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization


It is mainly used to travel object's state on the network (that is known as marshalling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to
"mark" Java classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.

The Serializable interface must be implemented by the class whose object needs to
be persisted.

The String class and all the wrapper classes implement the java.io.Serializable interface
by default.

Let's see the example given below:

Student.java

• import java.io.Serializable;
• public class Student implements Serializable{
• int id;
• String name;
• public Student(int id, String name) {
• this.id = id;
• this.name = name;
• }
• }

Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute
the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API
uses JDBC drivers to connect with the database. There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We have discussed the above four drivers in the next chapter.

We can use JDBC API to access tabular data stored in any relational database. By the
help of JDBC API, we can save, update, delete and fetch data from the database. It is
like Open Database Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017.
It is based on the X/Open SQL Call Level Interface. The java.sql package contains
classes and interfaces for JDBC API. A list of popular interfaces of JDBC API are given
below:

o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

A list of popular classes of JDBC API are given below:

o DriverManager class
o Blob class
o Clob class
o Types class

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and execute the query with
the database. But, ODBC API uses ODBC driver which is written in C language (i.e.
platform dependent and unsecured). That is why Java has defined its own API (JDBC
API) that uses JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the
following activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of
thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that
you use JDBC drivers provided by the vendor of your database instead of the JDBC-
ODBC Bridge.

Advantages:

o easy to use.
o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.
Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written
in java.
Advantage:

o No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.

Disadvantages:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it
is known as thin driver. It is fully written in Java language.
Advantage:

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage:

o Drivers depend on the Database.

o DriverManager class
o The DriverManager class is the component of JDBC API and also a member of
the java.sql package. The DriverManager class acts as an interface between
users and drivers. It keeps track of the drivers that are available and handles
establishing a connection between a database and the appropriate driver. It
contains all the appropriate methods to register and deregister the database
driver class and to create a connection between a Java application and the
database. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
Note that before interacting with a Database, it is a mandatory process to
register the driver; otherwise, an exception is thrown.
o Methods of the DriverManager Class

Method Description

1) public static synchronized void is used to register the given driver with DriverManager.
registerDriver(Driver driver): No action is performed by the method when the given
driver is already registered.

2) public static synchronized void is used to deregister the given driver (drop the driver
deregisterDriver(Driver driver): from the list) with DriverManager. If the given driver has
been removed from the list, then no action is performed
by the method.
3) public static Connection is used to establish the connection with the specified
getConnection(String url) throws url. The SQLException is thrown when the
SQLException: corresponding Driver class of the given database is not
registered with the DriverManager.

4) public static Connection is used to establish the connection with the specified
getConnection(String url,String url, username, and password. The SQLException is
userName,String password) throws thrown when the corresponding Driver class of the
SQLException: given database is not registered with the
DriverManager.

5) public static Driver Those drivers that understand the mentioned URL
getDriver(String url) (present in the parameter of the method) are returned
by this method provided those drivers are mentioned
in the list of registered drivers.

6) pubic static int The duration of time a driver is allowed to wait in order
getLoginTimeout() to establish a connection with the database is returned
by this method.

7) pubic static void The method provides the time in seconds. sec
setLoginTimeout(int sec) mentioned in the parameter is the maximum time that
a driver is allowed to wait in order to establish a
connection with the database. If 0 is passed in the
parameter of this method, the driver will have to wait
infinitely while trying to establish the connection with
the database.
8) public static Connection A connection object is returned by this method after
getConnection(String URL, creating a connection to the database present at the
Properties prop) throws mentioned URL, which is the first parameter of this
SQLException method. The second parameter, which is "prop", fetches
the authentication details of the database (username
and password.). Similar to the other variation of the
getConnection() method, this method also throws the
SQLException, when the corresponding Driver class of
the given database is not registered with the
DriverManager.

ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.

By default, ResultSet object can be moved forward only and it is not updatable.

But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:

1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


2. ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface

1) public boolean next(): is used to move the cursor to the one row next from the
current position.

2) public boolean previous(): is used to move the cursor to the one row previous from
the current position.

3) public boolean first(): is used to move the cursor to the first row in result set
object.
4) public boolean last(): is used to move the cursor to the last row in result set
object.

5) public boolean absolute(int is used to move the cursor to the specified row number in
row): the ResultSet object.

6) public boolean relative(int is used to move the cursor to the relative row number in
row): the ResultSet object, it may be positive or negative.

7) public int getInt(int is used to return the data of specified column index of the
columnIndex): current row as int.

8) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.

9) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.

10) public String is used to return the data of specified column name of the
getString(String columnName): current row as String.

Example of Scrollable ResultSet


Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.

• import java.sql.*;
• class FetchRecord{
• public static void main(String args[])throws Exception{

• Class.forName("oracle.jdbc.driver.OracleDriver");
• Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
• Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Resul
tSet.CONCUR_UPDATABLE);
• ResultSet rs=stmt.executeQuery("select * from emp765");

• //getting the record of 3rd row
• rs.absolute(3);
• System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

• con.close();
• }}

• java.sql
• We have relational databases, from which at many times we need to access the
data. For various data processing related matters from RDDBMS we have
java.sql package. The various classes in the package are shown below:

Class Description

Date It gives time in milliseconds. It is a wrapper type. It provides sql with dates.
The class is declared as:
public class Date extends Date
The class methods are inherited from date class.

DriverManager The class is designed for managing the various JDBC drivers. The class is
declared as follows:
public class DriverManager extends Object
The class methods are inherited from Object class.

DriverPropertyInfo The class keeps an account for managing the various properties of JDBC
drivers which are required for making a secure connection. The class is
declared as follows:
public class DriverPropertyInfo extends Object
The class methods are inherited from Object class.
SQLPermission The class manages the various SQL related permissions which are provided
to the accessing objects. The class is declared as follows:
public final class SQLPermission extends BasicPermission
The class methods are inherited from BasicPermission class.

Time It is wrapper class around java.util. The class provides time related
information. The class is declared as follows:
public class Time extends Date
The class methods are inherited from Date class.

Timestamp It is wrapper class around java.util. The class allows JDBC API to identify as
TIMESTAMP value. The class is declared as follows:
public class Timestamp extends Date
The class methods are inherited from Date class.

Types The class defines various SQL constants. The class is declared as follows:
public class Types extends Object
The class methods are inherited from Object class.

Exception Class in Java


An error is a problem, bug, or human-created mistake that arises at the time of
execution of a program. An exception interrupts the flow of the program and
terminates it abnormally. The termination of the program abnormally is not
recommended, and for that, we need to handle these exceptions.

Java provides Java.lang.Exception class for handling the exceptions which inherit the
properties and methods of Object and Throwable class.
Methods of java.lang.Throwable class
addSuppressed(), fillInStackTrace(), getCause(), getLocalizedMessage(), getMessage(),
getStackTrace(), getSuppressed(), initCause(), printStackTrace(), printStackTrace(), pri
ntStackTrace(), setStackTrace(), and toString().

Methods of java.lang.Object class


clone(), equals(), finalize(), getClass(), hashCode(), notify(), notifyAll(), and wait().

The Exception class has a set of sub-classes for handling different types of exceptions
such as IOException, NotBoundException, and NotOwnerException etc.

All the subclasses of the Exception class are in the form of Throwable that indicates
the conditions that an application wants to catch.

The Exception class provides the following 5 constructors:

1. public Exception()
The public Exception () construct an exception with a null detail message. The cause
can be subsequently initialized by
calling Throwable.initCause(Java.lang.Throwable). It is a default constructor and
takes no parameters for message and Throwable cause.

2. public Exception(String message)


The public Exception( String message) construct a new exception with the given
detailed message. Just like the default constructor, the cause can be subsequently
initialized by calling Throwable.initCause(Java.lang.Throwable). It is a
parameterized constructor which takes a parameter of type String for detail message.
The detail message is saved so that the Throwable.getMessage() method can
retrieve it.

Parameters

a. message
It is of type string for the error message or detail message.

3. public Exception(String message, Throwable cause)


It is another variation of the Exception () constructor, which takes two
parameters, i.e., message and cause. It constructs a new exception with the
given detailed message and cause. The message associated with the cause will
not be automatically included in the exception detail message.

Parameters

a. message
It is of type string for the error message or detail message.
b. cause
The cause is saved so that the Throwable.getCause() method can
retrieve it. The null value defines that the cause is nonexistent or
unknown.

4. public Exception(Throwable cause)


It is another variation of the Exception () constructor, which takes only a single
parameter, i.e., cause. The constructor creates an Exception with the given
cause and the detailed message of the cause.

c. detail message = (cause == null ? null : cause.toString())

It is mainly used for the exceptions, which are more than wrappers for other
throwables.

Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion

Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java

o It provides readymade architecture.


o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm
3. Hierarchy of Collection Framework
4. Let us see the hierarchy of Collection framework. The java.util package
contains all the classes and interfaces for the Collection framework.

5.
6.
7. Methods of Collection interface
8. There are many methods declared in the Collection interface. They are as
follows:
No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean It is used to insert the specified collection elements in


addAll(Collection<? the invoking collection.
extends E> c)

3 public boolean It is used to delete an element from the collection.


remove(Object element)

4 public boolean It is used to delete all the elements of the specified


removeAll(Collection<?> c) collection from the invoking collection.

5 default boolean It is used to delete all the elements of the collection


removeIf(Predicate<? super that satisfy the specified predicate.
E> filter)

6 public boolean It is used to delete all the elements of invoking


retainAll(Collection<?> c) collection except the specified collection.

7 public int size() It returns the total number of elements in the collection.

8 public void clear() It removes the total number of elements from the
collection.

9 public boolean It is used to search an element.


contains(Object element)

10 public boolean It is used to search the specified collection in the


containsAll(Collection<?> collection.
c)

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type
of the returned array is that of the specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with the collection


parallelStream() as its source.
16 default Stream<E> stream() It returns a sequential Stream with the collection as its
source.

17 default Spliterator<E> It generates a Spliterator over the specified elements in


spliterator() the collection.

18 public boolean It matches two collections.


equals(Object element)

19 public int hashCode() It returns the hash code number of the collection.

Java AWT Tutorial


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

PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

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

The AWT tutorial will help the user to understand Java GUI programming in simple and
easy steps.

Why AWT is platform independent?


Java AWT calls the native platform calls the native platform (operating systems)
subroutine for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have
different look and feel for the different platforms like Windows, MAC OS, and Unix.
The reason for this is the platforms have different view for their native components
and AWT directly calls the native subroutine that creates those components.

In simple words, an AWT application will look like a windows application in Windows
OS whereas it will look like a Mac application in the MAC OS.

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

It is basically a screen where the where the components are placed at their specific
locations. Thus it contains and controls the layout of components.

Note: A container itself is a component (see the above diagram), therefore we can add a
container inside container.

Types of containers:

There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. Dialog

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. We need to create an instance of
Window class to create this container.

Panel

The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we can
add components.

Frame

The Frame is the container that contain title bar and border and can have menu bars.
It can have other components like button, text field, scrollbar etc. Frame is most widely
used container while developing an AWT application.

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 Defines the layout manager for the component.
m)

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)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.

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

• }

• }
download this example

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:
AWT Example by Association
Let's see a simple example of AWT where we are creating instance of Frame class. Here,
we are creating a TextField, Label and Button component on the Frame.

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, 100, 80, 30);
• b.setBounds(100, 100, 80, 30);

• // adding components into frame
• f.add(b);
• f.add(l);
• 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[]) {

• // creating instance of Frame class
• AWTExample2 awt_obj = new AWTExample2();

• }

• }

Interface Components
Users have become aware of interface components acting in a certain manner, so try
to be predictable and consistent in our selections and their layout. As a result, task
completion, satisfaction, and performance, will increase.

Interface components may involve:

1. Input controls
2. Navigational Components
3. Informational Components
4. Containers

Input Controls: Input Controls involve buttons, toggles, dropdown lists, checkboxes,
date fields, radio buttons, and text fields.

Navigational Components: Navigational components contain slider, tags,


pagination, search field, breadcrumb, icons.

Informational Components: Informational Components contain tooltips, modal


windows, progress bar, icons, notification message boxes.

Containers: Containers include accordion.

Many components may be suitable to display content at times. When this happens, it
is crucial to think about this trade-off. For example, sometimes, components that may
help you space, place more focus on the user, forcing them to guess what the
dropdown is or what the element might be.

BorderLayout (LayoutManagers)
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components
in GUI forms. LayoutManager is an interface that is implemented by all the classes of
layout managers. There are the following classes that represent the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center. Each region (area) may contain one component only. It is the default
layout of a frame or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the


components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

Example of BorderLayout class: Using BorderLayout()


constructor
FileName: Border.java

• import java.awt.*;
• import javax.swing.*;

• public class Border
• {
• JFrame f;
• Border()
• {
• f = new JFrame();

• // creating buttons
• JButton b1 = new JButton("NORTH");; // the button will be labeled as NORT
H
• JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUT
H
• JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
• JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
• JButton b5 = new JButton("CENTER");; // the button will be labeled as CENT
ER

• f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction

• f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction

• f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction


• f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
• f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

• f.setSize(300, 300);
• f.setVisible(true);
• }
• public static void main(String[] args) {
• new Border();
• }
• }
Output:

download this example

Example of BorderLayout class: Using BorderLayout(int hgap,


int vgap) constructor
The following example inserts horizontal and vertical gaps between buttons using the
parameterized constructor BorderLayout(int hgap, int gap)

FileName: BorderLayoutExample.java

• // import statement
• import java.awt.*;
• import javax.swing.*;
• public class BorderLayoutExample
• {
• JFrame jframe;
• // constructor
• BorderLayoutExample()
• {
• // creating a Frame
• jframe = new JFrame();
• // create buttons
• JButton btn1 = new JButton("NORTH");
• JButton btn2 = new JButton("SOUTH");
• JButton btn3 = new JButton("EAST");
• JButton btn4 = new JButton("WEST");
• JButton btn5 = new JButton("CENTER");
• // creating an object of the BorderLayout class using
• // the parameterized constructor where the horizontal gap is 20
• // and vertical gap is 15. The gap will be evident when buttons are placed
• // in the frame
• jframe.setLayout(new BorderLayout(20, 15));
• jframe.add(btn1, BorderLayout.NORTH);
• jframe.add(btn2, BorderLayout.SOUTH);
• jframe.add(btn3, BorderLayout.EAST);
• jframe.add(btn4, BorderLayout.WEST);
• jframe.add(btn5, BorderLayout.CENTER);
• jframe.setSize(300,300);
• jframe.setVisible(true);
• }
• // main method
• public static void main(String argvs[])
• {
• new BorderLayoutExample();
• }
• }

Output:
Java BorderLayout: Without Specifying Region
The add() method of the JFrame class can work even when we do not specify the
region. In such a case, only the latest component added is shown in the frame, and all
the components added previously get discarded. The latest component covers the
whole area. The following example shows the same.

FileName: BorderLayoutWithoutRegionExample.java

• // import statements
• import java.awt.*;
• import javax.swing.*;

• public class BorderLayoutWithoutRegionExample
• {
• JFrame jframe;

• // constructor
• BorderLayoutWithoutRegionExample()
• {
• jframe = new JFrame();

• JButton btn1 = new JButton("NORTH");
• JButton btn2 = new JButton("SOUTH");
• JButton btn3 = new JButton("EAST");
• JButton btn4 = new JButton("WEST");
• JButton btn5 = new JButton("CENTER");

• // horizontal gap is 7, and the vertical gap is 7
• // Since region is not specified, the gaps are of no use
• jframe.setLayout(new BorderLayout(7, 7));

• // each button covers the whole area
• // however, the btn5 is the latest button
• // that is added to the frame; therefore, btn5
• // is shown
• jframe.add(btn1);
• jframe.add(btn2);
• jframe.add(btn3);
• jframe.add(btn4);
• jframe.add(btn5);

• jframe.setSize(300,300);
• jframe.setVisible(true);
• }

• // main method
• public static void main(String argvs[])
• {
• new BorderLayoutWithoutRegionExample();
• }
• }

Output:

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after
another (in a flow). It is the default layout of the applet or panel.

Fields of FlowLayout class

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5
unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor


FileName: FlowLayoutExample.java

1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class FlowLayoutExample
6. {
7.
8. JFrame frameObj;
9.
10. // constructor
11. FlowLayoutExample()
12. {
13. // creating a frame object
14. frameObj = new JFrame();
15.
16. // creating the buttons
17. JButton b1 = new JButton("1");
18. JButton b2 = new JButton("2");
19. JButton b3 = new JButton("3");
20. JButton b4 = new JButton("4");
21. JButton b5 = new JButton("5");
22. JButton b6 = new JButton("6");
23. JButton b7 = new JButton("7");
24. JButton b8 = new JButton("8");
25. JButton b9 = new JButton("9");
26. JButton b10 = new JButton("10");
27.
28.
29. // adding the buttons to frame
30. frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);

31. frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);

32. frameObj.add(b9); frameObj.add(b10);


33.
34. // parameter less constructor is used
35. // therefore, alignment is center
36. // horizontal as well as the vertical gap is 5 units.
37. frameObj.setLayout(new FlowLayout());
38.
39. frameObj.setSize(300, 300);
40. frameObj.setVisible(true);
41. }
42.
43. // main method
44. public static void main(String argvs[])
45. {
46. new FlowLayoutExample();
47. }
48. }

Output:

Example of FlowLayout class: Using FlowLayout(int align)


constructor
FileName: MyFlowLayout.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. // adding buttons to the frame
16. f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);
17.
18. // setting flow layout of right alignment
19. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new MyFlowLayout();
26. }
27. }

Output:

download this example


Example of FlowLayout class: Using FlowLayout(int align, int
hgap, int vgap) constructor
FileName: FlowLayoutExample1.java

1. // import statement
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class FlowLayoutExample1
6. {
7. JFrame frameObj;
8.
9. // constructor
10. FlowLayoutExample1()
11. {
12. // creating a frame object
13. frameObj = new JFrame();
14.
15. // creating the buttons
16. JButton b1 = new JButton("1");
17. JButton b2 = new JButton("2");
18. JButton b3 = new JButton("3");
19. JButton b4 = new JButton("4");
20. JButton b5 = new JButton("5");
21. JButton b6 = new JButton("6");
22. JButton b7 = new JButton("7");
23. JButton b8 = new JButton("8");
24. JButton b9 = new JButton("9");
25. JButton b10 = new JButton("10");
26.
27.
28. // adding the buttons to frame
29. frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);

30. frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);


31. frameObj.add(b9); frameObj.add(b10);
32.
33. // parameterized constructor is used
34. // where alignment is left
35. // horizontal gap is 20 units and vertical gap is 25 units.
36. frameObj.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 25));
37.
38.
39. frameObj.setSize(300, 300);
40. frameObj.setVisible(true);
41. }
42. // main method
43. public static void main(String argvs[])
44. {
45. new FlowLayoutExample1();
46. }
47. }

Output:

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button, dragging mouse
etc. The java.awt.event package provides many event classes and Listener interfaces for event
handling.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

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. Register the component with the Listener

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

o Button
o public void addActionListener(ActionListener a){}
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
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener

• import java.awt.*;
• import java.awt.event.*;
• class AEvent extends Frame implements ActionListener{
• TextField tf;
• AEvent(){

• //create components
• tf=new TextField();
• tf.setBounds(60,50,170,20);
• Button b=new Button("click me");
• b.setBounds(100,120,80,30);

• //register listener
• b.addActionListener(this);//passing current instance

• //add components and set size, layout and visibility
• 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[]){
• new AEvent();
• }
• }

public void setBounds(int xaxis, int yaxis, int width, int height); have been used
in the above example that sets the position of the component it may be button,
textfield etc.

2) Java event handling by outer class


• import java.awt.*;
• import java.awt.event.*;
• class AEvent2 extends Frame{
• TextField tf;
• AEvent2(){
• //create components
• tf=new TextField();
• tf.setBounds(60,50,170,20);
• Button b=new Button("click me");
• b.setBounds(100,120,80,30);
• //register listener
• Outer o=new Outer(this);
• b.addActionListener(o);//passing outer class instance
• //add components and set size, layout and visibility
• add(b);add(tf);
• setSize(300,300);
• setLayout(null);
• setVisible(true);
• }
• public static void main(String args[]){
• new AEvent2();
• }
• }

• import java.awt.event.*;
• class Outer implements ActionListener{
• AEvent2 obj;
• Outer(AEvent2 obj){
• this.obj=obj;
• }
• public void actionPerformed(ActionEvent e){
• obj.tf.setText("welcome");
• }
• }
3) Java event handling by anonymous class

• import java.awt.*;
• import java.awt.event.*;
• class AEvent3 extends Frame{
• TextField tf;
• AEvent3(){
• tf=new TextField();
• tf.setBounds(60,50,170,20);
• Button b=new Button("click me");
• b.setBounds(50,120,80,30);

• b.addActionListener(new ActionListener(){
• public void actionPerformed(){
• tf.setText("hello");
• }
• });
• add(b);add(tf);
• setSize(300,300);
• setLayout(null);
• setVisible(true);
• }
• public static void main(String args[]){
• new AEvent3();
• }
• }

Delegation Event Model in Java


The Delegation Event model is defined to handle events in GUI programming
languages. The GUI stands for Graphical User Interface, where a user
graphically/visually interacts with the system.

The GUI programming is inherently event-driven; whenever a user initiates an activity


such as a mouse activity, clicks, scrolling, etc., each is known as an event that is mapped
to a code to respond to functionality to the user. This is known as event handling.

In this section, we will discuss event processing and how to implement the delegation
event model in Java. We will also discuss the different components of an Event Model.
Event Processing in Java
Java support event processing since Java 1.0. It provides support for AWT ( Abstract
Window Toolkit), which is an API used to develop the Desktop application. In Java 1.0,
the AWT was based on inheritance. To catch and process GUI events for a program, it
should hold subclass GUI components and override action() or handleEvent() methods.
The below image demonstrates the event processing.

But, the modern approach for event processing is based on the Delegation Model. It
defines a standard and compatible mechanism to generate and process events. In this
model, a source generates an event and forwards it to one or more listeners. The
listener waits until it receives an event. Once it receives the event, it is processed by
the listener and returns it. The UI elements are able to delegate the processing of an
event to a separate function.

The key advantage of the Delegation Event Model is that the application logic is
completely separated from the interface logic.

In this model, the listener must be connected with a source to receive the event
notifications. Thus, the events will only be received by the listeners who wish to receive
them. So, this approach is more convenient than the inheritance-based event model
(in Java 1.0).

In the older model, an event was propagated up the containment until a component
was handled. This needed components to receive events that were not processed, and
it took lots of time. The Delegation Event model overcame this issue.

Basically, an Event Model is based on the following three components:


o Events
o Events Sources
o Events Listeners

Events
The Events are the objects that define state change in a source. An event can be
generated as a reaction of a user while interacting with GUI elements. Some of the
event generation activities are moving the mouse pointer, clicking on a button,
pressing the keyboard key, selecting an item from the list, and so on. We can also
consider many other user operations as events.

The Events may also occur that may be not related to user interaction, such as a timer
expires, counter exceeded, system failures, or a task is completed, etc. We can define
events for any of the applied actions.

Event Sources
A source is an object that causes and generates an event. It generates an event when
the internal state of the object is changed. The sources are allowed to generate several
different types of events.

A source must register a listener to receive notifications for a specific event. Each event
contains its registration method. Below is an example:

1. public void addTypeListener (TypeListener e1)

From the above syntax, the Type is the name of the event, and e1 is a reference to the
event listener. For example, for a keyboard event listener, the method will be called
as addKeyListener(). For the mouse event listener, the method will be called
as addMouseMotionListener(). When an event is triggered using the respected
source, all the events will be notified to registered listeners and receive the event
object. This process is known as event multicasting. In few cases, the event notification
will only be sent to listeners that register to receive them.

Some listeners allow only one listener to register. Below is an example:

1. public void addTypeListener(TypeListener e2) throws java.util.TooManyListen


ersException

From the above syntax, the Type is the name of the event, and e2 is the event listener's
reference. When the specified event occurs, it will be notified to the registered listener.
This process is known as unicasting events.
A source should contain a method that unregisters a specific type of event from the
listener if not needed. Below is an example of the method that will remove the event
from the listener.

1. public void removeTypeListener(TypeListener e2?)

From the above syntax, the Type is an event name, and e2 is the reference of the
listener. For example, to remove the keyboard listener,
the removeKeyListener() method will be called.

The source provides the methods to add or remove listeners that generate the events.
For example, the Component class contains the methods to operate on the different
types of events, such as adding or removing them from the listener.

Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners
require two things; first, it must be registered with a source; however, it can be
registered with several resources to receive notification about the events. Second, it
must implement the methods to receive and process the received notifications.

The methods that deal with the events are defined in a set of interfaces. These
interfaces can be found in the java.awt.event package.

For example, the MouseMotionListener interface provides two methods when the
mouse is dragged and moved. Any object can receive and process these events if it
implements the MouseMotionListener interface.

Types of Events
The events are categories into the following two categories:

The Foreground Events:

The foreground events are those events that require direct interaction of the user.
These types of events are generated as a result of user interaction with the GUI
component. For example, clicking on a button, mouse movement, pressing a keyboard
key, selecting an option from the list, etc.

The Background Events :

The Background events are those events that result from the interaction of the end-
user. For example, an Operating system interrupts system failure (Hardware or
Software).
To handle these events, we need an event handling mechanism that provides control
over the events and responses.

The Delegation Model


The Delegation Model is available in Java since Java 1.1. it provides a new delegation-
based event model using AWT to resolve the event problems. It provides a convenient
mechanism to support complex Java programs.

Design Goals
The design goals of the event delegation model are as following:

o It is easy to learn and implement


o It supports a clean separation between application and GUI code.
o It provides robust event handling program code which is less error-prone
(strong compile-time checking)
o It is Flexible, can enable different types of application models for event flow and
propagation.
o It enables run-time discovery of both the component-generated events as well
as observable events.
o It provides support for the backward binary compatibility with the previous
model.

Let's implement it with an example:

Java Program to Implement the Event Deligation Model


The below is a Java program to handle events implementing the event deligation
model:

TestApp.java:

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

• public class TestApp {
• public void search() {
• // For searching
• System.out.println("Searching...");
• }
• public void sort() {
• // for sorting
• System.out.println("Sorting....");
• }

• static public void main(String args[]) {
• TestApp app = new TestApp();
• GUI gui = new GUI(app);
• }
• }

• class Command implements ActionListener {
• static final int SEARCH = 0;
• static final int SORT = 1;
• int id;
• TestApp app;

• public Command(int id, TestApp app) {
• this.id = id;
• this.app = app;
• }

• public void actionPerformed(ActionEvent e) {
• switch(id) {
• case SEARCH:
• app.search();
• break;
• case SORT:
• app.sort();
• break;
• }
• }
• }

• class GUI {

• public GUI(TestApp app) {
• Frame f = new Frame();
• f.setLayout(new FlowLayout());

• Command searchCmd = new Command(Command.SEARCH, app);
• Command sortCmd = new Command(Command.SORT, app);

• Button b;
• f.add(b = new Button("Search"));
• b.addActionListener(searchCmd);
• f.add(b = new Button("Sort"));
• b.addActionListener(sortCmd);

• List l;
• f.add(l = new List());
• l.add("Alphabetical");
• l.add("Chronological");
• l.addActionListener(sortCmd);
• f.pack();

• f.show();
• }
• }

Output:

Searching...

• Event Classes

• The classes that represent events are at the core of Java’s event handling mechanism
Thus, a discussion of event handling must begin with the event classes. It is important t
understand, however, that Java defines several types of events and that not all even
classes can be discussed in this chapter. Arguably, the most widely used events at the tim
of this writing are those defined by the AWT and those defined by Swing. This chapte
focuses on the AWT events. (Most of these events also apply to Swing.) Several Swing
specific events are described in Chapter 31, when Swing is covered.

• At the root of the Java event class hierarchy is EventObject, which is in java.util. It
the superclass for all events. Its one constructor is shown here:

• EventObject(Object src)

• Here, src is the object that generates this event.
• EventObject defines two methods: getSource( ) and toString( ). The getSource
) method returns the source of the event. Its general form is shown here:

• Object getSource( )

• As expected, toString( ) returns the string equivalent of the event.

• The class AWTEvent, defined within the java.awt package, is a subclas
of EventObject. It is the superclass (either directly or indirectly) of all AWT-base
events used by the delegation event model. Its getID( ) method can be used to determin
the type of the event. The signature of this method is shown here:

• int getID( )

• Additional details about AWTEvent are provided at the end of Chapter 26. At this poin
it is important to know only that all of the other classes discussed in this section ar
subclasses of AWTEvent.

• To summarize:

• EventObject is a superclass of all events.

• AWTEvent is a superclass of all AWT events that are handled by the delegation even
model.

• The package java.awt.event defines many types of events that are generated by variou
user interface elements. Table 24-1 shows several commonly used event classes an
provides a brief description of when they are generated. Commonly used constructors an
methods in each class are described in the following sections.
• Event Class : Description

• ActionEvent : Generated when a button is pressed, a list item is double-clicked, or
menu item is selected.

• AdjustmentEvent : Generated when a scroll bar is manipulated.

• ComponentEvent : Generated when a component is hidden, moved, resized, or become
visible.

• ContainerEvent : Generated when a component is added to or removed from a containe

• FocusEvent : Generated when a component gains or loses keyboard focus.

• InputEvent : Abstract superclass for all component input event classes.

• ItemEvent : Generated when a check box or list item is clicked; also occurs when a choic
selection is made or a checkable menu item is selected or deselected.

• KeyEvent : Generated when input is received from the keyboard.

• MouseEvent : Generated when the mouse is dragged, moved, clicked, pressed, o
released; also generated when the mouse enters or exits a component.

• MouseWheelEvent : Generated when the mouse wheel is moved.

• TextEvent : Generated when the value of a text area or text field is changed.

• WindowEvent : Generated when a window is activated, closed, deactivated
deiconified, iconified, opened, or quit.

Java Adapter Classes


Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all
the methods of listener interfaces. So it saves code.

Pros of using Adapter classes:

o It assists the unrelated classes to work combinedly.


o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.

The adapter classes are found in java.awt.event,


java.awt.dnd and javax.swing.event packages. The Adapter classes with their
corresponding listener interfaces are given below.

java.awt.event Adapter classes


Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes

Adapter class Listener interface

DragSourceAdapter DragSourceListener

DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes

Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener

Java WindowAdapter Example


In the following example, we are implementing the WindowAdapter class of AWT and
one its methods windowClosing() to close the frame window.

AdapterExample.java

• // importing the necessary libraries


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

• public class AdapterExample {
• // object of Frame
• Frame f;
• // class constructor
• AdapterExample() {
• // creating a frame with the title
• f = new Frame ("Window Adapter");
• // adding the WindowListener to the frame
• // overriding the windowClosing() method
• f.addWindowListener (new WindowAdapter() {
• public void windowClosing (WindowEvent e) {
• f.dispose();
• }
• });
• // setting the size, layout and
• f.setSize (400, 400);
• f.setLayout (null);
• f.setVisible (true);
• }

• // main method
• public static void main(String[] args) {
• new AdapterExample();
• }
• }

Output:
Java MouseAdapter Example
In the following example, we are implementing the MouseAdapter class. The
MouseListener interface is added into the frame to listen the mouse event in the frame.

MouseAdapterExample.java

• // importing the necessary libraries


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

• // class which inherits the MouseAdapter class
• public class MouseAdapterExample extends MouseAdapter {
• // object of Frame class
• Frame f;
• // class constructor
• MouseAdapterExample() {
• // creating the frame with the title
• f = new Frame ("Mouse Adapter");
• // adding MouseListener to the Frame
• f.addMouseListener(this);
• // setting the size, layout and visibility of the frame
• f.setSize (300, 300);
• f.setLayout (null);
• f.setVisible (true);
• }
• // overriding the mouseClicked() method of the MouseAdapter class
• public void mouseClicked (MouseEvent e) {
• // creating the Graphics object and fetching them from the Frame object using
getGraphics() method
• Graphics g = f.getGraphics();
• // setting the color of graphics object
• g.setColor (Color.BLUE);
• // setting the shape of graphics object
• g.fillOval (e.getX(), e.getY(), 30, 30);
• }
• // main method
• public static void main(String[] args) {
• new MouseAdapterExample();
• }
• }

Output:

Java MouseMotionAdapter Example


In the following example, we are implementing the MouseMotionAdapter class and its
different methods to listen to the mouse motion events in the Frame window.

MouseMotionAdapterExample.java

• // importing the necessary libraries


• import java.awt.*;
• import java.awt.event.*;
• // class which inherits the MouseMotionAdapter class
• public class MouseMotionAdapterExample extends MouseMotionAdapter {

• // object of Frame class


• Frame f;
• // class constructor
• MouseMotionAdapterExample() {
• // creating the frame with the title
• f = new Frame ("Mouse Motion Adapter");
• // adding MouseMotionListener to the Frame
• f.addMouseMotionListener (this);
• // setting the size, layout and visibility of the frame
• f.setSize (300, 300);
• f.setLayout (null);
• f.setVisible (true);
• }
• // overriding the mouseDragged() method
• public void mouseDragged (MouseEvent e) {
• // creating the Graphics object and fetching them from the Frame object using
getGraphics() method
• Graphics g = f.getGraphics();
• // setting the color of graphics object
• g.setColor (Color.ORANGE);
• // setting the shape of graphics object
• g.fillOval (e.getX(), e.getY(), 20, 20);
• }
• public static void main(String[] args) {
• new MouseMotionAdapterExample();
• }
• }

Output:
Java KeyAdapter Example
In the following example, we are implementing the KeyAdapter class and its method.

KeyAdapterExample.java

• // importing the necessary libraries


• import java.awt.*;
• import java.awt.event.*;
• // class which inherits the KeyAdapter class
• public class KeyAdapterExample extends KeyAdapter {
• // creating objects of Label, TextArea and Frame
• Label l;
• TextArea area;
• Frame f;
• // class constructor
• KeyAdapterExample() {
• // creating the Frame with title
• f = new Frame ("Key Adapter");
• // creating the Label
• l = new Label();
• // setting the location of label
• l.setBounds (20, 50, 200, 20);
• // creating the text area
• area = new TextArea();
• // setting the location of text area
• area.setBounds (20, 80, 300, 300);
• // adding KeyListener to text area
• area.addKeyListener(this);
• // adding the label and text area to frame
• f.add(l);
• f.add(area);
• // setting the size, layout and visibility of frame
• f.setSize (400, 400);
• f.setLayout (null);
• f.setVisible (true);
• }
• // overriding the keyReleased() method
• public void keyReleased (KeyEvent e) {
• // creating the String object to get the text fromTextArea
• String text = area.getText();
• // splitting the String into words
• String words[] = text.split ("\\s");
• // setting the label text to print the number of words and characters of given s
tring
• l.setText ("Words: " + words.length + " Characters:" + text.length());
• }
• // main method
• public static void main(String[] args) {
• new KeyAdapterExample();
• }
• }

Output:
Types of events in Java
An event is one of the most important concepts in Java. The change in the state of an
object or behavior by performing actions is referred to as an Event in Java. Actions
include button click, keypress, page scrolling, or cursor movement.

Java provides a package java.awt.event that contains several event classes.

We can classify the events in the following two categories:

1. Foreground Events
2. Background Events

Foreground Events
Foreground events are those events that require user interaction to generate. In order
to generate these foreground events, the user interacts with components in GUI. When
a user clicks on a button, moves the cursor, and scrolls the scrollbar, an event will be
fired.

Background Events
Background events don't require any user interaction. These events automatically
generate in the background. OS failure, OS interrupts, operation completion, etc., are
examples of background events.

Delegation Event Model


A mechanism for controlling the events and deciding what should happen after an
event occur is referred to as event handling. Java follows the Delegation Event
Model for handling the events.

The Delegation Event Model consists of Source and Listener.

Source

Buttons, checkboxes, list, menu-item, choice, scrollbar, etc., are the sources from which
events are generated.

Listeners

The events which are generated from the source are handled by the listeners. Each and
every listener represents interfaces that are responsible for handling events.

To learn more about Delegation Event Model, go through the following link:

https://www.javatpoint.com/delegation-event-model-in-java

We need to register the source with the listener for handling events. Different types of
classes provide different registration methods.

The syntax of registering the source with the listener is as follows:

1. addTypeListener

For example, if we need to register Key and Action events, we use


the addActionListener() and addKeyListener() methods.

These are some of the most used Event classes:

S.N Event Class Listener Methods Descriptions


o. Interface

1. ActionEvent ActionListener actionPerformed() ActionEvent


indicates that
a component-
defined action
occurred.

2. AdjustmentEv AdjustmentListe adjustmentValueCha Adjustment


ent ner nged() events occur
by an
adjustable
object like a
scrollbar.

3. ComponentEv ComponentListe componentResized(), An event


ent ner componentMoved(), occurs when a
componentShown() component
and moved,
componentHidden() changed its
visibility or the
size changed.

4. ContainerEven ContainerListene componentRemoved The event is


t r () and fired when a
componentAdded() component is
added or
removed from
a container.

5. FocusEvent FocusListener focusLost() and Focus events


focusGained() include focus,
focusout,
focusin, and
blur.

6. ItemEvent ItemListener itemStateChanged() Item event


occurs when
an item is
selected.

7. KeyEvent KeyListener keyPressed(), A key event


keyReleased(), and occurs when
keyTyped(). the user
presses a key
on the
keyboard.
8. MouseEvent MouseListener mouseClicked(), A mouse event
and mousePressed(), occurs when
MouseMotionLis mouseEntered(), the user
tener mouseExited() and interacts with
mouseReleased() are the mouse.
the mouseListener
methods.
mouseDregged() and
mouseMoved() are
the
MouseMotionListene
r() methods.

9. MouseWheelE MouseWheelList mouseWheelMoved() MouseWheelE


vent ener . vent occurs
when the
mouse wheel
rotates in a
component.

10. TextEvent TextListener textChanged() TextEvent


occurs when
an object's
text change.

11. WindowEvent WindowListener windowActivated(), Window


windowDeactivated() events occur
, windowOpened(), when a
windowClosed(), window's
windowClosing(), status is
windowIconfied() and changed.
windowDeiconified().

Let's take an example to understand how we can work with the events and listeners:

EventHandlingExample1.java

• // import required classes and package, if any


• package JavaTpoint.Examples;

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

• //create class EventHandlingExample1 to perform event handling within the cl
ass
• public class EventHandlingExample1 {

• // create variables for Frame, Label and Panel
• private Frame frame;
• private Label header;
• private Label status;
• private Panel panel;

• // default constructor
• public EventHandlingExample1(){
• makeGUI();
• }

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

• // create an instance of EventHandlingExample1
• EventHandlingExample1 obj = new EventHandlingExample1();
• obj.addButtonsAndLabel();
• }

• // create makeGUI() method to create a UI to perform user interaction
• private void makeGUI(){

• // initialize Frame
• frame = new Frame("Event Handling Example");

• // set frame size by using setSize() method
• frame.setSize(400,400);

• //set frame layout by using setLayout() method
• frame.setLayout(new GridLayout(3, 1));

• // add window listener to frame
• frame.addWindowListener(new WindowAdapter() {
• public void windowClosing(WindowEvent windowEvent){
• System.exit(0);
• }
• });

• // initialize header and set alignment to center
• header = new Label();
• header.setAlignment(Label.CENTER);

• //initialize status and set its alignment and size
• status = new Label();
• status.setAlignment(Label.CENTER);
• status.setSize(350,100);

• // initialize panel
• panel = new Panel();

• // set flow layout to panel
• panel.setLayout(new FlowLayout());

• // add header, status and panel to frame
• frame.add(header);
• frame.add(panel);
• frame.add(status);
• frame.setVisible(true);
• }

• // create addButtonsAndLabel() method
• private void addButtonsAndLabel(){

• // set label test
• header.setText("Click a button: ");

• // create ok, submit and cancel buttons
• Button okBtn = new Button("OK");
• Button submitBtn = new Button("Submit");
• Button cancelBtn = new Button("Cancel");

• // use setActionCommand() method to set action for ok, submit and canc
el buttons
• okBtn.setActionCommand("OK");
• submitBtn.setActionCommand("Submit");
• cancelBtn.setActionCommand("Cancel");

• // add event listener to buttons using addActionListener() and ButtonClic
kListener()
• okBtn.addActionListener(new ButtonClickListener());
• submitBtn.addActionListener(new ButtonClickListener());
• cancelBtn.addActionListener(new ButtonClickListener());

• // add buttons to panel
• panel.add(okBtn);
• panel.add(submitBtn);
• panel.add(cancelBtn);

• // make frame visible by using setVisible()mmethod
• frame.setVisible(true);
• }

• // implements ActionListener interface
• private class ButtonClickListener implements ActionListener{

• // define actionPerformed() method of ActionListener
• public void actionPerformed(ActionEvent event) {

• // get action command using getActionCommand() method of Event
• String command = event.getActionCommand();

• // code to check which button is pressed
• if( command.equals( "OK" )) {
• status.setText("Ok Button clicked.");
• } else if( command.equals( "Submit" ) ) {
• status.setText("Submit Button clicked.");
• } else {
• status.setText("Cancel Button clicked.");
• }
• }
• }
• }

Output:

Java Swing Tutorial


Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit)
API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components


are platform-independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look
and feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.

What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Do You Know
o How to create runnable jar file in java?
o How to display image on a button in swing?
o How to change the component color by choosing a color from ColorChooser ?
o How to display the digital watch in swing tutorial ?
o How to create a notepad in swing?
o How to create puzzle game and pic puzzle game in swing ?
o How to create tic tac toe game in swing ?

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.


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

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

public void setVisible(boolean b) sets the visibility of the component. It is by default


false.

Java Swing Examples


There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on
the JFrame object inside the main() method.

File: FirstSwingExample.java

• import javax.swing.*;
• public class FirstSwingExample {
• public static void main(String[] args) {
• JFrame f=new JFrame();//creating instance of JFrame

• JButton b=new JButton("click");//creating instance of JButton
• b.setBounds(130,100,100, 40);//x axis, y axis, width, height

• f.add(b);//adding button in JFrame

• f.setSize(400,500);//400 width and 500 height
• f.setLayout(null);//using no layout managers
• f.setVisible(true);//making the frame visible
• }
• }

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call inside the
java constructor.

File: Simple.java

• import javax.swing.*;
• public class Simple {
• JFrame f;
• Simple(){
• f=new JFrame();//creating instance of JFrame

• JButton b=new JButton("click");//creating instance of JButton
• b.setBounds(130,100,100, 40);

• f.add(b);//adding button in JFrame

• f.setSize(400,500);//400 width and 500 height
• f.setLayout(null);//using no layout managers
• f.setVisible(true);//making the frame visible
• }

• public static void main(String[] args) {
• new Simple();
• }
• }

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example
that sets the position of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of
JFrame class explicitly.

File: Simple2.java

• import javax.swing.*;
• public class Simple2 extends JFrame{//inheriting JFrame
• JFrame f;
• Simple2(){
• JButton b=new JButton("click");//create button
• b.setBounds(130,100,100, 40);

• add(b);//adding button on frame
• setSize(400,500);
• setLayout(null);
• setVisible(true);
• }
• public static void main(String[] args) {
• new Simple2();
• }}

SWING - Containers

Containers are an integral part of SWING GUI components. A container provides a


space where a component can be located. A Container in AWT is a component itself
and it provides the capability to add a component to itself. Following are certain
noticable points to be considered.
• Sub classes of Container are called as Container. For example, JPanel,
JFrame and JWindow.
• Container can add only a Component to itself.
• A default layout is present in each container which can be overridden
using setLayout method.

SWING Containers
Following is the list of commonly used containers while designed GUI using SWING.

Sr.No. Container & Description

Panel
1 JPanel is the simplest container. It provides space in which any other
component can be placed, including other panels.

Frame
2
A JFrame is a top-level window with a title and a border.

Window
3 A JWindow object is a top-level window with no borders and no
menubar.

Java JFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame
class. JFrame works like the main window where components like labels, buttons,
textfields are added to create a GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

Nested Class

Modifier and Class Description


Type
protected class JFrame.AccessibleJFrame This class implements accessibility support
for the JFrame class.

Fields

Modifier and Field Description


Type

protected accessibleContext The accessible context property.


AccessibleContext

static int EXIT_ON_CLOSE The exit application default window close


operation.

protected rootPane The JRootPane instance that manages the


JRootPane contentPane and optional menuBar for this
frame, as well as the glassPane.

protected rootPaneCheckingEnabled If true then calls to add and setLayout will be


boolean forwarded to the contentPane.

Constructors

Constructor Description

JFrame() It constructs a new frame that is initially invisible.

JFrame(GraphicsConfiguration gc) It creates a Frame in the specified


GraphicsConfiguration of a screen device and a blank
title.
JFrame(String title) It creates a new, initially invisible Frame with the
specified title.

JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.

JFrame Example
• import java.awt.FlowLayout;
• import javax.swing.JButton;
• import javax.swing.JFrame;
• import javax.swing.JLabel;
• import javax.swing.JPanel;
• public class JFrameExample {
• public static void main(String s[]) {
• JFrame frame = new JFrame("JFrame Example");
• JPanel panel = new JPanel();
• panel.setLayout(new FlowLayout());
• JLabel label = new JLabel("JFrame By Example");
• JButton button = new JButton();
• button.setText("Button");
• panel.add(label);
• panel.add(button);
• frame.add(panel);
• frame.setSize(200, 300);
• frame.setLocationRelativeTo(null);
• frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
• frame.setVisible(true);
• }
• }

Output
JWindow is a part of Java Swing and it can appear on any part of the users
desktop. It is different from JFrame in the respect that JWindow does not
have a title bar or window management buttons like minimize, maximize,
and close, which JFrame has. JWindow can contain several components
such as buttons and labels.
Constructor of the class are:
1. JWindow() : creates an empty Window without any specified
owner
2. JWindow(Frame o) :creates an empty Window with a specified
frame as its owner
3. JWindow(Frame o) : creates an empty Window with a specified
frame as its owner
4. JWindow(Window o) : creates an empty Window with a specified
window as its owner
5. JWindow(Window o, GraphicsConfiguration g) : creates an
empty window with a specified window as its owner and specified
graphics Configuration.
6. JWindow(GraphicsConfiguration g) :creates an empty window
with a specified Graphics Configuration g.
Commonly used methods
1. setLayout(LayoutManager m) : sets the layout of the Window to
specified layout manager
2. setContentPane(Container c) : sets the ContentPane property of
the window
3. getContentPane() : get the container which is the ContentPane for
this Window
4. add(Component c): adds component to the Window
5. isVisible(boolean b): sets the visibility of the Window, if value of
the boolean is true then visible else invisible
6. update(Graphics g) : calls the paint(g) function
7. remove(Component c) : removes the component c
8. getGraphics() : returns the graphics context of the component.
9. getLayeredPane() : returns the layered pane for the window
10. setContentPane(Container c) :sets the content pane for the
window
11. setLayeredPane(JLayeredPane l) : set the layered pane for the
window
12. setRootPane(JRootPane r) : sets the rootPane for the window
13. setTransferHandler(TransferHandler n) : Sets the
transferHandler property, which is a mechanism to support
transfer of data into this component.
14. setRootPaneCheckingEnabled(boolean enabled) : Sets
whether calls to add and setLayout are forwarded to the
contentPane.
15. setRootPane(JRootPane root) :Sets the rootPane property of
the window.
16. setGlassPane(Component glass) : Sets the glassPane property
of the window.
17. repaint(long time, int x, int y, int width, int height): Repaints
the specified rectangle of this component within time milliseconds.
18. remove(Component c): Removes the specified component from
the window.
19. isRootPaneCheckingEnabled() : Returns whether calls to add
and setLayout are forwarded to the contentPane or not .
20. getTransferHandler() : returns the transferHandler property.
21. getRootPane() : Returns the rootPane object for this window.
22. getGlassPane() : Returns the glassPane object for this window.
23. createRootPane() : Called by the constructor methods to create
the default rootPane.
24. addImpl(Component co, Object c, int i) : Adds the specified
child Component to the window.
The following programs will illustrate the use of JWindow
1. program to create a simple JWindow

// java Program to create a simple JWindow


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

class solveit extends JFrame implements ActionListener {


// frame
static JFrame f;

// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");

// create a object
solveit s = new solveit();

// create a panel
JPanel p = new JPanel();

JButton b = new JButton("click");

// add actionlistener to button


b.addActionListener(s);

// add button to panel


p.add(b);

f.add(p);

// set the size of frame


f.setSize(400, 400);

f.show();
}

// if button is pressed
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("click")) {
// create a window
JWindow w = new JWindow(f);

// set panel
JPanel p = new JPanel();

// create a label
JLabel l = new JLabel("this is a window");
// set border
p.setBorder(BorderFactory.createLineBorder(Color.black));

p.add(l);
w.add(p);

// set background
p.setBackground(Color.red);

// setsize of window
w.setSize(200, 100);

// set visibility of window


w.setVisible(true);

// set location of window


w.setLocation(100, 100);
}
}
}

Output :

1. program to create a multiple JWindow .( where one window is the


owner of the other )

// java program to create a multiple JWindow .( where one window is the owner of the
other )<
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solveit extends JFrame implements ActionListener {
// frame
static JFrame f;

// windows
JWindow w, w1;

// object of class
static solveit s;

// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");

// create a object
s = new solveit();

// create a panel
JPanel p = new JPanel();

JButton b = new JButton("click");

// add actionlistener to button


b.addActionListener(s);

// add button to panel


p.add(b);

f.add(p);

// set the size of frame


f.setSize(400, 400);

f.show();
}

// if button is pressed
public void actionPerformed(ActionEvent e)
{
String s1 = e.getActionCommand();
if (s1.equals("click")) {
// create a window
w = new JWindow(f);
// set panel
JPanel p = new JPanel();

// create a label
JLabel l = new JLabel("this is first window");

// create a button
JButton b = new JButton("Click me");

// add Action listener


b.addActionListener(s);

// set border
p.setBorder(BorderFactory.createLineBorder(Color.black));

p.add(l);
p.add(b);
w.add(p);

// set background
p.setBackground(Color.red);

// setsize of window
w.setSize(200, 100);

// set visibility of window


w.setVisible(true);

// set location of window


w.setLocation(100, 100);
}
else {
// create a window
w1 = new JWindow(w);

// set panel
JPanel p = new JPanel();

// create a label
JLabel l = new JLabel("this is the second window");

// set border
p.setBorder(BorderFactory.createLineBorder(Color.black));

p.add(l);
w1.add(p);

// set background
p.setBackground(Color.blue);

// setsize of window
w1.setSize(200, 100);

// set visibility of window


w1.setVisible(true);

// set location of window


w1.setLocation(210, 210);
}
}
}

Output :

Java JDialog
The JDialog control represents a top level window with a border and a title used to
take some form of input from the user. It inherits the Dialog class.

Unlike JFrame, it doesn't have maximize and minimize buttons.

JDialog class declaration


Let's see the declaration for javax.swing.JDialog class.
1. public class JDialog extends Dialog implements WindowConstants, Accessibl
e, RootPaneContainer

Commonly used Constructors:

Constructor Description

JDialog() It is used to create a modeless


dialog without a title and
without a specified Frame
owner.

JDialog(Frame owner) It is used to create a modeless


dialog with specified Frame as
its owner and an empty title.

JDialog(Frame owner, It is used to create a dialog with


String title, boolean the specified title, owner Frame
modal) and modality.

Java JDialog Example


• import javax.swing.*;
• import java.awt.*;
• import java.awt.event.*;
• public class DialogExample {
• private static JDialog d;
• DialogExample() {
• JFrame f= new JFrame();
• d = new JDialog(f , "Dialog Example", true);
• d.setLayout( new FlowLayout() );
• JButton b = new JButton ("OK");
• b.addActionListener ( new ActionListener()
• {
• public void actionPerformed( ActionEvent e )
• {
• DialogExample.d.setVisible(false);
• }
• });
• d.add( new JLabel ("Click button to continue."));
• d.add(b);
• d.setSize(300,300);
• d.setVisible(true);
• }
• public static void main(String args[])
• {
• new DialogExample();
• }
• }

Output:

Java JPanel
The JPanel is a simplest container class. It provides space in which an application can
attach any other component. It inherits the JComponents class.

It doesn't have title bar.

JPanel class declaration


1. public class JPanel extends JComponent implements Accessible

Commonly used Constructors:

Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and a
flow layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout and the


isDoubleBuffered) specified buffering strategy.

JPanel(LayoutManager It is used to create a new JPanel with the specified layout


layout) manager.

Java JPanel Example


• import java.awt.*;
• import javax.swing.*;
• public class PanelExample {
• PanelExample()
• {
• JFrame f= new JFrame("Panel Example");
• JPanel panel=new JPanel();
• panel.setBounds(40,80,200,200);
• panel.setBackground(Color.gray);
• JButton b1=new JButton("Button 1");
• b1.setBounds(50,100,80,30);
• b1.setBackground(Color.yellow);
• JButton b2=new JButton("Button 2");
• b2.setBounds(100,100,80,30);
• b2.setBackground(Color.green);
• panel.add(b1); panel.add(b2);
• f.add(panel);
• f.setSize(400,400);
• f.setLayout(null);
• f.setVisible(true);
• }
• public static void main(String args[])
• {
• new PanelExample();
• }
• }

Output:

Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or
off.

Nested Classes

Modifier Class Description


and
Type

protected JToggleButton.AccessibleJToggleButton This class


class implements
accessibility
support for
the
JToggleButton
class.

static class JToggleButton.ToggleButtonModel The


ToggleButton
model

Constructors

Constructor Description

JToggleButton() It creates an initially


unselected toggle button
without setting the text or
image.

JToggleButton(Action a) It creates a toggle button


where properties are taken
from the Action supplied.

JToggleButton(Icon icon) It creates an initially


unselected toggle button
with the specified image
but no text.

JToggleButton(Icon icon, It creates a toggle button


boolean selected) with the specified image
and selection state, but no
text.

JToggleButton(String text) It creates an unselected


toggle button with the
specified text.

JToggleButton(String text, It creates a toggle button


boolean selected) with the specified text and
selection state.

JToggleButton(String text, It creates a toggle button


Icon icon) that has the specified text
and image, and that is
initially unselected.
JToggleButton(String text, It creates a toggle button
Icon icon, boolean with the specified text,
selected) image, and selection state.

Methods

Modifier and Method Description


Type

AccessibleContext getAccessibleContext() It gets the


AccessibleContext
associated with
this
JToggleButton.

String getUIClassID() It returns a string


that specifies the
name of the l&f
class that renders
this component.

protected String paramString() It returns a string


representation of
this
JToggleButton.

void updateUI() It resets the UI


property to a
value from the
current look and
feel.

JToggleButton Example
• import java.awt.FlowLayout;
• import java.awt.event.ItemEvent;
• import java.awt.event.ItemListener;
• import javax.swing.JFrame;
• import javax.swing.JToggleButton;

• public class JToggleButtonExample extends JFrame implements ItemListener
{
• public static void main(String[] args) {
• new JToggleButtonExample();
• }
• private JToggleButton button;
• JToggleButtonExample() {
• setTitle("JToggleButton with ItemListener Example");
• setLayout(new FlowLayout());
• setJToggleButton();
• setAction();
• setSize(200, 200);
• setVisible(true);
• setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
• }
• private void setJToggleButton() {
• button = new JToggleButton("ON");
• add(button);
• }
• private void setAction() {
• button.addItemListener(this);
• }
• public void itemStateChanged(ItemEvent eve) {
• if (button.isSelected())
• button.setText("OFF");
• else
• button.setText("ON");
• }
• }

Output
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true)
or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off"
to "on ".It inherits JToggleButton class.

JCheckBox class declaration


Let's see the declaration for javax.swing.JCheckBox class.

1. public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected


check box button with no text,
no icon.

JChechBox(String s) Creates an initially unselected


check box with text.

JCheckBox(String text, Creates a check box with text


boolean selected) and specifies whether or not it
is initially selected.

Commonly used Methods:

Methods Description
AccessibleContext It is used to get the AccessibleContext associated
getAccessibleContext() with this JCheckBox.

protected String paramString() It returns a string representation of this


JCheckBox.

Java JCheckBox Example


1. import javax.swing.*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. checkBox1.setBounds(100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);
9. checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}

Output:
Java JCheckBox Example with ItemListener
• import javax.swing.*;
• import java.awt.event.*;
• public class CheckBoxExample
• {
• CheckBoxExample(){
• JFrame f= new JFrame("CheckBox Example");
• final JLabel label = new JLabel();
• label.setHorizontalAlignment(JLabel.CENTER);
• label.setSize(400,100);
• JCheckBox checkbox1 = new JCheckBox("C++");
• checkbox1.setBounds(150,100, 50,50);
• JCheckBox checkbox2 = new JCheckBox("Java");
• checkbox2.setBounds(150,150, 50,50);
• f.add(checkbox1); f.add(checkbox2); f.add(label);
• checkbox1.addItemListener(new ItemListener() {
• public void itemStateChanged(ItemEvent e) {
• label.setText("C++ Checkbox: "
• + (e.getStateChange()==1?"checked":"unchecked"));
• }
• });
• checkbox2.addItemListener(new ItemListener() {
• public void itemStateChanged(ItemEvent e) {
• label.setText("Java Checkbox: "
• + (e.getStateChange()==1?"checked":"unchecked"));
• }
• });
• f.setSize(400,400);
• f.setLayout(null);
• f.setVisible(true);
• }
• public static void main(String args[])
• {
• new CheckBoxExample();
• }
• }

Output:

Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration


PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

Let's see the declaration for javax.swing.JRadioButton class.

1. public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio


button with no text.

JRadioButton(String s) Creates an unselected radio


button with specified text.

JRadioButton(String s, Creates a radio button with


boolean selected) the specified text and
selected status.

Commonly used Methods:

Methods Description

void setText(String s) It is used to set


specified text on
button.

String getText() It is used to return


the text of the
button.

void setEnabled(boolean b) It is used to enable


or disable the
button.

void setIcon(Icon b) It is used to set the


specified Icon on
the button.

Icon getIcon() It is used to get the


Icon of the button.
void setMnemonic(int a) It is used to set the
mnemonic on the
button.

void It is used to add the


addActionListener(ActionListener action listener to
a) this object.

Java JRadioButton Example


• import javax.swing.*;
• public class RadioButtonExample {
• JFrame f;
• RadioButtonExample(){
• f=new JFrame();
• JRadioButton r1=new JRadioButton("A) Male");
• JRadioButton r2=new JRadioButton("B) Female");
• r1.setBounds(75,50,100,30);
• r2.setBounds(75,100,100,30);
• ButtonGroup bg=new ButtonGroup();
• bg.add(r1);bg.add(r2);
• f.add(r1);f.add(r2);
• f.setSize(300,300);
• f.setLayout(null);
• f.setVisible(true);
• }
• public static void main(String[] args) {
• new RadioButtonExample();
• }
• }

Output:
Java JRadioButton Example with ActionListener
• import javax.swing.*;
• import java.awt.event.*;
• class RadioButtonExample extends JFrame implements ActionListener{
• JRadioButton rb1,rb2;
• JButton b;
• RadioButtonExample(){
• rb1=new JRadioButton("Male");
• rb1.setBounds(100,50,100,30);
• rb2=new JRadioButton("Female");
• rb2.setBounds(100,100,100,30);
• ButtonGroup bg=new ButtonGroup();
• bg.add(rb1);bg.add(rb2);
• b=new JButton("click");
• b.setBounds(100,150,80,30);
• b.addActionListener(this);
• add(rb1);add(rb2);add(b);
• setSize(300,300);
• setLayout(null);
• setVisible(true);
• }
• public void actionPerformed(ActionEvent e){
• if(rb1.isSelected()){
• JOptionPane.showMessageDialog(this,"You are Male.");
• }
• if(rb2.isSelected()){
• JOptionPane.showMessageDialog(this,"You are Female.");
• }
• }
• public static void main(String args[]){
• new RadioButtonExample();
• }}

Output:

Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.

JLabel class declaration


PlayNext
Unmute

Current Time 0:00

/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

Let's see the declaration for javax.swing.JLabel class.

1. public class JLabel extends JComponent implements SwingConstants, Acces


sible

Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance


with no image and with an
empty string for the title.

JLabel(String s) Creates a JLabel instance


with the specified text.

JLabel(Icon i) Creates a JLabel instance


with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance


horizontalAlignment) with the specified text,
image, and horizontal
alignment.

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component
will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along
alignment) the X axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents


along the X axis.

Java JLabel Example


• import javax.swing.*;
• class LabelExample
• {
• public static void main(String args[])
• {
• JFrame f= new JFrame("Label Example");
• JLabel l1,l2;
• l1=new JLabel("First Label.");
• l1.setBounds(50,50, 100,30);
• l2=new JLabel("Second Label.");
• l2.setBounds(50,100, 100,30);
• f.add(l1); f.add(l2);
• f.setSize(300,300);
• f.setLayout(null);
• f.setVisible(true);
• }
• }

Output:
Java JLabel Example with ActionListener
• import javax.swing.*;
• import java.awt.*;
• import java.awt.event.*;
• public class LabelExample extends Frame implements ActionListener{
• JTextField tf; JLabel l; JButton b;
• LabelExample(){
• tf=new JTextField();
• tf.setBounds(50,50, 150,20);
• l=new JLabel();
• l.setBounds(50,100, 250,20);
• b=new JButton("Find IP");
• b.setBounds(50,150,95,30);
• b.addActionListener(this);
• add(b);add(tf);add(l);
• setSize(400,400);
• setLayout(null);
• setVisible(true);
• }
• public void actionPerformed(ActionEvent e) {
• try{
• String host=tf.getText();
• String ip=java.net.InetAddress.getByName(host).getHostAddress();
• l.setText("IP of "+host+" is: "+ip);
• }catch(Exception ex){System.out.println(ex);}
• }
• public static void main(String[] args) {
• new LabelExample();
• }}

Output:

Java JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.

JTextField class declaration


PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
Let's see the declaration for javax.swing.JTextField class.

1. public class JTextField extends JTextComponent implements SwingConstant


s

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField


initialized with the specified
text.

JTextField(String text, Creates a new TextField


int columns) initialized with the specified text
and columns.

JTextField(int Creates a new empty TextField


columns) with the specified number of
columns.

Commonly used Methods:

Methods Description

void It is used to add


addActionListener(ActionListener l) the specified
action listener to
receive action
events from this
textfield.

Action getAction() It returns the


currently set
Action for this
ActionEvent
source, or null if
no Action is set.
void setFont(Font f) It is used to set
the current font.

void It is used to
removeActionListener(ActionListener remove the
l) specified action
listener so that it
no longer
receives action
events from this
textfield.

Java JTextField Example


• import javax.swing.*;
• class TextFieldExample
• {
• public static void main(String args[])
• {
• JFrame f= new JFrame("TextField Example");
• JTextField t1,t2;
• t1=new JTextField("Welcome to Javatpoint.");
• t1.setBounds(50,100, 200,30);
• t2=new JTextField("AWT Tutorial");
• t2.setBounds(50,150, 200,30);
• f.add(t1); f.add(t2);
• f.setSize(400,400);
• f.setLayout(null);
• f.setVisible(true);
• }
• }

Output:
Java JTextField Example with ActionListener
• import javax.swing.*;
• import java.awt.event.*;
• public class TextFieldExample implements ActionListener{
• JTextField tf1,tf2,tf3;
• JButton b1,b2;
• TextFieldExample(){
• JFrame f= new JFrame();
• tf1=new JTextField();
• tf1.setBounds(50,50,150,20);
• tf2=new JTextField();
• tf2.setBounds(50,100,150,20);
• tf3=new JTextField();
• tf3.setBounds(50,150,150,20);
• tf3.setEditable(false);
• b1=new JButton("+");
• b1.setBounds(50,200,50,50);
• b2=new JButton("-");
• b2.setBounds(120,200,50,50);
• b1.addActionListener(this);
• b2.addActionListener(this);
• f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
• f.setSize(300,300);
• f.setLayout(null);
• f.setVisible(true);
• }
• public void actionPerformed(ActionEvent e) {
• String s1=tf1.getText();
• String s2=tf2.getText();
• int a=Integer.parseInt(s1);
• int b=Integer.parseInt(s2);
• int c=0;
• if(e.getSource()==b1){
• c=a+b;
• }else if(e.getSource()==b2){
• c=a-b;
• }
• String result=String.valueOf(c);
• tf3.setText(result);
• }
• public static void main(String[] args) {
• new TextFieldExample();
• }}

Output:
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class

JTextArea class declaration


Let's see the declaration for javax.swing.JTextArea class.

1. public class JTextArea extends JTextComponent

Commonly used Constructors:

Constructor Description

JTextArea() Creates a text area that displays


no text initially.

JTextArea(String s) Creates a text area that displays


specified text initially.

JTextArea(int row, int Creates a text area with the


column) specified number of rows and
columns that displays no text
initially.

JTextArea(String s, int Creates a text area with the


row, int column) specified number of rows and
columns that displays specified
text.

Commonly used Methods:

Methods Description

void setRows(int It is used to set specified number


rows) of rows.

void setColumns(int It is used to set specified number


cols) of columns.
void setFont(Font f) It is used to set the specified
font.

void insert(String s, It is used to insert the specified


int position) text on the specified position.

void append(String s) It is used to append the given


text to the end of the document.

Java JTextArea Example


• import javax.swing.*;
• public class TextAreaExample
• {
• TextAreaExample(){
• JFrame f= new JFrame();
• JTextArea area=new JTextArea("Welcome to javatpoint");
• area.setBounds(10,30, 200,200);
• f.add(area);
• f.setSize(300,300);
• f.setLayout(null);
• f.setVisible(true);
• }
• public static void main(String args[])
• {
• new TextAreaExample();
• }}

Output:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by
user is shown on the top of a menu. It inherits JComponent class.

JComboBox class declaration


Let's see the declaration for javax.swing.JComboBox class.

1. public class JComboBox extends JComponent implements ItemSelectable, Li


stDataListener, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a


default data model.

JComboBox(Object[] Creates a JComboBox that


items) contains the elements in the
specified array.

JComboBox(Vector<?> Creates a JComboBox that


items) contains the elements in the
specified Vector.

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an


item to the item list.

void removeItem(Object It is used to delete


anObject) an item to the item
list.

void removeAllItems() It is used to remove


all the items from
the list.
void setEditable(boolean b) It is used to
determine whether
the JComboBox is
editable.

void It is used to add


addActionListener(ActionListener the ActionListener.
a)

void It is used to add


addItemListener(ItemListener i) the ItemListener.

Java JComboBox Example


1. import javax.swing.*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"};
7. JComboBox cb=new JComboBox(country);
8. cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(null);
11. f.setSize(400,500);
12. f.setVisible(true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }

Output:
Java JComboBox Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class ComboBoxExample {
4. JFrame f;
5. ComboBoxExample(){
6. f=new JFrame("ComboBox Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. JButton b=new JButton("Show");
11. b.setBounds(200,100,75,20);
12. String languages[]={"C","C++","C#","Java","PHP"};
13. final JComboBox cb=new JComboBox(languages);
14. cb.setBounds(50, 100,90,20);
15. f.add(cb); f.add(label); f.add(b);
16. f.setLayout(null);
17. f.setSize(350,350);
18. f.setVisible(true);
19. b.addActionListener(new ActionListener() {
20. public void actionPerformed(ActionEvent e) {
21. String data = "Programming language Selected: "
22. + cb.getItemAt(cb.getSelectedIndex());
23. label.setText(data);
24. }
25. });
26. }
27. public static void main(String[] args) {
28. new ComboBoxExample();
29. }
30. }

Output:

Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is
limited, we use a scroll pane to display a large component or a component whose size
can change dynamically.

Constructors

Constructor Purpose

JScrollPane()
JScrollPane(Component) It creates a scroll pane. The
Component parameter,
JScrollPane(int, int) when present, sets the scroll
pane's client. The two int
JScrollPane(Component,
parameters, when present,
int, int)
set the vertical and
horizontal scroll bar policies
(respectively).

Useful Methods

Modifier Method Description

void setColumnHeaderView(Component) It sets the column header


for the scroll pane.

void setRowHeaderView(Component) It sets the row header for


the scroll pane.

void setCorner(String, Component) It sets or gets the specified


corner. The int parameter
Component getCorner(String) specifies which corner and
must be one of the
following constants defined
in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

JScrollPane Example
• import java.awt.FlowLayout;
• import javax.swing.JFrame;
• import javax.swing.JScrollPane;
• import javax.swing.JtextArea;

• public class JScrollPaneExample {
• private static final long serialVersionUID = 1L;

• private static void createAndShowGUI() {

• // Create and set up the window.
• final JFrame frame = new JFrame("Scroll Pane Example");

• // Display the window.
• frame.setSize(500, 500);
• frame.setVisible(true);
• frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

• // set flow layout for the frame
• frame.getContentPane().setLayout(new FlowLayout());

• JTextArea textArea = new JTextArea(20, 20);
• JScrollPane scrollableTextArea = new JScrollPane(textArea);

• scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL
_SCROLLBAR_ALWAYS);
• scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS);

• frame.getContentPane().add(scrollableTextArea);
• }
• public static void main(String[] args) {


• javax.swing.SwingUtilities.invokeLater(new Runnable() {

• public void run() {
• createAndShowGUI();
• }
• });
• }
• }

Output:

Servlets | Servlet Tutorial

Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this technology.
We have discussed these disadvantages below.

Backward Skip 10sPlay VideoForward Skip 10s

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic
web page.

Do You Know?
o What is the web application and what is the difference between Get and Post
request?
o What information is received by the web server if we request for a Servlet?
o How to run servlet in Eclipse, MyEclipse and Netbeans IDE?
o What are the ways for servlet collaboration and what is the difference between
RequestDispatcher and sendRedirect() method?
o What is the difference between ServletConfig and ServletContext interface?
o How many ways can we maintain the state of a user? Which approach is mostly
used in web development?
o How to count the total number of visitors and whole response time for a request
using Filter?
o How to run servlet with annotation?
o How to create registration form using Servlet and Oracle database?
o How can we upload and download the file from the server?

What is a web application?


A web application is an application accessible from the web. A web application is
composed of web components like Servlet, JSP, Filter, etc. and other elements such as
HTML, CSS, and JavaScript. The web components typically execute in Web Server and
respond to the HTTP request.

CGI (Common Gateway Interface)


CGI technology enables the web server to call an external program and pass HTTP
request information to the external program to process the request. For each request,
it starts a new process.

Disadvantages of CGI
There are many problems in CGI technology:

1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start
processes.
3. It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the
Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as follows:

1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.

Life Cycle of a Servlet (Servlet Life Cycle)


The web container maintains the life cycle of a servlet instance. Let's see the life cycle
of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and
end. The servlet is in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state. In the ready state, servlet performs all the
tasks. When the web container invokes the destroy() method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is loaded when
the first request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The init method
is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax
of the init method is given below:
1. public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method. Notice
that servlet is initialized only once. The syntax of the service method of the Servlet
interface is given below:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example
memory, thread etc. The syntax of the destroy method of the Servlet interface is given
below:

1. public void destroy()

GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces.
It provides the implementation of all the methods of these interfaces except the service
method.

GenericServlet class can handle any type of request so it is protocol-independent.

You may create a generic servlet by inheriting the GenericServlet class and providing
the implementation of the service method.

Methods of GenericServlet class


There are many methods in GenericServlet class. They are as follows:

1. public void init(ServletConfig config) is used to initialize the servlet.


2. public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time
when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and
indicates that servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now
there is no need to call super.init(config)
7. public ServletContext getServletContext() returns the object of
ServletContext.
8. public String getInitParameter(String name) returns the parameter value for
the given parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters
defined in the web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in
the servlet log file and a stack trace.

Servlet Example by inheriting the GenericServlet class


Let's see the simple example of servlet by inheriting the GenericServlet class.

It will be better if you learn it after visiting steps to create a servlet.

File: First.java
• import java.io.*;
• import javax.servlet.*;

• public class First extends GenericServlet{
• public void service(ServletRequest req,ServletResponse res)
• throws IOException,ServletException{

• res.setContentType("text/html");

• PrintWriter out=res.getWriter();
• out.print("<html><body>");
• out.print("<b>hello generic servlet</b>");
• out.print("</body></html>");

• }
• }

JSP Tutorial

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than
servlet such as expression language, JSTL, etc.

PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain
than Servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of
the Servlet in JSP. In addition to, we can use implicit objects, predefined tags,
expression language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the
presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces
the code. Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page


The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into Servlet by the help of
JSP translator. The JSP translator is a part of the web server which is responsible for
translating the JSP page into Servlet. After that, Servlet page is compiled by the
compiler and gets converted into the class file. Moreover, all the processes that happen
in Servlet are performed on JSP later like initialization, committing response to the
browser and destroy.

Creating a simple JSP Page


To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in
the web-apps directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java
code in the JSP page. We will learn scriptlet tag later.

1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>

It will print 10 on the browser.

How to run a simple JSP Page?


Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for
example, http://localhost:8888/myapplication/index.jsp

Do I need to follow the directory structure to run a simple JSP?


No, there is no need of directory structure if you don't have class files or TLD files. For
example, put JSP files in a folder directly and deploy that folder. It will be running fine.
However, if you are using Bean class, Servlet or TLD file, the directory structure is
required.

The Directory structure of JSP


The directory structure of JSP page is same as Servlet. We contain the JSP page outside
the WEB-INF folder or in any directory.
JSP Index
JSP logic
application's
side,
The
handling
from
better
architecture
aismaintainability
database
responsible
business
layer,
presentation,
oror
isserver-side,
logic.
aother
for
and
3-tier
displaying
The
storage
scalability
logic,
architecture
data
isand
responsible
system.
the
layer
ofdata
user
the
that
is This
responsible
layers.
application.
interface
separates
for
separation
processing
Theand
presentation
for
a handling
web
storing
of user
concerns
and
requests
user
layer,
retrieving
allows
interaction.
orand
client
fordata

What Is a Web Container?

A JSP-based web application requires a JSP engine, also known as a web


container, to process and execute the JSP pages. The web container is a web server
component that manages the execution of web programs such as servlets, JSPs,
and ASPs.

When a client sends a request for a JSP page, the web container intercepts it and
directs it to the JSP engine. The JSP engine then converts the JSP page into a
servlet class, compiles it, and creates an instance of the class. The service method
of the servlet class is then called, which generates the dynamic content for the JSP
page.

The web container also manages the lifecycle of the JSP pages and servlets,
handling tasks such as instantiating, initializing and destroying them. Additionally, it
provides security, connection pooling, and session management services to the JSP-
based web application.

Components of JSP Architecture

JSP architecture is a web application development model that defines the structure
and organization of a JSP-based web application. It typically consists of the following
components:

• JSP pages: These are the main building blocks of a JSP application. They
contain a combination of HTML, XML, and JSP elements (such as scriptlets,
expressions, and directives) that generate dynamic content.
• Servlets: JSP pages are converted into servlets by the JSP engine. Servlets
are Java classes that handle HTTP requests and generate dynamic content.
• JSP engine (web container): This web server component is responsible for
processing JSP pages. It converts JSP pages into servlets, compiles them,
and runs them in the Java Virtual Machine (JVM).
• JavaBeans: These are reusable Java classes that encapsulate business logic
and data. They are used to store and retrieve information from a database or
other data sources.
• JSTL (JavaServer Pages Standard Tag Library): This is a set of predefined
tags that can be used in JSP pages to perform common tasks such as
iterating over collections, conditional statements, and internationalization.
• Custom Tag Libraries: JSP allows the creation of custom tags that can be
used on JSP pages. These reusable Java classes encapsulate complex logic
and can generate dynamic content cleanly and consistently.
Overall, JSP architecture defines how the different components of a JSP application
interact with each other and how they are organized to provide a robust and scalable
web application

MVC Architecture in Java


The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program or
application shall consist of data model, presentation information and control
information. The MVC pattern needs all these components to be separated as different
objects.

PlayNext
Unmute

Current Time 0:00


/

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

In this section, we will discuss the MVC Architecture in Java, alongwith its advantages
and disadvantages and examples to understand the implementation of MVC in Java.

What is MVC architecture in Java?


The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software
using model designs.

The MVC pattern architecture consists of three layers:

o Model: It represents the business layer of application. It is an object to carry the


data that can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize
the data that the model contains.
o Controller: It works on both the model and view. It is used to manage the flow
of application, i.e. data flow in the model object and to update the view
whenever data is changed.

In Java Programming, the Model contains the simple Java classes, the View used to
display the data and the Controller contains the servlets. Due to this separation the
user requests are processed as follows:
1. A client (browser) sends a request to the controller on the server side, for a
page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.

The struts 2 framework is used to develop MVC-based web application.

The struts framework was initially created by Craig McClanahan and donated to
Apache Foundation in May, 2000 and Struts 1.0 was released in June 2001.

The current stable release of Struts is Struts 2.3.16.1 in March 2, 2014.

This struts 2 tutorial covers all the topics of Struts 2 Framework with simplified
examples for beginners and experienced persons.

Struts 2 Framework
The Struts 2 framework is used to develop MVC (Model View Controller) based web
applications. Struts 2 is the combination of webwork framework of opensymphony
and struts 1.

1. struts2 = webwork + struts1

The Struts 2 provides supports to POJO based actions, Validation Support, AJAX
Support, Integration support to various frameworks such as Hibernate, Spring, Tiles
etc, support to various result types such as Freemarker, Velocity, JSP etc
Struts 2 Architecture and Flow
The architecture and flow of struts 2 application, is combined with many
components such as Controller, ActionProxy, ActionMapper, Configuration Manager,
ActionInvocation, Inerceptor, Action, Result etc.

Here, we are going to understand the struts flow by 2 ways:

1. struts 2 basic flow


2. struts 2 standard architecture and flow provided by apache struts

Struts 2 basic flow

Let's try to understand the basic flow of struts 2 application by this simple figure:

1. User sends a request for the action


2. Controller invokes the ActionInvocation
3. ActionInvocation invokes each interceptors and action
4. A result is generated
5. The result is sent back to the ActionInvocation
6. A HttpServletResponse is generated
7. Response is sent to the user

Struts 2 standard flow (Struts 2 architecture)

Let's try to understand the standard architecture of struts 2 application by this simple
figure:
1. User sends a request for the action
2. Container maps the request in the web.xml file and gets the class name of
controller.
3. Container invokes the controller (StrutsPrepareAndExecuteFilter or
FilterDispatcher). Since struts2.1, it is StrutsPrepareAndExecuteFilter. Before 2.1
it was FilterDispatcher.
4. Controller gets the information for the action from the ActionMapper
5. Controller invokes the ActionProxy
6. ActionProxy gets the information of action and interceptor stack from the
configuration manager which gets the information from the struts.xml file.
7. ActionProxy forwards the request to the ActionInvocation
8. ActionInvocation invokes each interceptors and action
9. A result is generated
10. The result is sent back to the ActionInvocation
11. A HttpServletResponse is generated
12. Response is sent to the user

You might also like