UNIT 3
Java Exceptions
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).
Java try and catch
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.
The try and catch keywords come in pairs:
Syntax
try {
// Block of code to try
catch(Exception e) {
// Block of code to handle errors
Consider the following example:
This will generate an error, because myNumbers[10] does not exist.
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]); // error!
The output will be something like this:
Exception in thread "main" [Link]:
10 at [Link]([Link])Trself »
If an error occurs, we can use try...catch to catch the error and execute some code to handle
it: Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
The output will be:
Something went wrong.
Finally
The finally statement lets you execute code, after try...catch, regardless of the
result: Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
} finally {
[Link]("The 'try catch' is finished.");
The output will be:
Something went wrong.
The 'try catch' is finished.
The throw keyword
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many exception
types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old."); }
else {
[Link]("Access granted - You are old enough!");
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
The output will be:
Exception in thread "main" [Link]: Access denied - You must be at
least 18 years old.
at [Link]([Link])
at [Link]([Link])Try it Yourself »
If age was 20, you would not get an exception:
Example
checkAge(20);
The output will be:
Access granted - You are old enough!
Try it Yourself »
Types of exceptions
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see whether the programmer has handled them or
not. If these exceptions are not handled/declared in the program, you will get compilation
error. For example, SQLException, IOException, ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not
checked at compile-time so compiler does not check whether the programmer has handled
them or not but it’s the responsibility of the programmer to handle these exceptions and
provide a safe exit. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException [Link] defines several types of exceptions that relate to
its various class libraries. Java also allows users to define their own exceptions.
Built-in Exceptions
Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important
built-in exceptions in Java.
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index
is either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting, sleeping, or doing some processing, and it is
interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative or
greater than the size of the string
Examples of Built-in Exception:
• Arithmetic exception
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
[Link] ("Result = " + c);
catch(ArithmeticException e) {
[Link] ("Can't divide a number by 0"); }
Output:
Can't divide a number by 0
• NullPointer Exception
//Java program to demonstrate NullPointerException
class NullPointer_Demo
public static void main(String args[])
try {
String a = null; //null value
[Link]([Link](0));
} catch(NullPointerException e) {
[Link]("NullPointerException.."); }
Output:
NullPointerException..
• StringIndexOutOfBound Exception
// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
public static void main(String args[])
try {
String a = "This is like chipping "; // length is 22 char
c = [Link](24); // accessing 25th element
[Link](c);
catch(StringIndexOutOfBoundsException e) {
[Link]("StringIndexOutOfBoundsException"); }
Output:
StringIndexOutOfBoundsException
• FileNotFound Exception
//Java program to demonstrate FileNotFoundException
import [Link];
import [Link];
import [Link];
class File_notFound_Demo {
public static void main(String args[]) {
try {
// Following file does not exist
File file = new File("E://[Link]");
FileReader fr = new FileReader(file); }
catch (FileNotFoundException e) {
[Link]("File does not exist"); } }}
Output:
File does not exist
• NumberFormat Exception
// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
public static void main(String args[])
try {
// "akki" is not a number
int num = [Link] ("akki") ;
[Link](num);
} catch(NumberFormatException e) {
[Link]("Number format exception"); }
Output:
Number format exception
ArrayIndexOutOfBounds Exception
Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
public static void main(String args[])
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
catch(ArrayIndexOutOfBoundsException e){
[Link] ("Array Index is Out Of Bounds");
Output:
Array Index is Out Of Bounds
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In
such cases, user can also create exceptions which are called ‘user-defined Exceptions’.
Following steps are followed for the creation of user-defined Exception.
• The user should create an exception class as a subclass of Exception class. Since all the
exceptions are subclasses of Exception class, the user should also make his class a
subclass of it. This is done as:
class MyException extends Exception
• We
can write a default constructor in his own exception class.
MyException(){}
• Wecan also create a parameterized constructor with a string as a parameter. We
can use this to store exception details. We can call super class(Exception)
constructor from this and send the string there.
MyException(String str)
{
super(str);
}
• To
raise exception of user-defined type, we need to create an object to his exception
class and throw it using throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
• The following program illustrates how to create own exception class MyException. •
Details of account numbers, customer names, and balance amounts are taken in the
form of three arrays.
• In main() method, the details are displayed using a for-loop. At this time, check is done if in
any account the balance amount is less than the minimum balance amount to be apt in the
account.
• If it is so, then MyException is raised and a message is displayed “Balance amount is
less”
// Java program to demonstrate user defined exception
// This program throws an exception whenever balance
// amount is below Rs 1000
class MyException extends Exception
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};
private static String name[] =
{"Nish", "Shubh", "Sush", "Abhi", "Akash"};
private static double bal[] =
{10000.00, 12000.00, 5600.0, 999.00, 1100.55}; //
default constructor
MyException() { }
// parameterized constructor
MyException(String str) { super(str); }
// write main()
public static void main(String[] args)
try {
// display the heading for the table
[Link]("ACCNO" + "\t" + "CUSTOMER" + "\t" +
"BALANCE"); // display the actual account information for
(int i = 0; i < 5 ; i++)
[Link](accno[i] + "\t" + name[i] + "\t" +
bal[i]);
// display own exception if balance < 1000 if
(bal[i] < 1000)
MyException me =
new MyException("Balance is less than 1000"); throw me;
}
} //end of try
catch (MyException e) {
[Link]();
RunTime Error
MyException: Balance is less than 1000
at [Link]([Link])
Output:
ACCNO CUSTOMER BALANCE
1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0
Java Streams
Java provides I/O Streams to read and write data where, a Stream represents an input source
or an output destination which could be a file, i/o devise, other program etc.
In general, a Stream will be an input stream or, an output stream.
• InputStream − This is used to read data from a source.
• OutputStream − This is used to write data to a destination.
Based on the data they handle there are two types of streams −
• ByteStreams − These handle data in bytes (8 bits) i.e., the byte stream
classes read/write data of 8 bits. Using these you can store
characters, videos, audios, images etc.
• Character
Streams − These handle data in 16 bit Unicode. Using these
you can read and write text data only.
Standard Streams
In addition to above mentioned classes Java provides 3 standard streams representing the
input and, output devices.
• Standard Input − This is used to read data from user through
input devices. keyboard is used as standard input stream and
represented as [Link].
• Standard Output − This is used to project data (results) to the user through output
devices. A computer screen is used for standard output stream and represented as
[Link].
• Standard Error − This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as [Link].
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy
an input file into an output file –
Some important Byte stream classes.
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStrea Used for Buffered Output Stream.
m
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing java
standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that
contain print() and println() method
Example
import [Link].*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}finally {
if (in != null) {
[Link]();
if (out != null) {
[Link]();
}
}
Now let's have a file [Link] with the following content −
This is a test for copy file.
As a next step, compile the above program and execute it, which will
result in creating an [Link] file with the same content as we have in
[Link]. So let's put the above code in [Link] file and do the
following −
$javac [Link]
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit Unicode. Though there are
many classes related to character streams but the most frequently used classes are,
FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
Some important Character stream classes
Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output
We can re-write the above example, which makes the use of these two
classes to copy an input file (having Unicode characters) into an output
file −
Example
import [Link].*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}finally {
if (in != null) {
[Link]();
if (out != null) {
[Link]();
Now let's have a file [Link] with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will
result in creating an [Link] file with the same content as we have in
[Link]. So let's put the above code in [Link] file and do the
following −
$javac [Link]
$java CopyFile
Reading Console Input
We use the object of BufferedReader class to take inputs from the
keyboard.
Reading Characters
read() method is used with BufferedReader object to read
characters. As this function returns integer type value has we
need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character
input. class CharRead
public static void main( String args[])
BufferedReader br = new Bufferedreader(new
InputstreamReader([Link]));
char c = (char)[Link](); //Reading character }
Reading Strings in Java
To read string we have to use readLine() function with
BufferedReader class's object.
String readLine() throws IOException
Program to take String input from Keyboard in Java
import [Link].*;
class MyInput
{
public static void main(String[] args)
{ String text;
InputStreamReader isr = new InputStreamReader([Link]);
BufferedReader br = new BufferedReader(isr); text =
[Link](); //Reading String
[Link](text);
Program to read from a file using BufferedReader class
import java. Io *;
class ReadTest
public static void main(String[] args)
try
File fl = new File("d:/[Link]");
BufferedReader br = new BufferedReader(new
FileReader(fl)) ;
String str;
while ((str=[Link]())!=null)
[Link](str);
[Link]();
[Link]();
}
catch(IOException e) {
[Link]();
Program to write to a File using FileWriter class
import java. Io *;
class WriteTest
public static void main(String[] args)
try
File fl = new File("d:/[Link]"); String
str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
[Link](str);
[Link]();
[Link]();
catch (IOException e)
{ [Link](); }
}
Ways to read input from console in Java
In Java, there are four different ways for reading input from the user in the command line
environment(console).
[Link] Buffered Reader Class
This is the Java classical method to take input, Introduced in JDK1.0. This method is used by
wrapping the [Link] (standard input stream) in an InputStreamReader which is wrapped in
a BufferedReader, we can read input from the user in the command line.
• The input is buffered for efficient reading.
• Thewrapping code is hard to remember.
Implementation:
// Java program to demonstrate BufferedReader
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)
throws IOException
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(
new InputStreamReader([Link]));
// Reading data using readLine
String name = [Link]();
// Printing the read line
[Link](name);
Input:
Geek
Output:
Geek
Note:
To read other types, we use functions like [Link](), [Link](). To read
multiple values, we use split().
2. Using Scanner Class
This is probably the most preferred method to take input. The main purpose of the Scanner
class is to parse primitive types and strings using regular expressions, however, it is also can
be used to read input from the user in the command line.
• Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized
input.
• Regular expressions can be used to find tokens.
• The reading methods are not synchronized
// Java program to demonstrate working of Scanner in Java
import [Link];
class GetInputFromUser {
public static void main(String args[])
// Using Scanner for Getting Input from User
Scanner in = new Scanner([Link]); String s =
[Link]();
[Link]("You entered string " + s); int
a = [Link]();
[Link]("You entered integer " + a);
float b = [Link]();
[Link]("You entered float " + b); //
closing scanner
[Link]();
Input:
GeeksforGeeks
12
3.4
Output:
You entered string GeeksforGeeks
You entered integer 12
You entered float 3.4
3. Using Console Class
It has been becoming a preferred way for reading user’s input from the command line. In
addition, it can be used for reading password-like input without echoing the characters
entered by the user; the format string syntax can also be used (like [Link]()).
Advantages:
• Reading password without echoing the entered characters.
• Reading methods are synchronized.
• Format string syntax can be used.
• Does not work in non-interactive environment (such as in an IDE).
// Java program to demonstrate working of [Link]()
// Note that this program does not work on IDEs as
// [Link]() may require console
public class Sample {
public static void main(String[] args)
// Using Console to input data from user
String name = [Link]().readLine();
[Link]("You entered string " + name);
Input:
GeeksforGeeks
Output:
You entered string GeeksforGeeks
4. Using Command line argument
Most used user input for competitive coding. The command-line arguments are stored in the
String format. The parseInt method of the Integer class converts string argument into Integer.
Similarly, for float and others during execution. The usage of args[] comes into existence in
this input form. The passing of information takes place during the program run. The
command line is given to args[]. These programs have to be run on cmd.
Code: // Program to check for command line arguments
class Hello {
public static void main(String[] args)
// check if length of args array is
// greater than 0
if ([Link] > 0) {
[Link](
"The command line arguments are:");
// iterating the args array and printing
// the command line arguments
for (String val : args)
[Link](val);
else
[Link]("No command line "
+ "arguments found."); }
Command Line Arguments:
javac [Link]
java Main Hello World
Output:
The command line arguments are:
Hello
World
UNIT 4
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class:
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
[Link]("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
[Link]("Zzz");
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
[Link]();
[Link]();
Output:
The pig says: wee wee
Zzz
Notes on Interfaces:
• Likeabstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass) • Interface
methods do not have a body - the body is provided by the "implement" class • On
implementation of an interface, you must override all of its methods • Interface methods
are by default abstract and public
• Interface attributes are by default public, static and final
• An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple
interfaces. Note: To implement multiple interfaces, separate them with a comma (see
example below).
Multiple Interfaces
To implement multiple interfaces, separate them with a
comma: Example
interface FirstInterface {
public void myMethod(); // interface method
interface SecondInterface {
public void myOtherMethod(); // interface method
class DemoClass implements FirstInterface, SecondInterface
{ public void myMethod() {
[Link]("Some text..");
public void myOtherMethod() {
[Link]("Some other text...");
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
[Link]();
[Link]();
}
output
Some text...
Some other text...
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
The relationship between classes and interfaces
A class extends another class, an interface extends another interface, but a class implements
an interface.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){[Link]("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. [Link]();
10. }
11. }
Output:
Hello
Java Interface Example: Bank
Let's see another example of java interface which provides the implementation of
Bank interface.
File: [Link]
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
[Link] TestInterface2{
[Link] static void main(String[] args){
[Link] b=new SBI();
[Link]("ROI: "+[Link]());
14.}}
Output::
ROI: 9.15
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){[Link]("Hello");}
9. public void show(){[Link]("Welcome");}
[Link] static void main(String args[]){
11.A7 obj = new A7();
[Link]();
[Link]();
14. }
15.}
Test it Now
Output:Hello
Welcome
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the same
time.
Threads can be used to perform complicated tasks in the background without interrupting the
main program.
Creating a Thread
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
public class Main extends Thread {
public void run() {
[Link]("This code is running in a thread");
Another way to create a thread is to implement the Runnable interface:
Implement Syntax
public class Main implements Runnable {
public void run() {
[Link]("This code is running in a thread");
}
}
Running Threads
If the class extends the Thread class, the thread can be run by creating an instance of the class
and call its start() method:
Extend Example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
[Link]();
[Link]("This code is outside of the thread");
}
public void run() {
[Link]("This code is running in a thread");
output
This code is outside of the thread
This code is running in a thread
Try it Yourself »
If the class implements the Runnable interface, the thread can be run by passing an instance
of the class to a Thread object's constructor and then calling the thread's start() method:
Implement Example
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
[Link]();
[Link]("This code is outside of the thread");
public void run() {
[Link]("This code is running in a thread");
output
This code is outside of the thread
This code is running in a thread
Try it Yourself »
Differences between "extending" and "implementing" Threads
The major difference is that when a class extends the Thread class, you cannot extend any
other class, but by implementing the Runnable interface, it is possible to extend from another
class as well, like: class MyClass extends OtherClass implements Runnable.
Concurrency Problems
Because threads run at the same time as other parts of the program, there is no way to know in
which order the code will run. When the threads and main program are reading and writing
the same variables, the values are unpredictable. The problems that result from this are called
concurrency problems.
Example
A code example where the value of the variable amount is unpredictable:
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
[Link]();
[Link](amount);
amount++;
[Link](amount);
public void run() {
amount++;
Output
0
2
To avoid concurrency problems, it is best to share as few attributes between
threads as possible. If attributes need to be shared, one possible solution is
to use the isAlive() method of the thread to check whether the thread
has finished running before using any attributes that the thread can change.
Example
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
[Link]();
// Wait for the thread to finish
while([Link]()) {
[Link]("Waiting...");
// Update amount and print its value
[Link]("Main: " + amount);
amount++;
[Link]("Main: " + amount);
}
public void run() {
amount++;
Output
Waiting. . .
Main: 1
Main: 2
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc
A thread can be in one of the following states:
NEW – A thread that has not yet started is in this state.
RUNNABLE – A thread executing in the Java virtual machine is in this state.
BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.
WAITING – A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.
TIMED_WAITING – A thread that is waiting for another thread to perform an action
for up to a specified waiting time is in this state.
TERMINATED – A thread that has exited is in this state.
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
try {
// Displaying the thread that is running
[Link](
"Thread " + [Link]().getId() + " is
running");
catch (Exception e) {
// Throwing an exception
[Link]("Exception is caught"); }
// Main Class
public class Multithread {
public static void main(String[] args)
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
[Link](); }
}
}
Output
Thread 15 is
running Thread 14
is running Thread
16 is running
Thread 12 is
running Thread 11
is running Thread
13 is running
Thread 18 is
running Thread 17
is running
UNIT 5
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.
Java JButton Example
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:
Java JButton Example with
ActionListener 1. import [Link].*;
2. import [Link].*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
7. [Link](50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. [Link](50,100,95,30);
10. [Link](new ActionListener(){
[Link] void actionPerformed(ActionEvent e){
12. [Link]("Welcome to Javatpoint.");
13. }
14. });
15. [Link](b);[Link](tf);
16. [Link](400,400);
17. [Link](null);
18. [Link](true);
19.}
20.}
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.
Java JLabel Example
1. import [Link].*;
2. class LabelExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. [Link](50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. [Link](50,100, 100,30);
12. [Link](l1); [Link](l2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. }
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.
Java JTextField Example
1. import [Link].*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Javatpoint.");
9. [Link](50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. [Link](50,150, 200,30);
12. [Link](t1); [Link](t2);
13. [Link](400,400);
14. [Link](null);
15. [Link](true);
16. }
17. }
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
Java JTextArea Example
1. import [Link].*;
2. public class TextAreaExample
3. {
4. TextAreaExample(){
5. JFrame f= new JFrame();
6. JTextArea area=new JTextArea("Welcome to javatpoint"); 7.
[Link](10,30, 200,200);
8. [Link](area);
9. [Link](300,300);
10. [Link](null);
11. [Link](true);
12. }
[Link] static void main(String args[])
14. {
15. new TextAreaExample();
16. }}
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.
Java JCheckBox Example
1. import [Link].*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. [Link](100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true); 9.
[Link](100,150, 50,50);
10. [Link](checkBox1);
11. [Link](checkBox2);
12. [Link](400,400);
13. [Link](null);
14. [Link](true);
15. }
[Link] static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}
Output:
Java JCheckBox Example: Food Order
1. import [Link].*;
2. import [Link].*;
3. public class CheckBoxExample extends JFrame implements
ActionListener{ 4. JLabel l;
5. JCheckBox cb1,cb2,cb3;
6. JButton b;
7. CheckBoxExample(){
8. l=new JLabel("Food Ordering System");
9. [Link](50,50,300,20);
10. cb1=new JCheckBox("Pizza @ 100");
11. [Link](100,100,150,20);
12. cb2=new JCheckBox("Burger @ 30");
13. [Link](100,150,150,20);
14. cb3=new JCheckBox("Tea @ 10");
15. [Link](100,200,150,20);
16. b=new JButton("Order");
17. [Link](100,250,80,30);
18. [Link](this);
19. add(l);add(cb1);add(cb2);add(cb3);add(b);
20. setSize(400,400);
21. setLayout(null);
22. setVisible(true);
23. setDefaultCloseOperation(EXIT_ON_CLOSE);
24. }
25. public void actionPerformed(ActionEvent e){
26. float amount=0;
27. String msg="";
28. if([Link]()){
29. amount+=100;
30. msg="Pizza: 100\n";
31. }
32. if([Link]()){
33. amount+=30;
34. msg+="Burger: 30\n";
35. }
36. if([Link]()){
37. amount+=10;
38. msg+="Tea: 10\n";
39. }
40. msg+="-----------------\n";
41. [Link](this,msg+"Total: "+amount); 42. }
43. public static void main(String[] args) {
44. new CheckBoxExample();
45. }
46.}
Output:
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Java JRadioButton Example
1. import [Link].*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. [Link](75,50,100,30);
9. [Link](75,100,100,30);
[Link] bg=new ButtonGroup();
[Link](r1);[Link](r2);
[Link](r1);[Link](r2);
[Link](300,300);
[Link](null);
[Link](true);
16.}
[Link] static void main(String[] args) {
18. new RadioButtonExample();
19.}
20.}
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.
Java JComboBox Example
1. import [Link].*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"}; 7.
JComboBox cb=new JComboBox(country);
8. [Link](50, 50,90,20);
9. [Link](cb);
10. [Link](null);
11. [Link](400,500);
12. [Link](true);
13.}
[Link] static void main(String[] args) {
15. new ComboBoxExample();
16.}
17.}
Output:
Java JList
The object of JList class represents a list of text items. The list of text items can be
set up so that the user can choose either one item or multiple items. It inherits
JComponent class.
Java JList Example
1. import [Link].*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>(); 7.
[Link]("Item1");
8. [Link]("Item2");
9. [Link]("Item3");
10. [Link]("Item4");
11. JList<String> list = new JList<>(l1);
12. [Link](100,100, 75,75);
13. [Link](list);
14. [Link](400,400);
15. [Link](null);
16. [Link](true);
17. }
[Link] static void main(String args[])
19. {
20. new ListExample();
21. }}
Output:
Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits JComponent class.
1. import [Link].*;
2. class ScrollBarExample
3. {
4. ScrollBarExample(){
5. JFrame f= new JFrame("Scrollbar Example");
6. JScrollBar s=new JScrollBar();
7. [Link](100,100, 50,100);
8. [Link](s);
9. [Link](400,400);
[Link](null);
[Link](true);
12.}
[Link] static void main(String args[])
14.{
[Link] ScrollBarExample();
16.}}
Output:
Java JMenuBar, JMenu and JMenuItem
The JMenuBar class is used to display menubar on the window or frame. It may have
several menus.
The object of JMenu class is a pull down menu component which is displayed from
the menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a
menu must belong to the JMenuItem or any of its subclass.
Java JMenuItem and JMenu Example
1. import [Link].*;
2. class MenuExample
3. {
4. JMenu menu, submenu;
5. JMenuItem i1, i2, i3, i4, i5;
6. MenuExample(){
7. JFrame f= new JFrame("Menu and MenuItem Example"); 8.
JMenuBar mb=new JMenuBar();
9. menu=new JMenu("Menu");
10. submenu=new JMenu("Sub Menu");
11. i1=new JMenuItem("Item 1");
12. i2=new JMenuItem("Item 2");
13. i3=new JMenuItem("Item 3");
14. i4=new JMenuItem("Item 4");
15. i5=new JMenuItem("Item 5");
16. [Link](i1); [Link](i2); [Link](i3);
17. [Link](i4); [Link](i5);
18. [Link](submenu);
19. [Link](menu);
20. [Link](mb);
21. [Link](400,400);
22. [Link](null);
23. [Link](true);
24.}
[Link] static void main(String args[])
26.{
[Link] MenuExample();
28.}}
Output:
Example of creating Edit menu for Notepad:
1. import [Link].*;
2. import [Link].*;
3. public class MenuExample implements ActionListener{
4. JFrame f;
5. JMenuBar mb;
6. JMenu file,edit,help;
7. JMenuItem cut,copy,paste,selectAll;
8. JTextArea ta;
9. MenuExample(){
10.f=new JFrame();
[Link]=new JMenuItem("cut");
[Link]=new JMenuItem("copy");
[Link]=new JMenuItem("paste");
[Link]=new JMenuItem("selectAll");
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link]=new JMenuBar();
[Link]=new JMenu("File");
[Link]=new JMenu("Edit");
[Link]=new JMenu("Help");
[Link](cut);[Link](copy);[Link](paste);[Link](selectAll);
[Link](file);[Link](edit);[Link](help);
[Link]=new JTextArea();
[Link](5,5,360,320);
[Link](mb);[Link](ta);
[Link](mb);
[Link](null);
[Link](400,400);
[Link](true);
32.}
[Link] void actionPerformed(ActionEvent e) {
[Link]([Link]()==cut)
[Link]();
[Link]([Link]()==paste)
[Link]();
[Link]([Link]()==copy)
[Link]();
[Link]([Link]()==selectAll)
[Link]();
42.}
[Link] static void main(String[] args) {
44. new MenuExample();
45.}
46.}
Output:
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message
dialog box, confirm dialog box and input dialog box. These dialog boxes are used to
display information or get input from the user. The JOptionPane class inherits
JComponent class.
Java JOptionPane Example: showMessageDialog()
1. import [Link].*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. [Link](f,"Hello, Welcome to Javatpoint."); 7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10.}
11.}
Output:
Java JOptionPane Example: showInputDialog()
1. import [Link].*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. String name=[Link](f,"Enter Name"); 7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10.}
11.}
Output:
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The [Link] class 4 life cycle methods and [Link] class
provides 1 life cycle methods for an applet.
[Link] class
For creating any applet [Link] 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.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create
an html file and place the applet code in html file. Now click the html file.
//[Link]
import [Link];
import [Link];
public class First extends Applet{
public void paint(Graphics g){
[Link]("welcome",150,150);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag
in comment and compile it. After that run it by: appletviewer [Link]. Now Html
file is not required but it is for testing purpose only.
//[Link]
import [Link];
import [Link];
public class First extends Applet{
public void paint(Graphics g){
[Link]("welcome to applet",150,150);
}
}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac [Link]
c:\>appletviewer [Link]
A Simple Applet
import [Link].*;
import [Link].*;
public class Simple extends Applet
public void paint(Graphics g)
[Link]("A simple Applet", 20, 20); }
}
Example of an Applet Skeleton
import [Link].*;
import [Link].*;
public class AppletTest extends Applet
public void init()
//initialization
public void start ()
//start or resume execution
public void stop()
//suspend execution
public void destroy()
//perform shutdown activity
}
public void paint (Graphics g)
//display the content of window
}
Example of an Applet
import [Link].*;
import [Link].*;
public class MyApplet extends Applet
int height, width;
public void init()
height = getSize().height;
width = getSize().width;
setName("MyApplet");
public void paint(Graphics g)
[Link](10, 30, 120, 120, 2,
3); }
}
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging mouse
etc. The [Link] package provides many event classes and Listener interfaces for event
handling.
Components of Event Handling
Event handling has three main components,
• Events : An event is a change in state of an object.
• Events Source : Event source is an object that generates an event.
• Listeners : A listener is an object that listens to the event. A listener gets
notified when an event occurs.
Steps to handle events:
1. Implement appropriate interface in the class.
2. Register the component with the listener.
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){}
Example of Event Handling
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class Test extends Applet implements KeyListener
String msg="";
public void init()
addKeyListener(this);
public void keyPressed(KeyEvent k)
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
showStatus("KeyRealesed");
public void keyTyped(KeyEvent k)
msg = msg+[Link]();
repaint();
public void paint(Graphics g)
[Link](msg, 20, 40);
HTML code:
<applet code="Test" width=300, height=100>
</applet>
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in [Link] package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
Java MouseListener Example
1. import [Link].*;
2. import [Link].*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. [Link](20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e)
{ 16. [Link]("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e)
{ 19. [Link]("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e)
{ 22. [Link]("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e)
{ 25. [Link]("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e)
{ 28. [Link]("Mouse Released");
29. }
[Link] static void main(String[] args)
{ 31. new MouseListenerExample();
32.}
33.}
Output:
Java MouseListener Example 2
1. import [Link].*;
2. import [Link].*;
3. public class MouseListenerExample2 extends Frame implements MouseListener{
4. MouseListenerExample2(){
5. addMouseListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseClicked(MouseEvent e) {
12. Graphics g=getGraphics();
13. [Link]([Link]);
14. [Link]([Link](),[Link](),30,30);
15. }
16. public void mouseEntered(MouseEvent e) {}
17. public void mouseExited(MouseEvent e) {}
18. public void mousePressed(MouseEvent e) {}
19. public void mouseReleased(MouseEvent e) {}
20.
[Link] static void main(String[] args) {
22. new MouseListenerExample2(); }}
Output:
Java MouseMotionListener Interface
The Java MouseMotionListener is notified whenever you move or drag mouse. It is
notified against MouseEvent. The MouseMotionListener interface is found in
[Link] package. It has two methods.
Methods of MouseMotionListener interface The signature
of 2 methods found in MouseMotionListener interface are given below:
1. public abstract void mouseDragged(MouseEvent e);
2. public abstract void mouseMoved(MouseEvent e);
Java MouseMotionListener Example
1. import [Link].*;
2. import [Link].*;
3. public class MouseMotionListenerExample extends Frame implements MouseMoti
onListener{
4. MouseMotionListenerExample(){
5. addMouseMotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
[Link] void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. [Link]([Link]);
14. [Link]([Link](),[Link](),20,20);
15.}
[Link] void mouseMoved(MouseEvent e) {}
17.
[Link] static void main(String[] args) {
19. new MouseMotionListenerExample();
20.}
21.}
Output:
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager
is an interface that is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link] 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 frame or window. The BorderLayout provides five constants for
each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Example of BorderLayout class:
1. import [Link].*;
2. import [Link].*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. [Link](b1,[Link]);
16. [Link](b2,[Link]);
17. [Link](b3,[Link]);
18. [Link](b4,[Link]);
19. [Link](b5,[Link]);
20.
21. [Link](300,300);
22. [Link](true);
23.}
[Link] static void main(String[] args) {
25. new Border();
26.}
27.}
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.
Example of GridLayout class
1. import [Link].*;
2. import [Link].*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
18.
19. [Link](b1);[Link](b2);[Link](b3);[Link](b4);[Link](b5); 20.
[Link](b6);[Link](b7);[Link](b8);[Link](b9); 21.
22. [Link](new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. [Link](300,300);
26. [Link](true);
27.}
[Link] static void main(String[] args)
{ 29. new MyGridLayout();
30.}
31.}
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It
is the default layout of applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Example of FlowLayout class
1. import [Link].*;
2. import [Link].*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. [Link](b1);[Link](b2);[Link](b3);[Link](b4);[Link](b5);
16.
17. [Link](new FlowLayout([Link]));
18. //setting flow layout of right alignment
19.
20. [Link](300,300);
21. [Link](true);
22.}
[Link] static void main(String[] args) {
24. new MyFlowLayout();
25.}
26.}
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or
along their baseline.
The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known
as its display area. Each component associates an instance of GridBagConstraints.
With the help of constraints object we arrange component's display area on the grid.
The GridBagLayout manages each component's minimum and preferred sizes in order
to determine component's size.
Example
1. import [Link];
2. import [Link];
3. import [Link];
4.
5. import [Link].*;
6. public class GridBagLayoutExample extends JFrame{
7. public static void main(String[] args) {
8. GridBagLayoutExample a = new GridBagLayoutExample(); 9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints(); 13.
setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout(); 16.
[Link](layout);
17. [Link] = [Link];
18. [Link] = 0;
19. [Link] = 0;
20. [Link](new Button("Button One"), gbc);
21. [Link] = 1;
22. [Link] = 0;
23. [Link](new Button("Button two"), gbc);
24. [Link] = [Link];
25. [Link] = 20;
26. [Link] = 0;
27. [Link] = 1;
28. [Link](new Button("Button Three"), gbc);
29. [Link] = 1;
30. [Link] = 1;
31. [Link](new Button("Button Four"), gbc);
32. [Link] = 0;
33. [Link] = 2;
34. [Link] = [Link];
35. [Link] = 2;
36. [Link](new Button("Button Five"), gbc);
37. setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE); 41.
42. }
43.
44.}
Output: