0% found this document useful (0 votes)
10 views67 pages

Java Notes

The document explains Java exceptions, detailing how errors can occur during execution and how to handle them using try, catch, and finally statements. It describes built-in exceptions, user-defined exceptions, and the distinction between checked and unchecked exceptions, along with examples of each type. Additionally, it covers Java I/O streams, including byte and character streams, and provides examples for copying files using these streams.

Uploaded by

renuajith39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views67 pages

Java Notes

The document explains Java exceptions, detailing how errors can occur during execution and how to handle them using try, catch, and finally statements. It describes built-in exceptions, user-defined exceptions, and the distinction between checked and unchecked exceptions, along with examples of each type. Additionally, it covers Java I/O streams, including byte and character streams, and provides examples for copying files using these streams.

Uploaded by

renuajith39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 67

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

System.out.println(myNumbers[10]); // error!

The output will be something like this:


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
10 at Main.main(Main.java:4)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};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("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};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

} finally {
System.out.println("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 {

System.out.println("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" java.lang.ArithmeticException: Access denied - You must be at


least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)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 etc.Java 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

System.out.println ("Result = " + c);

catch(ArithmeticException e) {

System.out.println ("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

System.out.println(a.charAt(0));
} catch(NullPointerException e) {

System.out.println("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 = a.charAt(24); // accessing 25th element

System.out.println(c);

catch(StringIndexOutOfBoundsException e) {

System.out.println("StringIndexOutOfBoundsException"); }

Output:
StringIndexOutOfBoundsException
• FileNotFound Exception

//Java program to demonstrate FileNotFoundException

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

class File_notFound_Demo {

public static void main(String args[]) {

try {

// Following file does not exist

File file = new File("E://file.txt");

FileReader fr = new FileReader(file); }

catch (FileNotFoundException e) {

System.out.println("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 = Integer.parseInt ("akki") ;


System.out.println(num);

} catch(NumberFormatException e) {

System.out.println("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){

System.out.println ("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

System.out.println("ACCNO" + "\t" + "CUSTOMER" + "\t" +

"BALANCE"); // display the actual account information for

(int i = 0; i < 5 ; i++)

System.out.println(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) {

e.printStackTrace();

RunTime Error
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
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 System.in.
• 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
System.out.
• 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 System.err.

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 java.io.*;

public class CopyFile {

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

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("input.txt");

out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {

out.write(c);

}finally {

if (in != null) {

in.close();

if (out != null) {

out.close();

}
}

Now let's have a file input.txt 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 output.txt file with the same content as we have in
input.txt. So let's put the above code in CopyFile.java file and do the
following −
$javac CopyFile.java
$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 java.io.*;

public class CopyFile {

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

FileReader in = null;

FileWriter out = null;

try {

in = new FileReader("input.txt");

out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {

out.write(c);

}finally {

if (in != null) {
in.close();

if (out != null) {

out.close();

Now let's have a file input.txt 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 output.txt file with the same content as we have in
input.txt. So let's put the above code in CopyFile.java file and do the
following −
$javac CopyFile.java
$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(System.in));

char c = (char)br.read(); //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 java.io.*;

class MyInput
{

public static void main(String[] args)

{ String text;
InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr); text =

br.readLine(); //Reading String

System.out.println(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:/myfile.txt");

BufferedReader br = new BufferedReader(new


FileReader(fl)) ;

String str;

while ((str=br.readLine())!=null)

System.out.println(str);

br.close();

fl.close();
}
catch(IOException e) {

e.printStackTrace();

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:/myfile.txt"); String

str="Write this string to my file";

FileWriter fw = new FileWriter(fl) ;

fw.write(str);

fw.close();

fl.close();

catch (IOException e)

{ e.printStackTrace(); }
}

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).
1.Using Buffered Reader Class
This is the Java classical method to take input, Introduced in JDK1.0. This method is used by
wrapping the System.in (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 java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class Test {

public static void main(String[] args)

throws IOException

// Enter data using BufferReader

BufferedReader reader = new BufferedReader(

new InputStreamReader(System.in));
// Reading data using readLine

String name = reader.readLine();

// Printing the read line

System.out.println(name);

Input:
Geek
Output:

Geek
Note:

To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). 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 java.util.Scanner;

class GetInputFromUser {

public static void main(String args[])

// Using Scanner for Getting Input from User

Scanner in = new Scanner(System.in); String s =

in.nextLine();

System.out.println("You entered string " + s); int

a = in.nextInt();

System.out.println("You entered integer " + a);

float b = in.nextFloat();

System.out.println("You entered float " + b); //


closing scanner

in.close();

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 System.out.printf()).

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 System.console()

// Note that this program does not work on IDEs as

// System.console() may require console

public class Sample {

public static void main(String[] args)

// Using Console to input data from user


String name = System.console().readLine();

System.out.println("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 (args.length > 0) {

System.out.println(

"The command line arguments are:");

// iterating the args array and printing

// the command line arguments

for (String val : args)


System.out.println(val);

else

System.out.println("No command line "


+ "arguments found."); }

Command Line Arguments:

javac GFG1.java
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

System.out.println("The pig says: wee wee");

}
public void sleep() {

// The body of sleep() is provided here

System.out.println("Zzz");

class Main {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

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

System.out.println("Some text..");

public void myOtherMethod() {

System.out.println("Some other text...");

class Main {

public static void main(String[] args) {

DemoClass myObj = new DemoClass();

myObj.myMethod();
myObj.myOtherMethod();

}
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(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Output:

Hello
Java Interface Example: Bank
Let's see another example of java interface which provides the implementation of
Bank interface.

File: TestInterface2.java
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. }
10.class TestInterface2{
11.public static void main(String[] args){
12.Bank b=new SBI();
13.System.out.println("ROI: "+b.rateOfInterest());
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(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.public static void main(String args[]){
11.A7 obj = new A7();
12.obj.print();
13.obj.show();
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() {

System.out.println("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() {

System.out.println("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();

thread.start();

System.out.println("This code is outside of the thread");

}
public void run() {

System.out.println("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);


thread.start();

System.out.println("This code is outside of the thread");

public void run() {

System.out.println("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();

thread.start();

System.out.println(amount);

amount++;
System.out.println(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();

thread.start();
// Wait for the thread to finish

while(thread.isAlive()) {

System.out.println("Waiting...");

// Update amount and print its value

System.out.println("Main: " + amount);

amount++;

System.out.println("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

System.out.println(

"Thread " + Thread.currentThread().getId() + " is

running");

catch (Exception e) {

// Throwing an exception

System.out.println("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();
object.start(); }

}
}

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 javax.swing 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 javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

Java JButton Example with


ActionListener 1. import java.awt.event.*;
2. import javax.swing.*;
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. tf.setBounds(50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
11.public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Javatpoint.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(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 javax.swing.*;
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. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(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 javax.swing.*;
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. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(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 javax.swing.*;
2. public class TextAreaExample
3. {
4. TextAreaExample(){
5. JFrame f= new JFrame();
6. JTextArea area=new JTextArea("Welcome to javatpoint"); 7.
area.setBounds(10,30, 200,200);
8. f.add(area);
9. f.setSize(300,300);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13.public 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 javax.swing.*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. checkBox1.setBounds(100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true); 9.
checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16.public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}

Output:
Java JCheckBox Example: Food Order
1. import javax.swing.*;
2. import java.awt.event.*;
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. l.setBounds(50,50,300,20);
10. cb1=new JCheckBox("Pizza @ 100");
11. cb1.setBounds(100,100,150,20);
12. cb2=new JCheckBox("Burger @ 30");
13. cb2.setBounds(100,150,150,20);
14. cb3=new JCheckBox("Tea @ 10");
15. cb3.setBounds(100,200,150,20);
16. b=new JButton("Order");
17. b.setBounds(100,250,80,30);
18. b.addActionListener(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(cb1.isSelected()){
29. amount+=100;
30. msg="Pizza: 100\n";
31. }
32. if(cb2.isSelected()){
33. amount+=30;
34. msg+="Burger: 30\n";
35. }
36. if(cb3.isSelected()){
37. amount+=10;
38. msg+="Tea: 10\n";
39. }
40. msg+="-----------------\n";
41. JOptionPane.showMessageDialog(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 javax.swing.*;
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. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10.ButtonGroup bg=new ButtonGroup();
11.bg.add(r1);bg.add(r2);
12.f.add(r1);f.add(r2);
13.f.setSize(300,300);
14.f.setLayout(null);
15.f.setVisible(true);
16.}
17.public 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 javax.swing.*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"}; 7.
JComboBox cb=new JComboBox(country);
8. cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(null);
11. f.setSize(400,500);
12. f.setVisible(true);
13.}
14.public static void main(String[] args) {
15. new ComboBoxExample();
16.}
17.}

Output:
Java 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 javax.swing.*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>(); 7.
l1.addElement("Item1");
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");
11. JList<String> list = new JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18.public 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 javax.swing.*;
2. class ScrollBarExample
3. {
4. ScrollBarExample(){
5. JFrame f= new JFrame("Scrollbar Example");
6. JScrollBar s=new JScrollBar();
7. s.setBounds(100,100, 50,100);
8. f.add(s);
9. f.setSize(400,400);
10.f.setLayout(null);
11.f.setVisible(true);
12.}
13.public static void main(String args[])
14.{
15.new 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 javax.swing.*;
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. menu.add(i1); menu.add(i2); menu.add(i3);
17. submenu.add(i4); submenu.add(i5);
18. menu.add(submenu);
19. mb.add(menu);
20. f.setJMenuBar(mb);
21. f.setSize(400,400);
22. f.setLayout(null);
23. f.setVisible(true);
24.}
25.public static void main(String args[])
26.{
27.new MenuExample();
28.}}

Output:

Example of creating Edit menu for Notepad:


1. import javax.swing.*;
2. import java.awt.event.*;
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();
11.cut=new JMenuItem("cut");
12.copy=new JMenuItem("copy");
13.paste=new JMenuItem("paste");
14.selectAll=new JMenuItem("selectAll");
15.cut.addActionListener(this);
16.copy.addActionListener(this);
17.paste.addActionListener(this);
18.selectAll.addActionListener(this);
19.mb=new JMenuBar();
20.file=new JMenu("File");
21.edit=new JMenu("Edit");
22.help=new JMenu("Help");
23.edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
24.mb.add(file);mb.add(edit);mb.add(help);
25.ta=new JTextArea();
26.ta.setBounds(5,5,360,320);
27.f.add(mb);f.add(ta);
28.f.setJMenuBar(mb);
29.f.setLayout(null);
30.f.setSize(400,400);
31.f.setVisible(true);
32.}
33.public void actionPerformed(ActionEvent e) {
34.if(e.getSource()==cut)
35.ta.cut();
36.if(e.getSource()==paste)
37.ta.paste();
38.if(e.getSource()==copy)
39.ta.copy();
40.if(e.getSource()==selectAll)
41.ta.selectAll();
42.}
43.public 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 javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. JOptionPane.showMessageDialog(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 javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. String name=JOptionPane.showInputDialog(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 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.

How to run an Applet?

There are two ways to run an applet

1. By html file.

2. By appletViewer tool (for testing purpose).


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

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}

myapplet.html

<html>
<body>
<applet code="First.class" 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 First.java. Now Html
file is not required but it is for testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

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

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

A Simple Applet
import java.awt.*;

import java.applet.*;

public class Simple extends Applet

public void paint(Graphics g)

g.drawString("A simple Applet", 20, 20); }

}
Example of an Applet Skeleton

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

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 java.applet.*;

import java.awt.*;

public class MyApplet extends Applet

int height, width;

public void init()

height = getSize().height;

width = getSize().width;

setName("MyApplet");

public void paint(Graphics g)

g.drawRoundRect(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 java.awt.event 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 java.awt.*;

import java.awt.event.*;

import java.applet.*;

import java.applet.*;

import java.awt.event.*;

import java.awt.*;

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+k.getKeyChar();

repaint();

public void paint(Graphics g)

g.drawString(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 java.awt.event 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 java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(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. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e)
{ 19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e)
{ 22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e)
{ 25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e)
{ 28. l.setText("Mouse Released");
29. }
30.public static void main(String[] args)
{ 31. new MouseListenerExample();
32.}
33.}

Output:
Java MouseListener Example 2
1. import java.awt.*;
2. import java.awt.event.*;
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. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),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.
21.public 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
java.awt.event 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 java.awt.*;
2. import java.awt.event.*;
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. }
11.public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),20,20);
15.}
16.public void mouseMoved(MouseEvent e) {}
17.
18.public 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. 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 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 java.awt.*;
2. import javax.swing.*;
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. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23.}
24.public 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 java.awt.*;
2. import javax.swing.*;
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. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); 20.
f.add(b6);f.add(b7);f.add(b8);f.add(b9); 21.
22. f.setLayout(new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. f.setSize(300,300);
26. f.setVisible(true);
27.}
28.public 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 java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
16.
17. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
18. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
22.}
23.public 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 java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4.
5. import javax.swing.*;
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.
this.setLayout(layout);
17. gbc.fill = GridBagConstraints.HORIZONTAL;
18. gbc.gridx = 0;
19. gbc.gridy = 0;
20. this.add(new Button("Button One"), gbc);
21. gbc.gridx = 1;
22. gbc.gridy = 0;
23. this.add(new Button("Button two"), gbc);
24. gbc.fill = GridBagConstraints.HORIZONTAL;
25. gbc.ipady = 20;
26. gbc.gridx = 0;
27. gbc.gridy = 1;
28. this.add(new Button("Button Three"), gbc);
29. gbc.gridx = 1;
30. gbc.gridy = 1;
31. this.add(new Button("Button Four"), gbc);
32. gbc.gridx = 0;
33. gbc.gridy = 2;
34. gbc.fill = GridBagConstraints.HORIZONTAL;
35. gbc.gridwidth = 2;
36. this.add(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:

You might also like