CLG Java
CLG Java
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
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 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.
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.
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
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:
It represents the runnable state.It means a thread is waiting in the queue to run.
It represents the blocked state. In this state, the thread is waiting to acquire a lock.
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.
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
It represents the final state of a thread that is terminated or dead. A terminated thread
means it has completed its execution.
// try-catch block
try
{
// moving thread t2 to the state timed waiting
Thread.sleep(100);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
// 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
// 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());
}
Java Threads | How to create a thread in Java
There are two ways to create a thread:
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.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
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:
Output:
thread is running...
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.
FileName: MyThread1.java
Output:
My first thread
4) Using the Thread Class: Thread(Runnable r, String name)
Observe the following program.
FileName: MyThread2.java
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.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. 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:
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();
• }
• }
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
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:
• 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:
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.
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.
. . .
try
b.move();
if (selfish)
{
long t = System.currentTimeMillis();
else
sleep(5);
. . .
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
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;
1. Checked Exception
2. Unchecked Exception
3. Error
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
Keyword Description
JavaExceptionExample.java
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:
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.
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.
1. By html file.
2. By appletViewer tool (for testing purpose).
• //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>
• //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>
• */
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
Display Block
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
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.
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");
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.
Method Description
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an
input stream of bytes.
Method Description
InputStream Hierarchy
Method Description
int available() It is used to return the estimated
number of bytes that can be read
from the input stream.
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:
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:
Method Description
Output:
Success...
testout.txt
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
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
Method
void close() It closes this random access file stream and releases
any system resources associated with the stream.
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 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."
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.
6 PipedReader This class provides methods to read characters from the connected
piped output stream.
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
• 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.
Constructor Description
• 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();
• }
• }
Class declaraction
Let's see the declaration for Java.io.BufferedWriter class:
Class constructors
Constructor Description
Class methods
Method Description
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.
• 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");
• }
• }
Class declaration
Let's see the declaration for Java.io.PrintWriter class:
1. public class PrintWriter extends Writer
Method Description
boolean checkError() It is used to flushes the stream and check its error state.
PrintWriter format(String It is used to write a formatted string to the writer using specified
format, Object... args) arguments and format string.
• 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();
• }
• }
We must have to implement the Serializable interface for serializing the object.
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.
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:
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
o DriverManager class
o Blob class
o Clob class
o Types class
We can use JDBC API to handle database using Java program and can perform the
following activities:
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)
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:
Disadvantage:
o No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
Disadvantages:
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:
Disadvantage:
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) 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.
• 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.
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().
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.
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.
Parameters
a. message
It is of type string for the error message or 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.
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).
5.
6.
7. Methods of Collection interface
8. There are many methods declared in the Collection interface. They are as
follows:
No. Method Description
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.
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.
19 public int hashCode() It returns the hash code number of the collection.
PlayNext
Unmute
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.
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.
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:
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.
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.
AWTExample1.java
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
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.
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.
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:
• 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
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.
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);
Output:
Output:
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);
Output:
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
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){}
1. Within class
2. Other class
3. Anonymous class
• 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.
• 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();
• }
• }
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.
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:
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.
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.
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 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 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.
Design Goals
The design goals of the event delegation model are as following:
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.
•
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
AdapterExample.java
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
Output:
MouseMotionAdapterExample.java
Output:
Java KeyAdapter Example
In the following example, we are implementing the KeyAdapter class and its method.
KeyAdapterExample.java
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.
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.
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.
1. addTypeListener
Let's take an example to understand how we can work with the events and listeners:
EventHandlingExample1.java
Output:
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
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.
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 ?
Method Description
public void setLayout(LayoutManager sets the layout manager for the component.
m)
We can write the code of swing inside the main(), constructor or any other 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
• }
• }
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.
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
SWING Containers
Following is the list of commonly used containers while designed GUI using SWING.
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
Fields
Constructors
Constructor Description
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
// 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();
f.add(p);
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);
Output :
// 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();
f.add(p);
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");
// 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 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);
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.
Constructor Description
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.
Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and a
flow layout.
Output:
Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or
off.
Nested Classes
Constructors
Constructor Description
Methods
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.
Constructor Description
Methods Description
AccessibleContext It is used to get the AccessibleContext associated
getAccessibleContext() with this JCheckBox.
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.
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
Constructor Description
Methods Description
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.
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
Constructor Description
Methods Description
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.
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.
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
Let's see the declaration for javax.swing.JTextField class.
Constructor Description
Methods Description
void It is used to
removeActionListener(ActionListener remove the
l) specified action
listener so that it
no longer
receives action
events from this
textfield.
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
Constructor Description
Methods Description
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.
Constructor Description
Methods Description
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
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:
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.
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.
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?
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.
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.
You may create a generic servlet by inheriting the GenericServlet class and providing
the implementation of the service method.
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
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.
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.
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.
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.
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.
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>
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.
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
PlayNext
Unmute
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.
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 framework was initially created by Craig McClanahan and donated to
Apache Foundation in May, 2000 and Struts 1.0 was released in June 2001.
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.
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.
Let's try to understand the basic flow of struts 2 application by this simple figure:
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