0% found this document useful (0 votes)
11 views166 pages

java Notes UNITS 1-5[1]pdf

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995, originally designed for interactive television but later adapted for internet programming. It features platform independence, security, and simplicity, making it popular for various applications, including mobile and web development. The document also details Java's history, naming origins, significant versions, and fundamental concepts such as data types and the differences between JDK, JRE, and JVM.

Uploaded by

160622733035
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views166 pages

java Notes UNITS 1-5[1]pdf

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995, originally designed for interactive television but later adapted for internet programming. It features platform independence, security, and simplicity, making it popular for various applications, including mobile and web development. The document also details Java's history, naming origins, significant versions, and fundamental concepts such as data types and the differences between JDK, JRE, and JVM.

Uploaded by

160622733035
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 166

Java is a programming language and a platform.

Java is a high level, robust, object-oriented and secure programming


language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known
as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has a
runtime environment (JRE) and API, it is called a platform.

History of Java
1.History of Java
2.Java Version History

The history of Java is very interesting. Java was originally designed for interactive television, but it was too advanced
technology for the digital cable television industry at the time. The history of Java starts with the Green Team. Java team
members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was best suited for internet programming. Later, Java technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by
James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the
early '90s.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following are given
significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team
of sun engineers called Green Team.

2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

Why Java was named as "Oak"?

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany,
Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java Programming named "Java"?

7) Why had they chose the name Java for Java language? The team gathered to choose a new name. The suggested words
were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say.

According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most of the team
members preferred Java than other names.

8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java
name was chosen by James Gosling while having a cup of coffee nearby his office.

9) Notice that Java is just a name, not an acronym.


10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and
released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features
added to the language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (to be released by March 2022)

Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure programming
language. Apart from this, there are also some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java
language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that incorporate both data and behaviour.Object-oriented
programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform
specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in
which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a software-based platform.The Java
platform differs from most other platforms in the sense that it is a software-based platform that runs on top of other
hardware-based platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run
on multiple platforms, i.e., Write Once and Run Anywhere (WORA).

Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

• No explicit pointer
• Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load
Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the
classes of the local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.
o Security Manager: It determines what resources a class can access such as reading and writing to the local
disk.
Java language provides these securities by default. Some security can also be provided by an application developer explicitly
through SSL, JAAS, Cryptography, etc.

Robust

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points make Java robust.

Architecture-neutral

Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types
is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.

High-performance

Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is
still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.

Distributed

Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for
creating distributed applications. This feature of Java makes us able to access files by calling the methods from any
machine on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once
by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web applications, etc.

Dynamic

Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also
supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).
First Java Program | Hello World Example
1.Software Requirements
2.Creating Hello Java Example
3.Resolving javac is not recognized

In this section, we will learn how to write the simple program of Java. We can write a simple hello Java program easily after
installing the JDK.

To create a simple Java program, you need to create a class that contains the main method. Let's understand the requirement
first.

The requirement for Java Hello World Example

For executing any Java program, the following software or application must be properly installed.

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program

Creating Hello World Example


Let's create the hello java program:

. class Simple{
. public static void main(String args[]){
. System.out.println("Hello Java");
. }
. }

Save the above file as Simple.java.

To compile: javac Simple.java

To execute: java Simple

Output:

Hello Java

Compilation Flow:

When we compile Java program using javac tool, the Java compiler converts the source code into byte code.
Parameters used in First Java Program

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core advantage
of the static method is that there is no need to create an object to invoke the static method. The main()
method is executed by the JVM, so it doesn't require creating an object to invoke the main() method. So, it
saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it in coming section.
o System.out.println() is used to print statement. Here, System is a class, out is an object of the PrintStream
class, println() is a method of the PrintStream class. We will discuss the internal working
of System.out.println() statement in the coming section.

To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories -> Notepad and
write a simple program as we have shownbelow:
As displayed in the above diagram, write the simple program of Java in notepad and saved it as Simple.java. In order to
compile and run the above program, you need to open the command prompt by start menu -> All Programs -> Accessories
-> command prompt. When we have done with all the steps properly, it shows the following output:

To compile and run the above program, go to your current directory first; my current directory is c:\new. Write here:

To compile: javac Simple.java

To execute: java Simple

Difference between JDK, JRE, and JVM


We must understand the differences between JDK, JRE, and JVM before proceeding further to Java. See the brief overview
of JVM here.

If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let's see the differences
between the JDK, JRE, and JVM.

JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a
specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs
which are written in other languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the
configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of
software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

JDK

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment
which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a
compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java
Application.

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types
available in Java language.
Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why
we need to declare variable's type and name.

There are 8 types of primitive data type

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte
float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that
track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example:

. Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its value-range lies
between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because
a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.

Example:

. byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767 (inclusive).
Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an
integer.

Example:

. short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default
value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem about memory.

Example:
. int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than
those provided by int.

Example:

. long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is recommended to use
a float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should
never be used for precise values, such as currency. Its default value is 0.0F.

Example:

. float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type
is generally used for decimal values just like float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.

Example:

. double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive).The char data type is used to store characters.
Java Arrays
An array is a collection of similar type of elements which has contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages

o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages

o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.

Types of Array in java

There are two types of array.

• Single Dimensional Array


• Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

. dataType[] arr; (or)


. dataType []arr; (or)
. dataType arr[];
Instantiation of an Array in Java

. arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

. //Java Program to illustrate how to declare, instantiate, initialize


. //and traverse the Java array.
. class Testarray
. {
. public static void main(String args[])
. {
. int a[]=new int[5];//declaration and instantiation
. a[0]=10;//initialization
. a[1]=20;
. a[2]=70;
. a[3]=40;
. a[4]=50;
. //traversing array
. for(int i=0;i<a.length;i++)//length is the property of array
. System.out.println(a[i]);
. }}

Output:

10
20
70
40
50

.
.
Example2://Java Program to illustrate the use of declaration, instantiation
. //and initialization of Java array in a single line
. class Testarray1{
. public static void main(String args[]){
. int a[]={33,3,4,5};//declaration, instantiation and initialization
. //printing array
. for(int i=0;i<a.length;i++)//length is the property of array
. System.out.println(a[i]);
. }}
Output:

33
3
4
5

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

. dataType[][] arrayRefVar; (or)


. dataType [][]arrayRefVar; (or)
. dataType arrayRefVar[][]; (or)
. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java

. int[][] arr=new int[3][3];//3 row and 3 column


Example to initialize Multidimensional Array in Java

. arr[0][0]=1;
. arr[0][1]=2;
. arr[0][2]=3;
. arr[1][0]=4;
. arr[1][1]=5;
. arr[1][2]=6;
. arr[2][0]=7;
. arr[2][1]=8;
. arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

. //Java Program to illustrate the use of multidimensional array


. class Testarray3{
. public static void main(String args[])
. {
. //declaring and initializing 2D array
. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
. //printing 2D array
. for(int i=0;i<3;i++)
. {
. for(int j=0;j<3;j++)
. {
. System.out.print(arr[i][j]+" ");
. }
. System.out.println();
. }
. }}

Output:

123
245
445

Jagged Array in Java

If we are creating odd number of columns in a 2D array, it is known as a jagged array. In


other words, it is an array of arrays with different number of columns.

. //Java Program to illustrate the jagged array


. class TestJaggedArray{
. public static void main(String[] args){
. //declaring a 2D array with odd columns
. int arr[][] = new int[3][];
. arr[0] = new int[3];
. arr[1] = new int[4];
. arr[2] = new int[2];
. //initializing a jagged array
. int count = 0;
. for (int i=0; i<arr.length; i++)
. for(int j=0; j<arr[i].length; j++)
. arr[i][j] = count++;
.
. //printing the data of a jagged array
. for (int i=0; i<arr.length; i++){
. for (int j=0; j<arr[i].length; j++){
. System.out.print(arr[i][j]+" ");
. }
. System.out.println();//new line
. }
. }
. }

Output:

012
3456
78
Operators in Java

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Operator Type Category Precedence

postfix expr++ expr--


Unary
prefix ++expr --expr +expr -expr ~ !

multiplicative */%
Arithmetic
additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof


equality == !=

bitwise AND &

Bitwise bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&


Logical
logical OR ||

Ternary ternary ?:

= += -= *= /= %= &= ^= |=
Assignment assignment
<<= >>= >>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --

. public class OperatorExample{


. public static void main(String args[]){
. int x=10;
. System.out.println(x++);//10 (11)
. System.out.println(++x);//12
. System.out.println(x--);//12 (11)
. System.out.println(--x);//10
. }}
Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --

. public class OperatorExample{


. public static void main(String args[]){
. int a=10;
. int b=10;
. System.out.println(a++ + ++a);//10+12=22
. System.out.println(b++ + b++);//10+11=21
. }
. }
Output:

22
21

Java Unary Operator Example: ~ and !

. public class OperatorExample


. {
. public static void main(String args[])
. {
. int a=10;
. int b=-10;
. boolean c=true;
. boolean d=false;
. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
. System.out.println(!c);//false (opposite of boolean value)
. System.out.println(!d);//true
. }
. }
Output:

-11
9
false
true

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Java Arithmetic Operator Example

. public class OperatorExample{


. public static void main(String args[]){
. int a=10;
. int b=5;
. System.out.println(a+b);//15
. System.out.println(a-b);//5
. System.out.println(a*b);//50
. System.out.println(a/b);//2
. System.out.println(a%b);//0
. }}
Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression

. public class OperatorExample{


. public static void main(String args[]){
. System.out.println(10*10/5+3-1*4/2);
. }}
Output:

21

Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Java Left Shift Operator Example

. public class OperatorExample{


. public static void main(String args[]){
. System.out.println(10<<2);//10*2^2=10*4=40
. System.out.println(10<<3);//10*2^3=10*8=80
. System.out.println(20<<2);//20*2^2=20*4=80
. System.out.println(15<<4);//15*2^4=15*16=240
. }
. }
Output:

40
80
80
240

Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.

Java Right Shift Operator Example

. public OperatorExample{
. public static void main(String args[]){
. System.out.println(10>>2);//10/2^2=10/4=2
. System.out.println(20>>2);//20/2^2=20/4=5
. System.out.println(20>>3);//20/2^3=20/8=2
. }}
Output:

2
5
2

Java Shift Operator Example: >> vs >>>

. public class OperatorExample


. {
. public static void main(String args[])
. {
. //For positive number, >> and >>> works same
. System.out.println(20>>2);
. System.out.println(20>>>2);
. //For negative number, >>> changes parity bit (MSB) to 0
. System.out.println(-20>>2);
. System.out.println(-20>>>2);
. }
. }
Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

. public class OperatorExample{


. public static void main(String args[]){
. int a=10;
. int b=5;
. int c=20;
. System.out.println(a<b&&a<c);//false && true = false
. System.out.println(a<b&a<c);//false & true = false
. }
. }
Output:

false
false

Java AND Operator Example: Logical && vs Bitwise &

. public class OperatorExample{


. public static void main(String args[]){
. int a=10;
. int b=5;
. int c=20;
. System.out.println(a<b&&a++<c);//false && true = false
. System.out.println(a);//10 because second condition is not checked
. System.out.println(a<b&a++<c);//false && true = false
. System.out.println(a);//11 because second condition is checked
. }
. }
Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.

. public class OperatorExample


. {
. public static void main(String args[])
. {
. int a=10;
. int b=5;
. int c=20;
. System.out.println(a>b||a<c);//true || true = true
. System.out.println(a>b|a<c);//true | true = true
. //|| vs |
. System.out.println(a>b||a++<c);//true || true = true
. System.out.println(a);//10 because second condition is not checked
. System.out.println(a>b|a++<c);//true | true = true
. System.out.println(a);//11 because second condition is checked
. }
. }
Output:

true
true
true
10
true
11

Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.

Java Ternary Operator Example

. public class OperatorExample{


. public static void main(String args[]){
. int a=2;
. int b=5;
. int min=(a<b)?a:b;
. System.out.println(min);
. }
. }
Output:

Another Example:

. public class OperatorExample


. {
. public static void main(String args[])
. {
. int a=10;
. int b=5;
. int min=(a<b)?a:b;
. System.out.println(min);
. }
. }
Output:

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left.

Java Assignment Operator Example

. public class OperatorExample


. {
. public static void main(String args[])
. {
. int a=10;
. int b=20;
. a+=4;//a=a+4 (a=10+4)
. b-=4;//b=b-4 (b=20-4)
. System.out.println(a);
. System.out.println(b);
. }
. }
Output:

14
16

Java Assignment Operator Example

. public class OperatorExample{


. public static void main(String[] args){
. int a=10;
. a+=3;//10+3
. System.out.println(a);
. a-=4;//13-4
. System.out.println(a);
. a*=2;//9*2
. System.out.println(a);
. a/=2;//18/2
. System.out.println(a);
. }}
Output:

13
9
18
9
Java Assignment Operator Example: Adding short

. public class OperatorExample{


. public static void main(String args[]){
. short a=10;
. short b=10;
. //a+=b;//a=a+b internally so fine
. a=a+b;//Compile time error because 10+10=20 now int
. System.out.println(a);
. }}
Output:

Compile time error

After type cast:

. public class OperatorExample{


. public static void main(String args[]){
. short a=10;
. short b=10;
. a=(short)(a+b);//20 which is int now converted to short
. System.out.println(a);
. }
. }
Output:

20

Java Control Statements | Control Flow in Java

Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


1. if statements
2. switch statement
2. Loop statements
1. do while loop
2. while loop
3. for loop
4. for-each loop
3. Jump statements

1. break statement
2. continue statement

Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.

Syntax of if statement is given below.

. if(condition) {
. statement 1; //executes when condition is true
. }
Consider the following example in which we have used the if statement in the java code.

Student.java

Student.java

. public class Student {


. public static void main(String[] args) {
. int x = 10;
. int y = 12;
. if(x+y > 20) {
. System.out.println("x + y is greater than 20");
. }
. }
. }
Output:

x + y is greater than 20

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

. if(condition) {
. statement 1; //executes when condition is true
. }
. else{
. statement 2; //executes when condition is false
. }
Consider the following example.

Student.java

. public class Student {


. public static void main(String[] args) {
. int x = 10;
. int y = 12;
. if(x+y < 10) {
. System.out.println("x + y is less than 10");
. } else {
. System.out.println("x + y is greater than 20");
. }
. }
. }
Output:
x + y is greater than 20

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.

Advertisement
Syntax of if-else-if statement is given below.

. if(condition 1) {
. statement 1; //executes when condition 1 is true
. }
. else if(condition 2) {
. statement 2; //executes when condition 2 is true
. }
. else {
. statement 2; //executes when all the conditions are false
. }
Consider the following example.

Student.java

. public class Student {


. public static void main(String[] args) {
. String city = "Delhi";
. if(city == "Meerut") {
. System.out.println("city is meerut");
. }else if (city == "Noida") {
. System.out.println("city is noida");
. }else if(city == "Agra") {
. System.out.println("city is agra");
. }else {
. System.out.println(city);
. }
. }
. }
Output:
Delhi

4. Nested if-statement

Advertisement
In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.

Syntax of Nested if-statement is given below.

. if(condition 1) {
. statement 1; //executes when condition 1 is true
. if(condition 2) {
. statement 2; //executes when condition 2 is true
. }
. else{
. statement 2; //executes when condition 2 is false
. }
. }
Consider the following example.

Student.java

. public class Student {


. public static void main(String[] args) {
. String address = "Delhi, India";
.
. if(address.endsWith("India")) {
. if(address.contains("Meerut")) {
. System.out.println("Your city is Meerut");
. }else if(address.contains("Noida")) {
. System.out.println("Your city is Noida");
. }else {
. System.out.println(address.split(",")[0]);
. }
. }else {
. System.out.println("You are not living in India");
. }
. }
. }
Output:
Delhi

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.

Advertisement
Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.

. switch (expression){
. case value1:
. statement1;
. break;
. .
. .
. .
. case valueN:
. statementN;
. break;
. default:
. default statement;
. }
Consider the following example to understand the flow of the switch statement.

Student.java

. public class Student implements Cloneable {


. public static void main(String[] args) {
. int num = 2;
. switch (num){
. case 0:
. System.out.println("number is 0");
. break;
. case 1:
. System.out.println("number is 1");
. break;
. default:
. System.out.println(num);
. }
. }
. }
Output:

While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value. The switch permits only int,
string, and Enum type variables to be used.

Loop Statements

In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.

. for(initialization, condition, increment/decrement) {


. //block of statements
. }
The flow chart for the for-loop is given below.

Consider the following example to understand the proper functioning of the for loop in java.

Calculation.java

. public class Calculattion {


. public static void main(String[] args) {
. // TODO Auto-generated method stub
. int sum = 0;
. for(int j = 1; j<=10; j++) {
. sum = sum + j;
. }
. System.out.println("The sum of first 10 natural numbers is " + sum);
. }
. }
Output:

The sum of first 10 natural numbers is 55

Java for-each loop

Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable. The syntax to use the for-each
loop in java is given below.

. for(data_type var : array_name/collection_name){


. //statements
. }
Consider the following example to understand the functioning of the for-each loop in Java.

Calculation.java

. public class Calculation {


. public static void main(String[] args) {
. // TODO Auto-generated method stub
. String[] names = {"Java","C","C++","Python","JavaScript"};
. System.out.println("Printing the content of the array names:\n");
. for(String name:names) {
. System.out.println(name);
. }
. }
. }
Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop

The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.

The syntax of the while loop is given below.

. while(condition){
. //looping statements
. }
The flow chart for the while loop is given in the following image.

Consider the following example.

Calculation .java

. public class Calculation {


. public static void main(String[] args) {
. // TODO Auto-generated method stub
. int i = 0;
. System.out.println("Printing the list of first 10 even numbers \n");
. while(i<=10) {
. System.out.println(i);
. i = i + 2;
. }
. }
. }
Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Java do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.

. do
. {
. //statements
. } while (condition);
The flow chart of the do-while loop is given in the following image.

Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java

. public class Calculation {


. public static void main(String[] args) {
. // TODO Auto-generated method stub
. int i = 0;
. System.out.println("Printing the list of first 10 even numbers \n");
. do {
. System.out.println(i);
. i = i + 2;
. }while(i<=10);
. }
. }
Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Jump Statements

Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.

Java break statement

As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.

BreakExample.java
. public class BreakExample {
.
. public static void main(String[] args) {
. // TODO Auto-generated method stub
. for(int i = 0; i<= 10; i++) {
. System.out.println(i);
. if(i==6) {
. break;
. }
. }
. }
. }
Output:

0
1
2
3
4
5
6

break statement example with labeled for loop

Calculation.java

. public class Calculation {


.
. public static void main(String[] args) {
. // TODO Auto-generated method stub
. a:
. for(int i = 0; i<= 10; i++) {
. b:
. for(int j = 0; j<=15;j++) {
. c:
. for (int k = 0; k<=20; k++) {
. System.out.println(k);
. if(k==5) {
. break a;
. }
. }
. }
.
. }
. }
.
.
. }
Output:

0
1
2
3
4
5

Java continue statement

Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue statement in
Java.

. public class ContinueExample {


.
. public static void main(String[] args) {
. // TODO Auto-generated method stub
.
. for(int i = 0; i<= 2; i++) {
.
. for (int j = i; j<=5; j++) {
.
. if(j == 4) {
. continue;
. }
. System.out.println(j);
. }
. }
. }
.
. }
Output:
0
1
2
3
5
1
2
3
5
2
3
5

UNIT-II

java package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package


The package keyword is used to create a package in java.

. //save as Simple.java
. package mypack;
. public class Simple
. {
. public static void main(String args[])
. {
. System.out.println("Welcome to package");
. }
. }

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

. javac -d directory javafilename


For example

. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .
represents the current folder.

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

The import keyword is used to make the classes and interface of another package accessible
to the current package.

Example of package that import the packagename.*

. //save by A.java
. package pack;
. public class A{
. public void msg(){System.out.println("Hello");}
. }

. //save by B.java
. package mypack;
. import pack.*;
.
. class B{
. public static void main(String args[]){
. A obj = new A();
. obj.msg();
. }
. }

Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

. //save by A.java
.
. package pack;
. public class A{
. public void msg(){System.out.println("Hello");}
. }

. //save by B.java
. package mypack;
. import pack.A;
.
. class B{
. public static void main(String args[]){
. A obj = new A();
. obj.msg();
. }
. }

Output:Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name

. //save by A.java
. package pack;
. public class A{
. public void msg(){System.out.println("Hello");}
. }

. //save by B.java
. package mypack;
. class B{
. public static void main(String args[]){
. pack.A obj = new pack.A();//using fully qualified name
. obj.msg();
. }
. }

Output:Hello

Note: If you import a package, subpackages will not be imported.


If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
Note: Sequence of the program must be package then import then class.

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the
package further.Let's take an example, Sun Microsystem has definded a package named
java that contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output operation,
Socket and ServerSocket classes are for networking etc and so on. So, Sun has
subcategorized the java package into subpackages such as lang, net, io etc. and put the
Input/Output related classes in io package, Server and ServerSocket classes in net packages
and so on.

The standard of defining package is domain.company.package e.g. com.javatpoint.bean


or org.sssit.dao.
Example of Subpackage
. package com.javatpoint.core;
. class Simple{
. public static void main(String args[]){
. System.out.println("Hello subpackage");
. }
. }
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage

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

What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.

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

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

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

. statement 1;
. statement 2;
. statement 3;
. statement 4;
. statement 5;//exception occurs
. statement 6;
. statement 7;
. statement 8;
. statement 9;
. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed.
That is why we use exception handling in Java.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as
the unchecked exception. However, according to Oracle, there are three types of exceptions
namely:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions

1) Checked Exception

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

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

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords

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

Keyword Description

The "try" keyword is used to specify a block


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

The "catch" block is used to handle the exception.


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

The "finally" block is used to execute the


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

The "throw" keyword is used to throw an


throw
exception.

The "throws" keyword is used to declare


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

Java Exception Handling Example

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

. public class JavaExceptionExample{


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

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch


block.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

. String s=null;
. System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters; converting
this variable into digit will cause NumberFormatException.

. String s="abc";
. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.

. int a[]=new int[5];


. a[10]=50; //ArrayIndexOutOfBoundsException

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

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


multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.

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

Advantages of Java Multithreading

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

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

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


single thread.
Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

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

2) Thread-based Multitasking (Multithreading)

o Threads share the same address space.


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

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

What is Thread in java

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


execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.

Life cycle of a Thread (Thread States)

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

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

Explanation of Different Thread States

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

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

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

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

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

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

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

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

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is
dead, and there is no way one can respawn (active after kill) the dead thread.

The following diagram shows the different states involved in the life cycle of a thread.
Java Threads | How to create a thread in Java

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

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

Commonly used Constructors of Thread class:

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

Commonly used methods of Thread class:

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


2. public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().

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

Starting a thread:

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

o A new thread starts(with new callstack).


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

1) Java Thread Example by extending Thread class

FileName: Multi.java

. class Multi extends Thread{


. public void run(){
. System.out.println("thread is running...");
. }
. public static void main(String args[]){
. Multi t1=new Multi();
. t1.start();
. }
. }
Output:

thread is running...

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

. class Multi3 implements Runnable{


. public void run(){
. System.out.println("thread is running...");
. }
.
. public static void main(String args[]){
. Multi3 m1=new Multi3();
. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
. t1.start();
. }
. }
Output:

thread is running...

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

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

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

FileName: MyThread1.java

. public class MyThread1


. {
. // Main method
. public static void main(String argvs[])
. {
. // creating an object of the Thread class using the constructor Thread(String name)
. Thread t= new Thread("My first thread");
.
. // the start() method moves the thread to the active state
. t.start();
. // getting the thread name by invoking the getName() method
. String str = t.getName();
. System.out.println(str);
. }
. }
Output:

My first thread

4) Using the Thread Class: Thread(Runnable r, String name)

Observe the following program.

FileName: MyThread2.java

. public class MyThread2 implements Runnable


. {
. public void run()
. {
. System.out.println("Now the thread is running ...");
. }
.
. // main method
. public static void main(String argvs[])
. {
. // creating an object of the class MyThread2
. Runnable r1 = new MyThread2();
.
. // creating an object of the class Thread using Thread(Runnable r, String name)
. Thread th1 = new Thread(r1, "My new thread");
.
. // the start() method moves the thread to the active state
. th1.start();
.
. // getting the thread name by invoking the getName() method
. String str = th1.getName();
. System.out.println(str);
. }
. }
Output:

My new thread
Now the thread is running ...

this keyword in Java

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current
object.

Usage of Java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance
variables and parameters, this keyword resolves the problem of ambiguity.

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:

. class Student{
. int rollno;
. String name;
. float fee;
. Student(int rollno,String name,float fee){
. rollno=rollno;
. name=name;
. fee=fee;
. }
. void display(){System.out.println(rollno+" "+name+" "+fee);}
. }
. class TestThis1{
. public static void main(String args[]){
. Student s1=new Student(111,"ankit",5000f);
. Student s2=new Student(112,"sumit",6000f);
. s1.display();
. s2.display();
. }}
Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we are using this
keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword

. class Student{
. int rollno;
. String name;
. float fee;
. Student(int rollno,String name,float fee){
. this.rollno=rollno;
. this.name=name;
. this.fee=fee;
. }
. void display(){System.out.println(rollno+" "+name+" "+fee);}
. }
.
. class TestThis2{
. public static void main(String args[])
. {
. Student s1=new Student(111,"ankit",5000f);
. Student s2=new Student(112,"sumit",6000f);
. s1.display();
. s2.display();
. }}
Output:

111 ankit 5000.0


112 sumit 6000.0

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use the this keyword,
compiler automatically adds this keyword while invoking the method. Let's see the example

. class A{
. void m(){System.out.println("hello m");}
. void n(){
. System.out.println("hello n");
. //m();//same as this.m()
. this.m();
. }
. }
. class TestThis4{
. public static void main(String args[]){
. A a=new A();
. a.n();
. }}

Output:

hello n
hello m
3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor.
In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

. class A{
. A(){System.out.println("hello a");}
. A(int x){
. this();
. System.out.println(x);
. }
. }
. class TestThis5{
. public static void main(String args[]){
. A a=new A(10);
. }}

Output:

hello a
10

4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's
see the example:

. class S2{
. void m(S2 obj){
. System.out.println("method is invoked");
. }
. void p(){
. m(this);
. }
. public static void main(String args[]){
. S2 s1 = new S2();
. s1.p();
. }
. }

Output:
method is invoked

Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to
reuse one object in many methods.

5) this: to pass as argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes.
Let's see the example:

. class B{
. A4 obj;
. B(A4 obj){
. this.obj=obj;
. }
. void display(){
. System.out.println(obj.data);//using data member of A4 class
. }
. }
.
. class A4{
. int data=10;
. A4(){
. B b=new B(this);
. b.display();
. }
. public static void main(String args[]){
. A4 a=new A4();
. }
. }

Output:10

6) this keyword can be used to return current class instance

We can return this keyword as an statement from the method. In such case, return type of the method must be
the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement


. return_type method_name(){
. return this;
. }
Example of this keyword that you return as a statement from the method
. class A{
. A getA(){
. return this;
. }
. void msg(){System.out.println("Hello java");}
. }
. class Test1{
. public static void main(String args[]){
. new A().getA().msg();
. }
. }
Output:

Hello java

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred
by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if parent class and child
class have same fields.

. class Animal{
. String color="white";
. }
. class Dog extends Animal{
. String color="black";
. void printColor(){
. System.out.println(color);//prints color of Dog class
. System.out.println(super.color);//prints color of Animal class
. }
. }
. class TestSuper1{
. public static void main(String args[]){
. Dog d=new Dog();
. d.printColor();
. }}

Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If we print color property, it
will print the color of current class by default. To access the parent property, we need to use super keyword.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if subclass contains the
same method as parent class. In other words, it is used if method is overridden.

. class Animal{
. void eat(){System.out.println("eating...");
. }
. }
. class Dog extends Animal{
. void eat(){System.out.println("eating bread...");
. }
. void bark(){System.out.println("barking...");
. }
. void work(){
. super.eat();
. bark();
. }
. }
. class TestSuper2{
. public static void main(String args[]){
. Dog d=new Dog();
. d.work();
. }}

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it
will call the eat() method of Dog class by default because priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:

. class Animal{
. Animal(){System.out.println("animal is created");}
. }
. class Dog extends Animal{
. Dog(){
. super();
. System.out.println("dog is created");
. }
. }
. class TestSuper3{
. public static void main(String args[])
. {
. Dog d=new Dog();
. }}
Output:

animal is created
dog is created

UNIT-III

Java I/O

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

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

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

Core Concepts of Java I/O

Java I/O revolves around two primary concepts: streams and readers/writers.

Streams: Streams represent a sequence of data. In Java, there are two types of streams: input streams
and output streams. Input streams are used to read data from a source, while output streams are used
to write data to a destination. Streams can be categorized into byte streams (InputStream and
OutputStream) and character streams (Reader and Writer).

Readers/Writers: Readers and writers are specialized stream classes designed for handling character
data. They provide a convenient way to read from and write to character-based data sources. Readers
read character data from input streams, while writers write character data to output streams.

Stream

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

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

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

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

. System.out.println("simple message");
. System.err.println("error message");
Let's see the code to get input from console.

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


. System.out.println((char)i);//will print the character

OutputStream Vs. InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

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

InputStream

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

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

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

Useful Methods of OutputStream Class

Method Description

public void write(int) throws IOException It is used to write a byte to the current output stream.

It is used to write an array of byte to the current output


public void write(byte[])throws IOException
stream.

public void flush() throws IOException It flushes the current output stream.

public void close() throws IOException It is used to close the current output stream.

OutputStream Hierarchy
InputStream Class

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

Useful Methods of InputStream Class

Method Description

It reads the next byte of data from the input stream. It


public abstract int read() throws IOException
returns -1 at the end of the file.

It returns an estimate of the number of bytes that can


public int available() throws IOException
be read from the current input stream.

public void close() throws IOException It is used to close the current input stream.

InputStream Hierarchy
Java I/O Classes

1. Java provides a rich set of classes for performing I/O operations. Some of the key classes
include:
2. InputStream and OutputStream: These abstract classes form the foundation for byte-
oriented I/O operations. They provide methods for reading and writing bytes from/to various
sources and destinations.
3. Reader and Writer: These abstract classes are used for character-based I/O operations. They
provide methods for reading and writing characters from/to character-based streams.
4. FileInputStream and FileOutputStream: These classes allow reading from and writing to
files in a byte-oriented manner.
5. FileReader and FileWriter: These classes enable reading from and writing to files using
character-oriented operations.
6. BufferedInputStream and BufferedOutputStream: These classes provide buffering
capabilities, which can significantly improve I/O performance by reducing the number of
system calls.
7. BufferedReader and BufferedWriter: These classes offer buffered reading and writing of
character data, enhancing I/O efficiency when working with character-based streams.

Practical Applications of Java I/O

Java I/O is employed in various real-world scenarios, including:

1. File Handling: Java I/O is extensively used for reading from and writing to files. Developers
can manipulate files, create directories, and perform file-related operations using Java's file
I/O classes.
2. Network Communication: Java's socket classes (Socket and ServerSocket) facilitate
network communication by enabling data exchange between client and server applications
over TCP/IP.
3. Serialization: Java's serialization mechanism allows objects to be converted into a stream of
bytes for storage or transmission. It is particularly useful for storing object state or
transferring objects between applications.
4. Data Processing: Java I/O is integral to data processing tasks such as parsing text files,
processing CSV data, and interacting with databases through JDBC (Java Database
Connectivity).

Best Practices for Java I/O

When working with Java I/O, consider the following best practices:

1. Use Try-with-Resources: Always use the try-with-resources statement when working with
streams to ensure proper resource management. This automatically closes the streams when
they are no longer needed, preventing resource leaks.
2. Use Buffered I/O: Whenever possible, use buffered I/O classes to minimize the number of
system calls and improve performance.
3. Handle Exceptions Gracefully: Handle I/O exceptions gracefully by implementing error
handling mechanisms such as logging or error propagation.
4. Use NIO for Performance: For high-performance I/O operations, consider using Java's NIO
(New I/O) package, which provides non-blocking I/O features and enhanced performance.
Console in Java

In this section, we will learn everything about the Console in Java, i.e., what a console is, how we can use the
console, how we can implement output in the console, how we can take input using the console, etc.

What is a Console?

To run a program, we might need input from the programmer or user according to the requirement. We cannot
always take input just from the program. Sometimes, we can take the input from the console or terminal too.
The process of taking input from the console is introduced by the concept of Java Console. Java programming
language provides several ways in order to take input from the console and provide its corresponding output on
the same console.

Java Console

Using the Console in Java, we can consider taking input and displaying the output. Generally, Console is mainly
meant for taking input. There are three ways to take the input from the Java console. They are:

1. Using Java Scanner class (Basic level)


2. Using Java BufferedReader class (Intermediate level)
3. Using Java Console class

Scanner class in Java

A class that is used to scan inputs within the program is known as the Scanner class. We use this class to take
the input within the program by creating an abject in the Scanner class. It is one of the easiest ways to scan the
input from the user using the console. It is used to scan all the regular expressions in Java. The Scanner class is
available in the util package. So, in order to scan the inputs using the Scanner class, we need to import the "
Java.util " package.

Syntax of Scanner class:

. Scanner obj = new Scanner(System.in);


Here, " Scanner " is considered as a class and " obj " is an object that is created within a class. So, in order to
scan any input in the entire program, we can use this object that is created in the " Scanner " class.

There are different methods used for scanning different data types. The type of method that we consider depends
on the data type of the input that we want to take. There are eight methods in the Scanner class, as there are
eight general Primitive data types.

Methods in Scanner class:

1. nextByte()
The method that deals with reading a Byte value from the user are nextByte()
2. nextDouble()
The method that deals with reading a Double value from the user are nextDouble()
3. nextFloat()
The method that deals with reading a Float value from the user are nextFloat()
4. nextInt()
The method that deals with reading an Int value from the user are nextInt()
5. nextLine()
The method that deals with reading a String value from the user are nextLine()
6. nextLong()
The method that deals with reading a Long value from the user are nextLong()
7. nextShort()
The method that deals with reading a Short value from the user are nextShort()

nextBoolean()
The method that deals with reading a Boolean value from the user are nextBoolean()A program that
demonstrates Scanner class to scan an input:

. // program to implement Scanner class


. // to scan the input from the user
.
. // import the Scanner class from the " util.Scanner " package
. import Java.util.Scanner;
.
. // consider a class Demo
. public class Demo
. {
. // initiate main section
. public static void main(String[] args)
. {
. // initiate and implement Scanner class
. Scanner obj = new Scanner(System.in);
. // scan an integer
. System.out.println("Enter an integer number: ");
. int x = obj.nextInt();
.
. // scan a float value
. System.out.print("Enter a Float number: ");
. float y = obj.nextFloat();
.
. // scan a String value
. System.out.print("Enter a String: ");
. String z = obj.nextLine();
. String a = obj.nextLine();
.
. // scan a Boolean value
. System.out.print("Enter a Boolean value: ");
. Boolean w = obj.nextBoolean();
.
. System.out.println("You have entered an Integer number ");
. System.out.println(x);
. System.out.println("You have entered a Float number ");
. System.out.println(y);
. System.out.println("You have entered a String ");
. System.out.println(a);
. System.out.println("You have entered a Boolean value");
. System.out.println(w);
. }
. }
Input:

. Enter an integer number: 5


. Enter a Float number: 3.4
. Enter a String: Hello
. Enter a Boolean value: True
Output:

You have entered an Integer number


5
You have entered a Float number
3.4
You have entered a String
Hello
You have entered a Boolean value
true

Advantages of Scanner class:

o This class provides several methods according to the data type used and that match the user's
requirement.
o It is the basic class used to scan an input that runs on almost all versions of Java.
Disadvantages of Scanner class:

o It runs and executes a little slower as the data must be parsed before being executed.
o The methods that are part of the class " Scanner " are not synchronized.

BufferedReader class in Java:

It is one of the classical methods of taking input from the user ( sometimes by using a console also ). A new
statement, " InputStreamReader " is also introduced along with the " BufferedReader " in order to scan the input
values using BufferedReader. Let us look at the mechanism of BufferedReader with its syntax followed by a
program.

Syntax of BufferedReader class:

. InputStreamReader obj1 = new InputStreamReader(System.in);


.
. BufferedReader obj2 = new BufferedReader(obj1);
Methods in BufferedReader class

1. readLine()
The method " readLine() " is used to scan the String values from the user.
2. parseInt()
The method " Integer.parseInt() " is used to scan the integer values from the user.
3. parseDouble()
The method " Double.parseDouble() " is used to scan the double values from the user.
4. parseFloat()
The method " Float.parseFloat() " is used to scan the float values from the user.

A program that demonstrates BufferedReader class to scan an input:

. import Java.io.BufferedReader;
. import Java.io.InputStreamReader;
. import Java.io.*;
.
. public class Demo
. {
. public static void main(String[] args) throws IOException
. {
. // initiate InputStreamReader class initially
. // and create an object within the class
. // InputStreamReader
. InputStreamReader obj1 = new InputStreamReader(System.in);
.
. // you can take the input using the BufferReader class
. // and by using the object created in the
. // InputStreamReader class
. BufferedReader obj2 = new BufferedReader(obj1);
.
. // scanning a string
. System.out.print("Enter a String: ");
. String s = obj2.readLine();
.
. // scanning a integer value
. System.out.print("Enter an integer value: ");
. int x = Integer.parseInt(obj2.readLine());
.
. // scanning a float value
. System.out.print("Enter a float value: ");
. float y = Float.parseFloat(obj2.readLine());
.
. // scanning a double value
. System.out.print("Enter a double value: ");
. double z = Double.parseDouble(obj2.readLine());
.
. // printing the values using the print statement
.
. // Printing the String
. System.out.print("The entered String is: ");
. System.out.println(s);
.
. // printing the value of integer entered
. System.out.print("The entered value of integer is: ");
. System.out.println(x);
.
. // printing the value of float entered
. System.out.print("The entered value of float is: ");
. System.out.println(y);
.
. // printing the value of double entered
. System.out.print("The entered value of double is: ");
. System.out.println(z);
.
. }
. }
Input:

. Enter a String: Hello


. Enter an integer value: 10
. Enter a float value: 3.5
. Enter a double value: 9.88
Output:

The entered String is: Hello


The entered value of integer is: 10
The entered value of float is: 3.5
The entered value of double is: 9.88

Advantages of BufferedReader class:

o All the methods that are provided by this class are completely synchronized.
o It is the mandatory class used to scan an input, mainly during the " Multi-threading " concept.
o This class has a large Buffer compared to the Scanner class.
o The speed of execution is faster when compared to the Scanner class.
Disadvantages of BufferedReader class

The methods present in the BufferedReader class are not in-built but should be parsed while using.

Java Console class in Java

The class " Console " in Java was introduced from Java version 1.5 and was brought into charge from that
version. It was one of the most anticipated usages in Java Programming language. The class " Console " can be
accessed through the package " Java.io " which is the basic package that is used in all programs constructed in
Java. There are several methods that are embedded within the " Console " class. Let us study all those methods
in the upcoming statements.

One of the major advantages of using the class " Console " in Java is that the confidential data or information
like passwords are hidden while taking input as well as printing output. This is the major reason for preferring
the Console class in Java. Not only this feature, but the methods of the console that can be read are also always
synchronized. But, the Console class can only be executed on command prompt or terminal but not on any other
IDE platforms. Basically, the class " Console " in Java does not have a specified syntax. The syntax and usage
of the " Console " class change depending on the purpose and situation the program is being performed.

Methods in Console class:

1. readLine()
The method that is used to read a single line of text or String from the console is the " readLine() "
method. This method can be accessed or used when an object is created within the String class.
2. readLine( String, Object )
The method that is used to provide a prompt that is formatted priorly in order to receive an input from
the console is the " readLine( String, Object ) " method. This method can be used when an object is
created within a String class. The only difference between the method " readLine() " and the method "
readLine( String, Object ) " is the type and number of arguments that are being passed through those
methods.
3. readPassword()
The method that is used to read or scan a password as an input in a way such that the input taken is
shown or visible at any time on the screen is the " readPassword() " method. The data type that is
supposed to be considered in this method is a Character array or " char[] ".
4. readPassword( String, Object )
The method that is used to read or scan a password as an input in a confidential way such that the input
taken is shown or visible any time on the screen along with providing a formatted prompt is the "
readPassword( String, Object ) " method. The data type that is supposed to be considered in this
method is a Character array or " char[] ".
5. reader()
The method is called by an object created in the class " Reader() " which handles and relates to the
console. This method also helps in the creation of the object in the class " Reader() ".
6. Console printf( String, Object )
The method that is used in order to print a string within the output of the console is " printf() ". It can
be accessed using the class " Console() ".
7. flush()
The method that is used to clear all the statements or the matter present on the console is " flush() ". It
is a general method which is neither creates an object nor will be accessed by an object created within a
particular class. It just removes the matter on the console screen. Its return data type is generally " void
".
8. Console format( String, Object )
The method that prints a formatted string ( when asked for print ) on the output screen of the console is
the " format( String, Object ) " method. We generally use this in order to have a classified string that is
arranged perfectly as per the requirement. This method can be accessed and is also a part of the class "
Console ".

Not only these methods, but there are also several other methods that are a part of the class " Console ". The
usage of the methods depends on the way the program runs and the operation that the program wants to perform.

A program that demonstrates Console class to scan an input:

. // import the required package, i.e., " Java.io "


. import Java.io.*;
. import Java.io.Console;
.
. // consider a public class with any random
. // name in order to consider it as the main class
. public class Demo2
. {
. // a main section where objects can be
. // declared within the class " Console "
. public static void main(String[] args)
. {
. // Using Console to
. // take an input of the data from the user
. System.out.println("You can enter an input using Console now!! ");
.
. // create an object " c " within
. // the Console class to access its methods
. Console c = System.console();
.
. // Consider taking input from the user
. // using Console class
. System.out.print("Enter the first input: ");
. // declare a String using a variable
. // for example, consider a variable " x " under
. // the String data type
. String x = c.readLine();
. System.out.println("The String that you have entered is: ");
. System.out.println(x);
.
. // using Reader class helps in order to
. // find the reader object of the Console class
. System.out.println("Let us find the reader object of the Console class: ");
. Reader r = c.reader();
.
. // printing the reader object of the console class
. // using reader object
. System.out.println("The reader object of the Console class is: ");
. System.out.print(r);
. }
. }
Input:

. Enter the first input: Hello


Output:

You can enter an input using Console now!!


Enter the first input: Hello
The String that you have entered is :
Hello
Let us find the reader object of the Console class:
The reader object of the Console class is:
Java.io.Console$LineReader@1be6f5c3

Input 2:

. Enter the first input: World


Output 2:

You can enter an input using Console now!!


Enter the first input: World
The String that you have entered is :
World
Let us find the reader object of the Console class:
The reader object of the Console class is:
Java.io.Console$LineReader@1be6f5c3

Java PrintWriter Class

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

It provides convenient methods for writing various data types, such as integers, doubles, and
strings, to a file or any other output destination. PrintWriter is often used in conjunction with
other I/O classes like FileWriter or BufferedWriter to write data to files efficiently. One
advantage of using PrintWriter is its ability to automatically handle line breaks and
conversions of primitive data types to text representations. Additionally, it offers methods for
formatting output using printf-style formatting. Overall, PrintWriter simplifies the process of
writing formatted text data to output streams in Java applications.
Class Declaration

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

. public class PrintWriter extends Writer


. {
. ….…..
. }
When creating a PrintWriter to write to a file, you can specify the character encoding to use.
This is particularly important when dealing with international characters or when you need to
ensure compatibility with specific systems. For example, you can specify the encoding as
follows:

. PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStrea


m("file.txt"), StandardCharsets.UTF_8));
.

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

Javatpoint provides tutorials of all technology.


Testout.txt

Like Java, Spring, Hibernate, Android, PHP etc.

String handling
In Java, Strings are the type of objects that can store the sequence of characters enclosed
by double quotes and every character is stored in 16 bits i.e using UTF 16-bit encoding. A
string acts the same as an array of characters. Java provides a robust and flexible API for
handling strings, allowing for various operations such as concatenation, comparison,
and manipulation.
Example:
String name = “Geeks”;
String num = “1234”
Ex-1:
public class Geeks {

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

// creating Java string using new keyword


String str = new String("GeeksforGeeks");

System.out.println(str);
}
}
Ex-2:
// Java Program to Create a String
import java.io.*;

class GFG {
public static void main (String[] args) {

// String literal
String s1="String1";
System.out.println(s1);

// Using new Keyword


String s2= new String("String2");
System.out.println(s2);
}
}
Ways of Creating a String
There are two ways to create a string in Java:
• String Literal
• Using new Keyword
Syntax:
<String_Type> <string_variable> = “<sequence_of_string>”;

1. String literal (Static Memory)

To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
Example:
String demoString = “GeeksforGeeks”;

2. Using new keyword (Heap Memory)

• String s = new String(“Welcome”);


• In such a case, JVM will create a new string object in normal (non-pool) heap
memory and the literal “Welcome” will be placed in the string constant pool. The
variable s will refer to the object in the heap (non-pool)
In the given example only one object will be created. Firstly JVM will not find any string
object with the value “Welcome” in the string constant pool, so it will create a new object.
After that it will find the string with the value “Welcome” in the pool, it will not create a
new object but will return the reference to the same instance.
Example:
String demoString = new String (“GeeksforGeeks”);
String Constructors in Java
String Constructor Description

1. String(byte[] byte_arr) Construct a new String by decoding the byte


array. It uses the platform’s default character set
for decoding.

2. String(byte[] byte_arr, Charset Construct a new String by decoding the byte


char_set) array. It uses the char_set for decoding.

3. String(byte[] byte_arr, int Construct a new string from the bytes


start_index, int length) array depending on the start_index(Starting
location) and length(number of characters from
starting location).

4. String(byte[] byte_arr, int Construct a new string from the bytes


start_index, int length, Charset array depending on the start_index(Starting
char_set) location) and length(number of characters from
starting location).Uses char_set for decoding.

5. String(char[] char_arr) Allocates a new String from the given Character


array.

6. String(char[] char_array, int Allocates a String from a given character


start_index, int count) array but choose count characters from
the start_index.

7. String(int[] uni_code_points, int Allocates a String from a uni_code_array but


offset, int count) choose count characters from the start_index.

8. String(StringBuffer s_buffer) Allocates a new string from the string in s_buffer.

9. String(StringBuilder s_builder) Allocates a new string from the string


String Constructor Description

in s_builder.

String Methods in Java


String Method Description

1. int length() Returns the number of characters in the String.

2. Char charAt(int i) Returns the character at ith index.

3. String substring (int i) Return the substring from the ith index character
to end.

4. String substring (int i, int j) Returns the substring from i to j-1 index.

5. String concat( String str) Concatenates specified string to the end of this
string.

6. int indexOf (String s) Returns the index within the string of the first
occurrence of the specified string.
If String s is not present in input string then -1 is
returned as the default value.

7. int indexOf (String s, int i) Returns the index within the string of the first
occurrence of the specified string, starting at the
specified index.

8. Int lastIndexOf( String s) Returns the index within the string of the last
occurrence of the specified string.
If String s is not present in input string then -1 is
returned as the default value.

9. boolean equals( Object otherObj) Compares this string to the specified object.

10. boolean equalsIgnoreCase Compares string to another string, ignoring case


(String anotherString) considerations.
String Method Description

11. int compareTo( String Compares two string lexicographically.


anotherString)

12. int compareToIgnoreCase( String Compares two string lexicographically, ignoring


anotherString) case considerations.
Note: In this case, it will not consider case of a
letter (it will ignore whether it is uppercase or
lowercase).

13. String toLowerCase() Converts all the characters in the String to lower
case.

14. String toUpperCase() Converts all the characters in the String to upper
case.

15. String trim() Returns the copy of the String, by removing


whitespaces at both ends. It does not affect
whitespaces in the middle.

16. String replace (char oldChar, Returns new string by replacing all occurrences
char newChar) of oldChar with newChar.
Note: s1 is still feeksforfeeks and s2 is
geeksgorgeeks

17. boolean contains(CharSequence Returns true if string contains contains the given
sequence) string.

18. Char[] toCharArray(): Converts this String to a new character array.

19. boolean startsWith(String prefix) Return true if string starts with this prefix.

Java String concat() Method with Examples

The string concat() method concatenates (appends) a string to the end of another string. It
returns the combined string. It is used for string concatenation in Java. It
returns NullPointerException if any one of the strings is Null.
In this article, we will learn how to concatenate two strings in Java.
Program to Concatenate Two Strings using concat() Method in Java
Below is the simplest method to concatenate the string in Java. We will be using
the concat() method of String class to append one string to the end of another and return the
new string.
// Java Program to Illustrate concat() method of String.
class GFG {
public static void main(String args[]) {
// String Initialization
String s = "Geeks";
// Use concat() method for string concatenation
s = s.concat("forGeeks");
System.out.println(s);
}
}
Output
GeeksforGeeks

StringBuffer class in Java


StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an
alternative to the immutable String class, allowing you to modify the contents of a string
without creating a new object every time.

Features of StringBuffer Class

Here are some important features and methods of the StringBuffer class:
• StringBuffer objects are mutable, meaning that you can change the contents of the
buffer without creating a new object.
• The initial capacity of a StringBuffer can be specified when it is created, or it can be
set later with the ensureCapacity() method.
• The append() method is used to add characters, strings, or other objects to the end of
the buffer.
• The insert() method is used to insert characters, strings, or other objects at a specified
position in the buffer.
• The delete() method is used to remove characters from the buffer.
• The reverse() method is used to reverse the order of the characters in the buffer.

Here is an example of using StringBuffer to concatenate strings:

// Java Program to Demonstrate


// String Buffer
public class StringBufferExample {
public static void main(String[] args){

// Creating StringBuffer
StringBuffer s = new StringBuffer();

// Adding elements in StringBuffer


s.append("Hello");
s.append(" ");
s.append("world");

// String with the StringBuffer value


String str = s.toString();
System.out.println(str);
}
}
Output
Hello world

Advantages of using StringBuffer in Java

There are several advantages of using StringBuffer over regular String objects in Java:
• Mutable: StringBuffer objects are mutable, which means that you can modify the
contents of the object after it has been created. In contrast, String objects are immutable,
which means that you cannot change the contents of a String once it has been created.
• Efficient: Because StringBuffer objects are mutable, they are more efficient than
creating new String objects each time you need to modify a string. This is especially true if
you need to modify a string multiple times, as each modification to a String object creates
a new object and discards the old one.
StringBuffer class is used to create mutable (modifiable) strings. The StringBuffer class in
Java is the same as the String class except it is mutable i.e. it can be changed.
Constructors of StringBuffer Class
Constructor Description Syntax

StringBuffer() It reserves room for 16


characters without StringBuffer s = new StringBuffer();
reallocation
Constructor Description Syntax

StringBuffer(int size) It accepts an integer


argument that explicitly StringBuffer s = new StringBuffer(20);
sets the size of the buffer.

StringBuffer(String It accepts a
str) string argument that sets
the initial contents of the
StringBuffer s
StringBuffer object and
= new StringBuffer(“GeeksforGeeks”);
reserves room for 16 more
characters without
reallocation.

Methods of Java StringBuffer Class


Methods Action Performed

append() Used to add text at the end of the existing text.

length() The length of a StringBuffer can be found by the length( ) method.

capacity() the total allocated capacity can be found by the capacity( ) method.

This method returns the char value in this sequence at the specified
charAt()
index.

delete() Deletes a sequence of characters from the invoking object.

deleteCharAt() Deletes the character at the index specified by the loc.

ensureCapacity() Ensures capacity is at least equal to the given minimum.

insert() Inserts text at the specified index position.

length() Returns the length of the string.

reverse() Reverse the characters within a StringBuffer object.

Replace one set of characters with another set inside a StringBuffer


replace()
object.
StringTokenizer
StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer
object internally maintains a current position within the string to be tokenized. Some
operations advance this current position past the characters processed.
A token is returned by taking a substring of the string that was used to create the
StringTokenizer object. It provides the first step in the parsing process often called lexer or
scanner.
Java String Tokenization
The StringTokenizer class allows an application to break a string into tokens based on
delimiters. It implements the Enumeration interface. To use StringTokenizer, we need to
specify an input string and a set of delimiters. A delimiter is a character or set of characters
that separate tokens in the string.
Illustration:

Constructors of StringToken
Let us consider ‘str’ as the string to be tokenized. In that case we have three constructor
cases as mentioned below:

Constructor Description

Default delimiters like newline, space,


StringTokenizer(String str)
tab, carriage return, and form feed.

StringTokenizer(String str, String delim is a set of delimiters that are used


delim) to tokenize the given string.
Constructor Description

The first two parameters have the same


StringTokenizer(String str, String
meaning wherein The flag serves the
delim, boolean flag)
following purpose.

Cases of StringToken Constructors

1. If the flag is false, delimiter characters serve to separate tokens


Example:
Input : if string --> "hello geeks" and Delimiter is " ", then
Output: tokens are "hello" and "geeks".
2. If the flag is true, delimiter characters are considered to be tokens.
Example:
Input : String --> is "hello geeks"and Delimiter is " ", then
Output: Tokens --> "hello", " " and "geeks".
3. Multiple delimiters can be chosen for a single string.
Example:
Syntax: StringTokenizer st1 = new StringTokenizer( "2+3-1*8/4", "+*-/");

Input : String --> is "2+3-1*8/4" and Delimiters are +,*,-,/

Methods Of StringTokenizer Class

Method Action Performed

Returns the total number of tokens


countTokens()
present

Tests if tokens are present for the


hasMoreTokens()
StringTokenizer’s string

nextElement() Returns an Object rather than String

Returns the same value as


hasMoreElements()
hasMoreToken

Returns the next token from the given


nextToken()
StringTokenizer.
Example of StringTokenizer Class

Simple.java

. import java.util.StringTokenizer;
. public class Simple{
. public static void main(String args[]){
. StringTokenizer st = new StringTokenizer("my name is khan"," ");
. while (st.hasMoreTokens()) {
. System.out.println(st.nextToken());
. }
. }
. }
Output:

my
name
is
Khan

Example of StringTokenizer.nextToken(String delim) Method

Test.java

. import java.util.*;
.
. public class Test {
. public static void main(String[] args) {
. StringTokenizer st = new StringTokenizer("my,name,is,khan");
.
. // printing next token
. System.out.println("Next token is : " + st.nextToken(","));
. }
. }
Output:

Next token is : my

Example of StringTokenizer.hasMoreTokens() Method

StringTokenizer1.java

. import java.util.StringTokenizer;
. public class StringTokenizer1
. {
. /* Driver Code */
. public static void main(String args[])
. {
. /* StringTokenizer object */
. StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTok
enizer class"," ");
. /* Checks if the String has any more tokens */
. while (st.hasMoreTokens())
. {
. System.out.println(st.nextToken());
. }
. }
. }
Output:

Demonstrating
methods
from
StringTokenizer
class

Example of StringTokenizer.countTokens() Method

StringTokenizer4.java

. import java.util.StringTokenizer;
. public class StringTokenizer3
. {
. /* Driver Code */
. public static void main(String args[])
. {
. /* StringTokenizer object */
. StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");

. /* Prints the number of tokens present in the String */


. System.out.println("Total number of Tokens: "+st.countTokens());
. }
. }
Output:

Total number of Tokens: 6


Collections in Java

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

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

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

What is Collection in Java?

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

What is a framework in Java?

A framework provides a ready-made structure of classes and interfaces for building software
applications efficiently. It simplifies adding new features by offering reusable components
that perform similar tasks, eliminating the need to create a framework from scratch for each
new project. This approach enhances object-oriented design, making development quicker,
more consistent, and reliable.

o It provides readymade architecture.


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

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It enhances code efficiency and readability by offering various data
structures, including arrays, linked lists, trees, and hash tables, tailored to different
programming needs. It has:

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


2. Algorithm

Why Collection Framework?

Before the Collection Framework was introduced in JDK 1.2, Java's approach to collections
was using Arrays, Vectors, and Hash tables lacked a common interface. This meant each type
of collection had its own set of methods, syntax, and constructors, with no standardization or
correlation between them.

This made it difficult for users to remember the diverse functionalities of each collection type
and hindered code consistency and reusability. The disparate nature of these collections
highlighted the need for a unified Collection Framework to simplify and standardize
collection operations in Java.
Hierarchy of Collection Framework

Let's see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.

The Java Collections Framework is structured around key interfaces-Collection, List, Set,
Queue, and Map. Each tailored for specific data management tasks. Implementations like
ArrayList, HashSet, and HashMap offer practical solutions for working with these collections,
giving Java developers a versatile set of tools for efficient data handling.

o Class: A class is a blueprint from which individual objects are created. It encapsulates
data for objects through fields (attributes) and defines behavior via methods. Classes
support inheritance, allowing one class to inherit the properties and methods of
another, facilitating code reuse and polymorphism.
o Interface: An interface is a reference type in Java that can contain constants and
abstract methods (methods without a body). Interfaces specify what a class must do
but not how it does it, enforcing a set of methods that the class must implement.
Interfaces are used to achieve abstraction and multiple inheritance in Java.

Collections class
Collections class in Java is one of the utility classes in Java Collections Framework. The
java.util package contains the Collections class in Java. Java Collections class is used with
the static methods that operate on the collections or return the collection. All the methods
of this class throw the NullPointerException if the collection or object passed to the
methods is null.
Collection Class declaration
The syntax of the Collection class declaration is mentioned below:
public class Collections extends Object

Java Collection Class


Collection Framework contains both classes and interfaces. Although both seem the same
but there are certain differences between Collection classes and the Collection framework.
There are some classes in Java as mentioned below:

1. ArrayList

ArrayList is a class implemented using a list interface, in that provides the functionality of
a dynamic array where the size of the array is not fixed.
Syntax:
ArrayList<_type_> var_name = new ArrayList<_type_>();

2. Vector

Vector is a Part of the collection class that implements a dynamic array that can grow or
shrink its size as required.
Syntax:
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess,
Cloneable, Serializable

3. Stack

Stack is a part of Java collection class that models and implements a Stack data structure. It
is based on the basic principle of last-in-first-out(LIFO) .
Syntax:
public class Stack<E> extends Vector<E>
4. LinkedList

LinkedList class is an implementation of the LinkedList data structure. It can store the
elements that are not stored in contiguous locations and every element is a separate object
with a different data part and different address part.
Syntax:
LinkedList name = new LinkedList();

5. HashSet

HashSet is implemented using the Hashtable data structure. It offers constant time
performance for the performing operations like add, remove, contains, and size.
Syntax:
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
Serializable

6. LinkedHashSet

LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across


all elements.
Syntax:
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable,
Serializable

7. TreeSet

TreeSet class is implementations of the SortedSet interface in Java that uses a Tree for
storage. The ordering of the elements is maintained by a set using their natural ordering
whether an explicit comparator is provided or not.
Syntax:
TreeSet t = new TreeSet(Collection col);

8. PriorityQueue

The PriorityQueue is based on the priority heap. The elements of the priority queue are
ordered according to the natural ordering, or by a Comparator provided at queue
construction time, depending on which constructor is used.
Syntax:
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

9. ArrayDeque

The ArrayDeque class in Java is an implementation of the Deque interface that uses a
resizable array to store its elements. The ArrayDeque class provides constant-time
performance for inserting and removing elements from both ends.
Syntax:
public class ArrayDeque<E> extends
AbstractCollection<E> implements Deque<E>, Cloneable,Serializable

10. HashMap

HashMap Class is similar to HashTable but the data unsynchronized. It stores the data in
(Key, Value) pairs, and you can access them by an index of another type.
Syntax:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

11. EnumMap

EnumMap extends AbstractMap and implements the Map interface in Java.


Syntax:
public class EnumMap<K extends Enum<K>,V> extends
AbstractMap<K,V> implements Serializable, Cloneable

12. AbstractMap

The AbstractMap class is a part of the Java Collection Framework. It implements the Map
interface to provide a structure to it, by doing so it makes the further implementations
easier.
Syntax:
public abstract class AbstractMap<K,V> extends Object, implements Map<K,V>

13. TreeMap

A TreeMap is implemented using a Red-Black tree.TreeMap provides an ordered collection


of key-value pairs, where the keys are ordered based on their natural order or a custom
Comparator passed to the constructor.
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
Java Collections Class Fields
The collection class contains 3 fields as listed below which can be used to return immutable
entities.
• EMPTY_LIST to get an immutable empty List
• EMPTY_SET to get an immutable empty Set
• EMPTY_MAP to get an immutable empty Map

Collections class declaration

Let's see the declaration for java.util.Collections class.


. public class Collections extends Object
SN Modifier & Type Methods Descriptions

It is used to adds all of


the specified elements
1) static <T> boolean addAll()
to the specified
collection.

It returns a view of a
2) static <T> Queue<T> asLifoQueue() Deque as a Last-in-
first-out (LIFO) Queue.

It searches the list for


the specified object and
3) static <T> int binarySearch()
returns their position in
a sorted list.

It is used to returns a
static <E> dynamically typesafe
4) checkedCollection()
Collection<E> view of the specified
collection.

It is used to returns a
dynamically typesafe
5) static <E> List<E> checkedList()
view of the specified
list.

It is used to returns a
static <K,V> dynamically typesafe
6) checkedMap()
Map<K,V> view of the specified
map.

It is used to returns a
static <K,V> dynamically typesafe
7) checkedNavigableMap()
NavigableMap<K,V> view of the specified
navigable map.

It is used to returns a
static <E> dynamically typesafe
8) checkedNavigableSet()
NavigableSet<E> view of the specified
navigable set.
It is used to returns a
dynamically typesafe
9) static <E> Queue<E> checkedQueue()
view of the specified
queue.

It is used to returns a
dynamically typesafe
10) static <E> Set<E> checkedSet()
view of the specified
set.

Java Collection Interface

Collection is a group of objects, which are known as elements. It is the root interface in the
collection hierarchy. This interface is basically used to pass around the collections and
manipulate them where the maximum generality is desired.

There are many methods defined in the Collection interface. These are as follows:

Method Description

This method returns a Boolean value true if it


add()
inserts the specified element in this collection.

This method returns a Boolean value true if it


addAll() adds all the elements of specified collection in the
invoking collection.

It removes all the elements automatically from


clear()
this collection.

It returns a Boolean value true if this queue


contains()
contains the specified element.

It returns a Boolean value true if this collection


containsAll() contains all the elements in the specified
collection.

This method returns a boolean value true if the


equals()
specified object is equal with this collection.

hashCode() It returns a hash code value for this collection.

isEmpty() This method returns true if this collection


contains no elements or is empty.

It returns an iterator over the elements in proper


iterator()
sequence.

It removes the specified element from this queue,


remove()
if it is present in the collection.

It removes all the elements of this collection


removeAll()
which are also present in the specified collection.

It removes all the elements of this collection that


removeIf()
satisfy the given predicate filter.

This method retains only those elements in this


retainAll() collection that are present in the specified
collection.

It returns the total number of the elements in this


size()
collection.

It returns a spliterator over the elements in this


spliterator()
collection.

It returns an array containing all the elements of


toArray()
this collection which are in proper sequence.
Iterators in Java
A Java Cursor is an Iterator, that is used to iterate or traverse or retrieve a Collection or
Stream object’s elements one by one. In this article, we will learn about Java Iterators and it’s
working.

Types of Cursors in Java


There are three cursors in Java as mentioned below:
1. Iterator
2. Enumeration
3. ListIterator
Note: SplitIterator can also be considered as a cursor as it is a type of Iterator
only.
1. Iterator
Iterators in Java are used in the Collection framework to retrieve elements one by one. It is
a universal iterator as we can apply it to any Collection object. By using Iterator, we can
perform both read and remove operations. It is an improved version of Enumeration with the
additional functionality of removing an element.
Iterator must be used whenever we want to enumerate elements in all Collection framework
implemented interfaces like Set, List, Queue, Deque, and all implemented classes of Map
interface. The iterator is the only cursor available for the entire collection framework. An
iterator object can be created by calling the iterator() method present in the Collection
interface.

Syntax

Iterator itr = c.iterator();


Note: Here “c” is any Collection object. itr is of type Iterator interface and
refers to “c”.
Methods of Iterator Interface in Java

The iterator interface defines three methods as listed below:


1. hasNext(): Returns true if the iteration has more elements.
public boolean hasNext();
2. next(): Returns the next element in the iteration. It throws NoSuchElementException if
no more element is present.
public Object next();
3. remove(): Removes the next element in the iteration. This method can be called only once
per call to next().
public void remove();
Note: remove() method can throw two exceptions namely as follows:
• UnsupportedOperationException : If the remove operation is not
supported by this iterator
• IllegalStateException : If the next method has not yet been called, or the
remove method has already been called after the last call to the next
method.

Example of Java Iterator

Now it's time to execute a Java program to illustrate the advantage of the Java Iterator
interface. The below code produces an ArrayList of city names. Then we initialize an iterator
applying the iterator () method of the ArrayList. After that, the list is traversed to represent
each element.

JavaIteratorExample.java

. import java.io.*;
. import java.util.*;
. public class JavaIteratorExample {
. public static void main(String[] args)
. {
. ArrayList<String> cityNames = new ArrayList<String>();
. cityNames.add("Delhi");
. cityNames.add("Mumbai");
. cityNames.add("Kolkata");
. cityNames.add("Chandigarh");
. cityNames.add("Noida");
. // Iterator to iterate the cityNames
. Iterator iterator = cityNames.iterator();
. System.out.println("CityNames elements : ");
. while (iterator.hasNext())
. System.out.print(iterator.next() + " ");
. }
. }
Output:

CityNames elements:
Delhi Mumbai Kolkata Chandigarh Noida

Map Interface in Java

The map interface in Java is a structure that holds a set of key-value pairs where each key is
unique and points to one value only. It is a component of the java.util package and is being
widely used in Java programming to structure and get data in an ordered manner. A Map is
useful if you have to search, update or delete elements on the basis of a key.
• No Duplicates in Keys: Ensures that keys are unique. However, values can be
duplicated.
• Null Handling: Allows one null key in implementations like HashMap
and LinkedHashMap and allows multiple null values in most implementations.
• Thread-Safe Alternatives: Use ConcurrentHashMap for thread-safe operations
also, wrap an existing Map using Collections.synchronizedMap() for synchronized
access.
// Java Program Implementing HashMap
import java.util.HashMap;
import java.util.Map;

public class MapCreationExample {

public static void main(String[] args)


{

// Create a Map using HashMap


Map<String, Integer> map = new HashMap<>();

// Displaying the Map


System.out.println("Map elements: " + map);
}
}
Output:
Map elements: {}
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.

A Map can't be traversed, so you need to convert it into Set


using keySet() or entrySet() method.

Class Description

HashMap is the implementation of Map, but it


HashMap
doesn't maintain any order.

LinkedHashMap is the implementation of Map. It


LinkedHashMap inherits HashMap class. It maintains insertion
order.

TreeMap is the implementation of Map and


TreeMap
SortedMap. It maintains ascending order.

Methods in Java Map Interface


Method Action Performed

This method is used in Java Map Interface to clear and remove all of the
clear()
elements or mappings from a specified Map collection.

This method is used in Map Interface in Java to check whether a particular


containsKey(Object) key is being mapped into the Map or not. It takes the key element as a
parameter and returns True if that element is mapped in the map.
Method Action Performed

This method is used in Map Interface to check whether a particular value


is being mapped by a single or more than one key in the Map. It takes the
containsValue(Object)
value as a parameter and returns True if that value is mapped by any of the
keys in the map.

This method is used in Map Interface in Java to create a set out of the
entrySet() same elements contained in the map. It basically returns a set view of the
map or we can create a new set and store the map elements into them.

This method is used in Java Map Interface to check for equality between
equals(Object) two maps. It verifies whether the elements of one map passed as a
parameter is equal to the elements of this map or not.

This method is used to retrieve or fetch the value mapped by a particular


get(Object) key mentioned in the parameter. It returns NULL when the map contains
no such mapping for the key.

This method is used in Map Interface to generate a hashCode for the given
hashCode()
map containing keys and values.

This method is used to check if a map is having any entry for key and
isEmpty()
value pairs. If no mapping exists, then this returns true.

This method is used in Map Interface to return a Set view of the keys
keySet() contained in this map. The set is backed by the map, so changes to the
map are reflected in the set, and vice-versa.

This method is used in Java Map Interface to associate the specified value
put(Object, Object)
with the specified key in this map.

This method is used in Map Interface in Java to copy all of the mappings
putAll(Map)
from the specified map to this map.

This method is used in Map Interface to remove the mapping for a key
remove(Object)
from this map if it is present in the map.

This method is used to return the number of key/value pairs available in


size()
the map.

Hierarchy of Map
Interface in Java
Method Action Performed

Java Comparator interface

Java Comparator interface is used to order the objects of a user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object


obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.

Methods of Java Comparator Interface

Method Description
It compares the first object with the second
public int compare(Object obj1, Object obj2)
object.

It is used to compare the current object with the


public boolean equals(Object obj)
specified object.

Method of Collections class for sorting List elements

public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.

Java Comparator Example (Non-generic Old Style)

Let's see the example of sorting the elements of List on the basis of age and name. In this
example, we have created 4 java classes:

1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java

Student.java
This class contains three fields rollno, name and age and a parameterized constructor.

. class Student{
. int rollno;
. String name;
. int age;
. Student(int rollno,String name,int age){
. this.rollno=rollno;
. this.name=name;
. this.age=age;
. }
. }
AgeComparator.java
This class defines comparison logic based on the age. If the age of the first object is greater
than the second, we are returning a positive value. It can be anyone such as 1, 2, 10. If the age
of the first object is less than the second object, we are returning a negative value, it can be
any negative value, and if the age of both objects is equal, we are returning 0.

. import java.util.*;
. class AgeComparator implements Comparator{
. public int compare(Object o1,Object o2){
. Student s1=(Student)o1;
. Student s2=(Student)o2;
.
. if(s1.age==s2.age)
. return 0;
. else if(s1.age>s2.age)
. return 1;
. else
. return -1;
. }
. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.

. import java.util.*;
. class NameComparator implements Comparator
. {
. public int compare(Object o1,Object o2)
. {
. Student s1=(Student)o1;
. Student s2=(Student)o2;
.
. return s1.name.compareTo(s2.name);
. }
. }
complete example using a comparator to sort a list of cars by year:

import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;

// Define a Car classclass Car {

public String brand;

public String model;

public int year;

public Car(String b, String m, int y) {

brand = b;

model = m;

year = y;
}}

// Create a comparatorclass SortByYear implements Comparator {

public int compare(Object obj1, Object obj2) {

// Make sure that the objects are Car objects

Car a = (Car) obj1;

Car b = (Car) obj2;

// Compare the year of both objects

if (a.year < b.year) return -1; // The first car has a smaller year

if (a.year > b.year) return 1; // The first car has a larger year

return 0; // Both cars have the same year

}}

public class Main {

public static void main(String[] args) {

// Create a list of cars

ArrayList<Car> myCars = new ArrayList<Car>();

myCars.add(new Car("BMW", "X5", 1999));

myCars.add(new Car("Honda", "Accord", 2006));

myCars.add(new Car("Ford", "Mustang", 1970));

// Use a comparator to sort the cars

Comparator myComparator = new SortByYear();

Collections.sort(myCars, myComparator);

// Display the cars

for (Car c : myCars) {

System.out.println(c.brand + " " + c.model + " " + c.year);

}}

Output:
Ford Mustang 1970
BMW X5 1999
Honda Accord 2006

Random Access Interface in Java

In the world of programming, efficient data manipulation is often a critical requirement. Java,
being one of the most popular programming languages, offers a variety of tools and interfaces
to help achieve this efficiently. One such interface is the RandomAccess interface, which
plays a vital role in enabling random access to data structures. In this section, we will dive
into the world of random access in Java, exploring what the RandomAccess interface is, how
it works, and provide practical examples to illustrate its usage.

Java RandomAccess Interface

The RandomAccess interface is a marker interface in Java, which means it doesn't declare
any methods of its own. Instead, it serves as a marker to indicate that a class implementing it
supports efficient random-access operations. By implementing this interface, a class
essentially tells Java that it can provide faster access to elements, typically using indices or
keys.

Why Use the RandomAccess Interface?

The primary reason for using the RandomAccess interface is to indicate that a class has
optimized its data structure for random access. This information can be beneficial for
algorithms and data structures that rely on efficient random access. When a class implements
RandomAccess, it signals that operations like accessing elements by index or key will be fast
and efficient.

Let's take a look at a practical example to understand this better. Suppose we have a large list
of data, and we want to access elements at random indices frequently. If the data structure
used to store this list implements the RandomAccess interface, we can expect faster
performance compared to a non-RandomAccess data structure.

Example: Using the RandomAccess Interface

In this example, we will create a custom class that implements the RandomAccess interface
to store a list of integers efficiently. We will then compare the performance of random access
with and without the interface.

RandomAccessDemo.java

. import java.util.ArrayList;
. import java.util.List;
. import java.util.RandomAccess;
. // Define a custom class that implements the RandomAccess interface
. class CustomList implements RandomAccess {
. private List<Integer> data;
. // Constructor to initialize the data list
. public CustomList() {
. data = new ArrayList<>();
. }
. // Method to add an element to the custom list
. public void add(int element) {
. data.add(element);
. }
. // Method to get an element at a specified index
. public int get(int index) {
. return data.get(index);
. }
. }

Java - java.util Package

The java.util package is a standard package of Java SDK. It contains the collections framework, legacy collection
classes, event model, date and time facilities, internationalization, and miscellaneous utility classes. This package is
very useful as it provides commonly used Collections like ArrayList, HashMap, Set etc. Java.util provides
StrinTokenizer classes for String operations and similarly other utility classes for event model handlings, date and
time operations and lot more. This reference will take you through simple and practical methods available
in java.util package.

Importing java.util Package


Being an inbuilt package of Java, we're not required to download any external library for java.util package and its all
classes can be imported using following syntax:

import java.util.*;

Here we've used * operator to import all classes from java.util package and now any class can be used in the program.
In case of specific class, for example ArrayList, we can import a class using following syntax:

import java.util.ArrayList;

Why java.util Package is used in Java Programs

Java.util package classes contains utility classes like collections frameworks, String operations utilities, Date and
Time operations utilities. Following list shows some of the categories of classes of java.util package.


Collections − ArrayList, HashMap, Dictionary are few of the classes of large set of Collection classes availble in
java.util package. These classes provides commonly used operations on large data sets.


Date Time Operations − GregorianCalendar, Timezone are some of the classes of utility classes availble in java.util
package. These classes provides commonly used operations on date and time.


String Manipulations − StringTokenizer is an important utility class availble in java.util package. This class provides
a lot of operations to manipulate strings.


Enumerations − Enumeration class of java.util package provides operations on set of values like iterations,
comparison etc.


Exceptions − java.util package contains various commonly occuring exceptions like
ConcurrentModificationException, InputMismatchException etc.

Important classes in java.util Package


Following is the list of important classes in java.util.package:

• ArrayDeque − This class provides resizable-array and implements the Deque interface. This class and its
iterator implement all of the optional methods of the Collection and Iterator interfaces.
• ArrayList − This class provides resizable-array and implements the List interface. The ArrayList class
extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
• Arrays − This class contains a static factory that allows arrays to be viewed as lists. The ArrayList class
contains various methods for manipulating arrays (such as sorting and searching).
• BitSet − This class creates a special type of array that holds bit values. The BitSet array can increase in size
as needed. This makes it similar to a vector of bits. This is a legacy class but it has been completely re-engineered in
Java 2, version 1.4. The Java BitSet class implements a vector of bits that grows as needed.
• Calendar − This class is an abstract class that provides methods for converting between a specific instant in
time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for
manipulating the calendar fields, such as getting the date of the next week.
• Collections − This class consists exclusively of static methods that operate on or return collections.
• Currency − This class represents a currency. The Currency class is designed so that there's never more than
one Currency instance for any given currency, this is the reason behind no public constructor.
• Date − This class represents a specific instant in time, with millisecond precision.
• Dictionary − This class is the abstract parent of any class, such as Hashtable, which maps keys to values.
• EnumMap − This class is a specialized Map implementation for use with enum keys. All of the keys in an
enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.
• EnumSet − This class is a specialized Set implementation for use with enum keys. All of the keys in an
enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.
• Formatter − This class provides support for layout justification and alignment, common formats for
numeric, string, and date/time data, and locale-specific output.
• GregorianCalendar − This class is a concrete subclass of Calendar and provides the standard calendar
system used by most of the world. It is a hybrid calendar that supports both the Julian and Gregorian calendar systems
with the support of a single discontinuity, which corresponds by default to the Gregorian date when the Gregorian
calendar was instituted.
• HashMap − This class is the Hash table based implementation of the Map interface.
• HashSet − This class implements the Set interface, backed by a hash table.
• HashTable − This class implements a hashtable, which maps keys to values.

Examples of java.util Package


Practice the following examples to learn the concept and usage of java.util package clasess.

Example of java.util.ArrayList

The following program illustrates several of the methods supported by ArrayList


UNIT-4

Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based
applications in Java.

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

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

Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components
like TextField, ChechBox, button, etc.

For example, an AWT GUI with components like TextField, label and button will have different look and feel for the
different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms have different view for their
native components and AWT directly calls the native subroutine that creates those components.

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

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.
Components

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

Container

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

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

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

There are four types of containers in Java AWT:

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

The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating
a window. We need to create an instance of Window class to create this container.

Panel

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

Frame

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

Useful Methods of Component Class

Method Description

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

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

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

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

Java AWT Example


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

1. By extending Frame class (inheritance)


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

AWT Example by Inheritance


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

AWTExample1.java

. // importing Java AWT class


. import java.awt.*;
.
. // extending Frame class to our class AWTExample1
. public class AWTExample1 extends Frame {
.
. // initializing using constructor
. AWTExample1() {
.
. // creating a button
. Button b = new Button("Click Me!!");
.
. // setting button position on screen
. b.setBounds(30,100,80,30);
.
. // adding button into frame
. add(b);
.
. // frame size 300 width and 300 height
. setSize(300,300);
.
. // setting the title of Frame
. setTitle("This is our basic AWT example");
.
. // no layout manager
. setLayout(null);
.
. // now frame will be visible, by default it is not visible
. setVisible(true);
. }
.
. // main method
. public static void main(String args[]) {
.
. // creating instance of Frame class
. AWTExample1 f = new AWTExample1();
.
. }
.
. }
Output:
AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are creating a TextField, Label
and Button component on the Frame.

AWTExample2.java

. // importing Java AWT class


. import java.awt.*;
.
. // class AWTExample2 directly creates instance of Frame class
. class AWTExample2 {
.
. // initializing using constructor
. AWTExample2() {
.
. // creating a Frame
. Frame f = new Frame();
.
. // creating a Label
. Label l = new Label("Employee id:");
.
. // creating a Button
. Button b = new Button("Submit");
.
. // creating a TextField
. TextField t = new TextField();
.
. // setting position of above components in the frame
. l.setBounds(20, 80, 80, 30);
. t.setBounds(20, 100, 80, 30);
. b.setBounds(100, 100, 80, 30);
.
. // adding components into frame
. f.add(b);
. f.add(l);
. f.add(t);
.
. // frame size 300 width and 300 height
. f.setSize(400,300);
.
. // setting the title of frame
. f.setTitle("Employee info");
.
. // no layout
. f.setLayout(null);
.
. // setting visibility of frame
. f.setVisible(true);
. }
.
. // main method
. public static void main(String args[]) {
.
. // creating instance of Frame class
. AWTExample2 awt_obj = new AWTExample2();
.
. }
.
. }
Output:
Event and Listener (Java Event Handling)

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

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods

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

o Button

o public void addActionListener(ActionListener a){}


o MenuItem
o public void addActionListener(ActionListener a){}
o TextField

o public void addActionListener(ActionListener a){}


o public void addTextListener(TextListener a){}
o TextArea

o public void addTextListener(TextListener a){}


o Checkbox

o public void addItemListener(ItemListener a){}


o Choice

o public void addItemListener(ItemListener a){}


o List

o public void addActionListener(ActionListener a){}


o public void addItemListener(ItemListener a){}

Java Event Handling Code

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

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

Java event handling by implementing ActionListener

. import java.awt.*;
. import java.awt.event.*;
. class AEvent extends Frame implements ActionListener{
. TextField tf;
. AEvent(){
.
. //create components
. tf=new TextField();
. tf.setBounds(60,50,170,20);
. Button b=new Button("click me");
. b.setBounds(100,120,80,30);
.
. //register listener
. b.addActionListener(this);//passing current instance
.
. //add components and set size, layout and visibility
. add(b);add(tf);
. setSize(300,300);
. setLayout(null);
. setVisible(true);
. }
. public void actionPerformed(ActionEvent e){
. tf.setText("Welcome");
. }
. public static void main(String args[]){
. new AEvent();
. }
. }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that
sets the position of the component it may be button, textfield etc.

2) Java event handling by outer class

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

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

3) Java event handling by anonymous class

. import java.awt.*;
. import java.awt.event.*;
. class AEvent3 extends Frame{
. TextField tf;
. AEvent3(){
. tf=new TextField();
. tf.setBounds(60,50,170,20);
. Button b=new Button("click me");
. b.setBounds(50,120,80,30);
.
. b.addActionListener(new ActionListener(){
. public void actionPerformed(){
. tf.setText("hello");
. }
. });
. add(b);add(tf);
. setSize(300,300);
. setLayout(null);
. setVisible(true);
. }
. public static void main(String args[]){
. new AEvent3();
. }
. }

Delegation Event Model in Java

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

The GUI programming is inherently event-driven; whenever a user initiates an activity such as a mouse activity,
clicks, scrolling, etc., each is known as an event that is mapped to a code to respond to functionality to the user.
This is known as event handling.

In this section, we will discuss event processing and how to implement the delegation event model in Java. We
will also discuss the different components of an Event Model.

Event Processing in Java

Java support event processing since Java 1.0. It provides support for AWT ( Abstract Window Toolkit), which is
an API used to develop the Desktop application. In Java 1.0, the AWT was based on inheritance. To catch and
process GUI events for a program, it should hold subclass GUI components and override action() or
handleEvent() methods. The below image demonstrates the event processing.

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

The key advantage of the Delegation Event Model is that the application logic is completely separated from the
interface logic.
In this model, the listener must be connected with a source to receive the event notifications. Thus, the events
will only be received by the listeners who wish to receive them. So, this approach is more convenient than the
inheritance-based event model (in Java 1.0).

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

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

o Events
o Events Sources
o Events Listeners

Events

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

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

Event Sources

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

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

. public void addTypeListener (TypeListener e1)


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

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

. public void addTypeListener(TypeListener e2) throws java.util.TooManyListenersException


From the above syntax, the Type is the name of the event, and e2 is the event listener's reference. When the
specified event occurs, it will be notified to the registered listener. This process is known as unicasting events.

A source should contain a method that unregisters a specific type of event from the listener if not needed. Below
is an example of the method that will remove the event from the listener.
. public void removeTypeListener(TypeListener e2?)
From the above syntax, the Type is an event name, and e2 is the reference of the listener. For example, to
remove the keyboard listener, the removeKeyListener() method will be called.

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

Event Listeners

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

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

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

Types of Events

The events are categories into the following two categories:

The Foreground Events:

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

The Background Events :

The Background events are those events that result from the interaction of the end-user. For example, an
Operating system interrupts system failure (Hardware or Software).

To handle these events, we need an event handling mechanism that provides control over the events and
responses.

The Delegation Model

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

Design Goals

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

o It is easy to learn and implement


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

Java Program to Implement the Event Deligation Model

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

TestApp.java:

. import java.awt.*;
. import java.awt.event.*;
. public class TestApp {
. public void search() {
. // For searching
. System.out.println("Searching...");
. }
. public void sort() {
. // for sorting
. System.out.println("Sorting....");
. }
. static public void main(String args[]) {
. TestApp app = new TestApp();
. GUI gui = new GUI(app);
. }
. }
. class Command implements ActionListener {
. static final int SEARCH = 0;
. static final int SORT = 1;
. int id;
. TestApp app;
. public Command(int id, TestApp app) {
. this.id = id;
. this.app = app;
. }
.
. public void actionPerformed(ActionEvent e) {
. switch(id) {
. case SEARCH:
. app.search();
. break;
. case SORT:
. app.sort();
. break;
. }
. }
. }
.
. class GUI {
.
. public GUI(TestApp app)
. {
. Frame f = new Frame();
. f.setLayout(new FlowLayout());
. Command searchCmd = new Command(Command.SEARCH, app);
. Command sortCmd = new Command(Command.SORT, app);
.
. Button b;
. f.add(b = new Button("Search"));
. b.addActionListener(searchCmd);
. f.add(b = new Button("Sort"));
. b.addActionListener(sortCmd);
.
. List l;
. f.add(l = new List());
. l.add("Alphabetical");
. l.add("Chronological");
. l.addActionListener(sortCmd);
. f.pack();
. f.show();
. }
. }
Output:

Java AWT Label


The object of the Label 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 a programmer but a user cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed. To create a label, we need to create the object
of Label class.

AWT Label Class Declaration

. public class Label extends Component implements Accessible

AWT Label Fields


The java.awt.Component class has following fields:
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.

Label class Constructors

Sr. no. Constructor Description

1. Label() It constructs an empty label.

It constructs a label with the given string


2. Label(String text)
(left justified by default).

It constructs a label with the specified


3. Label(String text, int alignement)
string and the specified alignment.

Label Class Methods

Sr. no. Method name Description

It sets the texts for label with the


1. void setText(String text)
specified text.

It sets the alignment for label with the


2. void setAlignment(int alignment)
specified alignment.

3. String getText() It gets the text of the label

4. int getAlignment() It gets the current alignment of the label.

Method inherited
The above methods are inherited by the following classes:

o java.awt.Component
o java.lang.Object

Java AWT Label Example


In the following example, we are creating two labels l1 and l2 using the Label(String text) constructor and adding them into
the frame.

LabelExample.java

. import java.awt.*;
.
. public class LabelExample {
. public static void main(String args[]){
.
. // creating the object of Frame class and Label class
. Frame f = new Frame ("Label example");
. Label l1, l2;
.
. // initializing the labels
. l1 = new Label ("First Label.");
. l2 = new Label ("Second Label.");
.
. // set the location of label
. l1.setBounds(50, 100, 100, 30);
. l2.setBounds(50, 150, 100, 30);
.
. // adding labels to the frame
. f.add(l1);
. f.add(l2);
.
. // setting size, layout and visibility of frame
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. }
Output:

Java AWT Button


A button is basically a control component with a label that generates an event when pushed. The Button class is used to
create a labeled button that has platform independent implementation. The application result in some action when the button
is pushed.

When we press a button and release it, AWT sends an instance of ActionEvent to that button by calling processEvent on
the button. The processEvent method of the button receives the all the events, then it passes an action event by calling its
own method processActionEvent. This method passes the action event on to action listeners that are interested in the action
events generated by the button.
To perform an action on a button being pressed and released, the ActionListener interface needs to be implemented. The
registered new listener can receive events from the button by calling addActionListener method of the button. The Java
application can use the button's action command as a messaging protocol.

AWT Button Class Declaration

. public class Button extends Component implements Accessible

Button Class Constructors

Sr. no. Constructor Description

It constructs a new button with an empty


1. Button( )
string i.e. it has no label.

It constructs a new button with given


2. Button (String text)
string as its label.

Button Class Methods

Sr. no. Method Description

1. void setText (String text) It sets the string message on the button

It fetches the String message on the


2. String getText()
button.

It sets the label of button with the


3. void setLabel (String label)
specified string.

4. String getLabel() It fetches the label of the button.

Java AWT Button Example

Example 1:

ButtonExample.java

. import java.awt.*;
. public class ButtonExample {
. public static void main (String[] args) {
.
. // create instance of frame with the label
. Frame f = new Frame("Button Example");
.
. // create instance of button with label
. Button b = new Button("Click Here");
.
. // set the position for the button in frame
. b.setBounds(50,100,80,30);
.
. // add button to the frame
. f.add(b);
. // set size, layout and visibility of frame
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. }
To compile the program using command prompt type the following commands

. C:\Users\Anurati\Desktop\abcDemo>javac ButtonExample.java
If there's no error, we can execute the code using:

. C:\Users\Anurati\Desktop\abcDemo>java ButtonExample
Output:

Java AWT Checkbox


The Checkbox 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".

AWT Checkbox Class Declaration

. public class Checkbox extends Component implements ItemSelectable, Accessible


Checkbox Class Constructors

Sr. no. Constructor Description

It constructs a checkbox with no string


1. Checkbox()
as the label.

It constructs a checkbox with the given


2. Checkbox(String label)
label.

It constructs a checkbox with the given


3. Checkbox(String label, boolean state)
label and sets the given state.

It constructs a checkbox with the given


Checkbox(String label, boolean state,
4. label, set the given state in the specified
CheckboxGroup group)
checkbox group.

It constructs a checkbox with the given


Checkbox(String label, CheckboxGroup
5. label, in the given checkbox group and
group, boolean state)
set to the specified state.

Method inherited by Checkbox


The methods of Checkbox class are inherited by following classes:

o java.awt.Component
o java.lang.Object

Checkbox Class Methods

Sr. no. Method name Description

It adds the given item listener to get the


1. void addItemListener(ItemListener IL)
item events from the checkbox.

AccessibleContext It fetches the accessible context of


2.
getAccessibleContext() checkbox.

3. void addNotify() It creates the peer of checkbox.

4. CheckboxGroup getCheckboxGroup() It determines the group of checkbox.

Java AWT Checkbox Example


In the following example we are creating two checkboxes using the Checkbox(String label) constructo and adding them into
the Frame using add() method.

CheckboxExample1.java
. // importing AWT class
. import java.awt.*;
. public class CheckboxExample1
. {
. // constructor to initialize
. CheckboxExample1() {
. // creating the frame with the title
. Frame f = new Frame("Checkbox Example");
. // creating the checkboxes
. Checkbox checkbox1 = new Checkbox("C++");
. checkbox1.setBounds(100, 100, 50, 50);
. Checkbox checkbox2 = new Checkbox("Java", true);
. // setting location of checkbox in frame
. checkbox2.setBounds(100, 150, 50, 50);
. // adding checkboxes to frame
. f.add(checkbox1);
. f.add(checkbox2);
.
. // setting size, layout and visibility of frame
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. // main method
. public static void main (String args[])
. {
. new CheckboxExample1();
. }
. }
Output:

Java AWT CheckboxGroup


The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one check box button is
allowed to be in "on" state and remaining check box button in "off" state. It inherits the object class.

Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for creating
radio buttons in AWT.

AWT CheckboxGroup Class Declaration


. public class CheckboxGroup extends Object implements Serializable

Java AWT CheckboxGroup Example

. import java.awt.*;
. public class CheckboxGroupExample
. {
. CheckboxGroupExample(){
. Frame f= new Frame("CheckboxGroup Example");
. CheckboxGroup cbg = new CheckboxGroup();
. Checkbox checkBox1 = new Checkbox("C++", cbg, false);
. checkBox1.setBounds(100,100, 50,50);
. Checkbox checkBox2 = new Checkbox("Java", cbg, true);
. checkBox2.setBounds(100,150, 50,50);
. f.add(checkBox1);
. f.add(checkBox2);
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. public static void main(String args[])
. {
. new CheckboxGroupExample();
. }
. }
Output:

Java AWT Choice


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

AWT Choice Class Declaration

. public class Choice extends Component implements ItemSelectable, Accessible

Choice Class constructor


Sr. no. Constructor Description

1. Choice() It constructs a new choice menu.

Methods inherited by class


The methods of Choice class are inherited by following classes:

o java.awt.Component
o java.lang.Object

Choice Class Methods

Sr. no. Method name Description

1. void add(String item) It adds an item to the choice menu.

It adds the item listener that receives


2. void addItemListener(ItemListener l)
item events from the choice menu.

3. void addNotify() It creates the peer of choice.

AccessibleContext It gets the accessbile context related to


4.
getAccessibleContext() the choice.

Java AWT Choice Example


In the following example, we are creating a choice menu using Choice() constructor. Then we add 5 items to the menu using
add() method and Then add the choice menu into the Frame.

ChoiceExample1.java

. // importing awt class


. import java.awt.*;
. public class ChoiceExample1 {
.
. // class constructor
. ChoiceExample1() {
.
. // creating a frame
. Frame f = new Frame();
.
. // creating a choice component
. Choice c = new Choice();
.
. // setting the bounds of choice menu
. c.setBounds(100, 100, 75, 75);
.
. // adding items to the choice menu
. c.add("Item 1");
. c.add("Item 2");
. c.add("Item 3");
. c.add("Item 4");
. c.add("Item 5");
.
. // adding choice menu to frame
. f.add(c);
.
. // setting size, layout and visibility of frame
. f.setSize(400, 400);
. f.setLayout(null);
. f.setVisible(true);
. }
.
. // main method
. public static void main(String args[])
. {
. new ChoiceExample1();
. }
. }
Output:

Java AWT List


The object of List class represents a list of text items. With the help of the List class, user can choose either one item or
multiple items. It inherits the Component class.

AWT List class Declaration

. public class List extends Component implements ItemSelectable, Accessible

AWT List Class Constructors

Sr. no. Constructor Description

1. List() It constructs a new scrolling list.


It constructs a new scrolling list
2. List(int row_num) initialized with the given number of
rows visible.

It constructs a new scrolling list


List(int row_num, Boolean
3. initialized which displays the given
multipleMode)
number of rows.

Methods Inherited by the List Class


The List class methods are inherited by following classes:

o java.awt.Component
o java.lang.Object

List Class Methods

Sr. no. Method name Description

It adds the specified item into the end of


1. void add(String item)
scrolling list.

It adds the specified item into list at the


2. void add(String item, int index)
given index position.

It adds the specified action listener to


3. void addActionListener(ActionListener l)
receive action events from list.

It adds specified item listener to receive


4. void addItemListener(ItemListener l)
item events from list.

Java AWT List Example


In the following example, we are creating a List component with 5 rows and adding it into the Frame.

ListExample1.java

. // importing awt class


. import java.awt.*;
.
. public class ListExample1
. {
. // class constructor
. ListExample1() {
. // creating the frame
. Frame f = new Frame();
. // creating the list of 5 rows
. List l1 = new List(5);
.
. // setting the position of list component
. l1.setBounds(100, 100, 75, 75);
.
. // adding list items into the list
. l1.add("Item 1");
. l1.add("Item 2");
. l1.add("Item 3");
. l1.add("Item 4");
. l1.add("Item 5");
.
. // adding the list to frame
. f.add(l1);
.
. // setting size, layout and visibility of frame
. f.setSize(400, 400);
. f.setLayout(null);
. f.setVisible(true);
. }
.
. // main method
. public static void main(String args[])
. {
. new ListExample1();
. }
. }
Output:

Java AWT Scrollbar


The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to see
invisible number of rows and columns.

It can be added to top-level container like Frame or a component like Panel. The Scrollbar class extends
the Component class.

AWT Scrollbar Class Declaration

. public class Scrollbar extends Component implements Adjustable, Accessible


Scrollbar Class Fields
The fields of java.awt.Image class are as follows:

o static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.


o static int VERTICAL - It is a constant to indicate a vertical scroll bar.

Scrollbar Class Constructors

Sr. no. Constructor Description

1 Scrollbar() Constructs a new vertical scroll bar.

Constructs a new scroll bar with the


2 Scrollbar(int orientation)
specified orientation.

Constructs a new scroll bar with the


Scrollbar(int orientation, int value, int specified orientation, initial value,
3
visible, int minimum, int maximum) visible amount, and minimum and
maximum values.

o orientation: specifiey whether the scrollbar will be horizontal or vertical.


o Value: specify the starting position of the knob of Scrollbar on its track.
o Minimum: specify the minimum width of track on which scrollbar is moving.
o Maximum: specify the maximum width of track on which scrollbar is moving.

Method Inherited by Scrollbar


The methods of Scrollbar class are inherited from the following classes:

o java.awt.Component
o java.lang.Object

Scrollbar Class Methods

Sr. no. Method name Description

It adds the given adjustment listener to


void addAdjustmentListener
1. receive instances of AdjustmentEvent
(AdjustmentListener l)
from the scroll bar.

2. void addNotify() It creates the peer of scroll bar.

It gets the block increment of the scroll


3. int getBlockIncrement()
bar.

It gets the maximum value of the scroll


4. int getMaximum()
bar.
It gets the minimum value of the scroll
5. int getMinimum()
bar.

Java AWT Scrollbar Example


In the following example, we are creating a scrollbar using the Scrollbar() and adding it into the Frame.

ScrollbarExample1.java

. // importing awt package


. import java.awt.*;
.
. public class ScrollbarExample1 {
.
. // class constructor
. ScrollbarExample1() {
.
. // creating a frame
. Frame f = new Frame("Scrollbar Example");
. // creating a scroll bar
. Scrollbar s = new Scrollbar();
.
. // setting the position of scroll bar
. s.setBounds (100, 100, 50, 100);
.
. // adding scroll bar to the frame
. f.add(s);
.
. // setting size, layout and visibility of frame
. f.setSize(400, 400);
. f.setLayout(null);
. f.setVisible(true);
. }
.
. // main method
. public static void main(String args[]) {
. new ScrollbarExample1();
. }
. }
Output:
Java AWT TextField
The object of a TextField class is a text component that allows a user to enter a single line text and edit it. It
inherits TextComponent class, which further inherits Component class.

When we enter a key in the text field (like key pressed, key released or key typed), the event is sent to TextField. Then
the KeyEvent is passed to the registered KeyListener. It can also be done using ActionEvent; if the ActionEvent is enabled
on the text field, then the ActionEvent may be fired by pressing return key. The event is handled by
the ActionListener interface.

AWT TextField Class Declaration

. public class TextField extends TextComponent

TextField Class constructors

Sr. no. Constructor Description

1. TextField() It constructs a new text field component.

It constructs a new text field initialized


2. TextField(String text) with the given string text to be
displayed.

It constructs a new textfield (empty)


3. TextField(int columns)
with given number of columns.

It constructs a new text field with the


4. TextField(String text, int columns) given text and given number of columns
(width).
TextField Class Methods

Sr. no. Method name Description

1. void addNotify() It creates the peer of text field.

It tells whether text field has character


2. boolean echoCharIsSet()
set for echoing or not.

It adds the specified action listener to


3. void addActionListener(ActionListener l)
receive action events from the text field.

It returns array of all action listeners


4. ActionListener[] getActionListeners()
registered on text field.

AccessibleContext It fetches the accessible context related


5.
getAccessibleContext() to the text field.

Method Inherited
The AWT TextField class inherits the methods from below classes:

1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object

Java AWT TextField Example


TextFieldExample1.java

. // importing AWT class


. import java.awt.*;
. public class TextFieldExample1 {
. // main method
. public static void main(String args[]) {
. // creating a frame
. Frame f = new Frame("TextField Example");
.
. // creating objects of textfield
. TextField t1, t2;
. // instantiating the textfield objects
. // setting the location of those objects in the frame
. t1 = new TextField("Welcome to Javatpoint.");
. t1.setBounds(50, 100, 200, 30);
. t2 = new TextField("AWT Tutorial");
. t2.setBounds(50, 150, 200, 30);
. // adding the components to frame
. f.add(t1);
. f.add(t2);
. // setting size, layout and visibility of frame
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. }
Output:

Java AWT TextArea


The object of a TextArea class is a multiline region that displays text. It allows the editing of multiple line text. It inherits
TextComponent class.

The text area allows us to type as much text as we want. When the text in the text area becomes larger than the viewable area,
the scroll bar appears automatically which helps us to scroll the text up and down, or right and left.

AWT TextArea Class Declaration

. public class TextArea extends TextComponent

Fields of TextArea Class


The fields of java.awt.TextArea class are as follows:

o static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical scrollbars.
o static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the horizontal scrollbar.
o static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the vertical scrollbar.
o static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text area.

Class constructors:
Sr. no. Constructor Description

It constructs a new and empty text area


1. TextArea()
with no text in it.

It constructs a new text area with


2. TextArea (int row, int column) specified number of rows and columns
and empty string as text.

It constructs a new text area and displays


3. TextArea (String text)
the specified text in it.

It constructs a new text area with the


TextArea (String text, int row, int
4. specified text in the text area and
column)
specified number of rows and columns.

It construcst a new text area with


TextArea (String text, int row, int specified text in text area and specified
5.
column, int scrollbars) number of rows and columns and
visibility.

Methods Inherited
The methods of TextArea class are inherited from following classes:

o java.awt.TextComponent
o java.awt.Component
o java.lang.Object

TetArea Class Methods

Sr. no. Method name Description

1. void addNotify() It creates a peer of text area.

It appends the specified text to the


2. void append(String str)
current text of text area.

AccessibleContext It returns the accessible context related


3.
getAccessibleContext() to the text area

It returns the number of columns of text


4. int getColumns()
area.

It determines the minimum size of a text


5. Dimension getMinimumSize()
area.

6. It determines the minimum size of a text


Dimension getMinimumSize(int rows,
area with the given number of rows and
int columns) columns.

Java AWT TextArea Example


The below example illustrates the simple implementation of TextArea where we are creating a text area using the constructor
TextArea(String text) and adding it to the frame.

TextAreaExample .java

. //importing AWT class


. import java.awt.*;
. public class TextAreaExample
. {
. // constructor to initialize
. TextAreaExample() {
. // creating a frame
. Frame f = new Frame();
. // creating a text area
. TextArea area = new TextArea("Welcome to javatpoint");
. // setting location of text area in frame
. area.setBounds(10, 30, 300, 300);
. // adding text area to frame
. f.add(area);
. // setting size, layout and visibility of frame
. f.setSize(400, 400);
. f.setLayout(null);
. f.setVisible(true);
. }
. // main method
. public static void main(String args[])
. {
. new TextAreaExample();
. }
. }
Output:
Java LayoutManagers

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

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

Java BorderLayout

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

1. public static final int NORTH


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

Constructors of BorderLayout class:


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

Example of BorderLayout class: Using BorderLayout() constructor

FileName: Border.java

. import java.awt.*;
. import javax.swing.*;
.
. public class Border
. {
. JFrame f;
. Border()
. {
. f = new JFrame();
.
. // creating buttons
. JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
. JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
. JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
. JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
. JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
.
. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
.
. f.setSize(300, 300);
. f.setVisible(true);
. }
. public static void main(String[] args) {
. new Border();
. }
. }
Output:
Example of BorderLayout class: Using BorderLayout(int hgap, int vgap) constructor

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

FileName: BorderLayoutExample.java

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

Java BorderLayout: Without Specifying Region

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

FileName: BorderLayoutWithoutRegionExample.java
. // import statements
. import java.awt.*;
. import javax.swing.*;
.
. public class BorderLayoutWithoutRegionExample
. {
. JFrame jframe;
.
. // constructor
. BorderLayoutWithoutRegionExample()
. {
. jframe = new JFrame();
.
. JButton btn1 = new JButton("NORTH");
. JButton btn2 = new JButton("SOUTH");
. JButton btn3 = new JButton("EAST");
. JButton btn4 = new JButton("WEST");
. JButton btn5 = new JButton("CENTER");
.
. // horizontal gap is 7, and the vertical gap is 7
. // Since region is not specified, the gaps are of no use
. jframe.setLayout(new BorderLayout(7, 7));
.
. // each button covers the whole area
. // however, the btn5 is the latest button
. // that is added to the frame; therefore, btn5
. // is shown
. jframe.add(btn1);
. jframe.add(btn2);
. jframe.add(btn3);
. jframe.add(btn4);
. jframe.add(btn5);
.
. jframe.setSize(300,300);
. jframe.setVisible(true);
. }
.
. // main method
. public static void main(String argvs[])
. {
. new BorderLayoutWithoutRegionExample();
. }
. }
Output:
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the
MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem class.

AWT MenuItem class declaration

. public class MenuItem extends MenuComponent implements Accessible

AWT Menu class declaration

. public class Menu extends MenuItem implements MenuContainer, Accessible

Java AWT MenuItem and Menu Example

. import java.awt.*;
. class MenuExample
. {
. MenuExample(){
. Frame f= new Frame("Menu and MenuItem Example");
. MenuBar mb=new MenuBar();
. Menu menu=new Menu("Menu");
. Menu submenu=new Menu("Sub Menu");
. MenuItem i1=new MenuItem("Item 1");
. MenuItem i2=new MenuItem("Item 2");
. MenuItem i3=new MenuItem("Item 3");
. MenuItem i4=new MenuItem("Item 4");
. MenuItem i5=new MenuItem("Item 5");
. menu.add(i1);
. menu.add(i2);
. menu.add(i3);
. submenu.add(i4);
. submenu.add(i5);
. menu.add(submenu);
. mb.add(menu);
. f.setMenuBar(mb);
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. public static void main(String args[])
. {
. new MenuExample();
. }
. }
Output:
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some form of input from the user. It
inherits the Window class.

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

Frame vs Dialog

Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't have.

AWT Dialog class declaration

. public class Dialog extends Window

Java AWT Dialog Example

. import java.awt.*;
. import java.awt.event.*;
. public class DialogExample {
. private static Dialog d;
. DialogExample() {
. Frame f= new Frame();
. d = new Dialog(f , "Dialog Example", true);
. d.setLayout( new FlowLayout() );
. Button b = new Button ("OK");
. b.addActionListener ( new ActionListener()
. {
. public void actionPerformed( ActionEvent e )
. {
. DialogExample.d.setVisible(false);
. }
. });
. d.add( new Label ("Click button to continue."));
. d.add(b);
. d.setSize(300,300);
. d.setVisible(true);
. }
. public static void main(String args[])
. {
. new DialogExample();
. }
. }
Output:
Filedialog Java
In Java programming, handling files is a common task that developers often encounter. Whether it's reading from or writing
to files, selecting specific files for processing, or managing file-related operations, having a straightforward way to interact
with the file system is essential. Java's FileDialog class offers a convenient solution for these file-handling tasks, providing a
user-friendly interface for file selection and manipulation. In this section, we will explore the functionalities of the File
Dialog class in Java, along with comprehensive examples and output demonstrations.

Java FileDialog Class


Java's FileDialog class is part of the AWT (Abstract Window Toolkit) package, specifically designed for creating a file
dialog box. This dialog box serves as an intermediary between the user and the underlying file system, allowing users to
browse through directories, select files, and perform operations on the selected files. With its easy-to-use methods,
developers can integrate file-handling capabilities seamlessly into their Java applications.

FileDialog Examples:

Let's delve into some illustrative examples to comprehend the practical implementation of the FileDialog class in Java.

Example 1: Displaying a File Dialog for File Selection

FileDialogExample.java

. import java.awt.FileDialog;
. import java.awt.Frame;
. public class FileDialogExample {
. public static void main(String[] args) {
. // Create a Frame, which is a graphical window to host the FileDialog.
. Frame frame = new Frame("File Dialog Example");
. // Create a FileDialog with a title, "Select File."
. FileDialog fileDialog = new FileDialog(frame, "Select File");
. // Display the FileDialog, allowing the user to select a file.
. fileDialog.setVisible(true);
. // Retrieve the name of the selected file.
. String file = fileDialog.getFile();
. // Check if a file was selected.
. if (file == null) {
. // No file was selected; print a message to the console.
. System.out.println("No file selected");
. } else {
. // A file was selected; print the selected file's name to the console.
. System.out.println("Selected file: " + file);
. }
. }
. }
Output:

Selected file: example.txt


UNIT-5

Java I/O Tutorial


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

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

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

Core Concepts of Java I/O


Java I/O revolves around two primary concepts: streams and readers/writers.

Streams: Streams represent a sequence of data. In Java, there are two types of streams: input streams and output streams.
Input streams are used to read data from a source, while output streams are used to write data to a destination. Streams can
be categorized into byte streams (InputStream and OutputStream) and character streams (Reader and Writer).

Readers/Writers: Readers and writers are specialized stream classes designed for handling character data. They provide a
convenient way to read from and write to character-based data sources. Readers read character data from input streams,
while writers write character data to output streams.

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

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

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

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

. System.out.println("simple message");
. System.err.println("error message");
Let's see the code to get input from console.

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


. System.out.println((char)i);//will print the character

OutputStream Vs. InputStream


The explanation of OutputStream and InputStream classes are given below:

OutputStream

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

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

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

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

Useful Methods of OutputStream Class

Method Description

public void write(int) throws IOException It is used to write a byte to the current output stream.

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

public void flush() throws IOException It flushes the current output stream.

public void close() throws IOException It is used to close the current output stream.

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

Useful Methods of InputStream Class

Method Description

It reads the next byte of data from the input stream. It returns -
public abstract int read() throws IOException
1 at the end of the file.

It returns an estimate of the number of bytes that can be read


public int available() throws IOException
from the current input stream.

public void close() throws IOException It is used to close the current input stream.

InputStream Hierarchy

Java I/O Classes


1. Java provides a rich set of classes for performing I/O operations. Some of the key classes include:
2. InputStream and OutputStream: These abstract classes form the foundation for byte-oriented I/O operations.
They provide methods for reading and writing bytes from/to various sources and destinations.
3. Reader and Writer: These abstract classes are used for character-based I/O operations. They provide methods for
reading and writing characters from/to character-based streams.
4. FileInputStream and FileOutputStream: These classes allow reading from and writing to files in a byte-oriented
manner.
5. FileReader and FileWriter: These classes enable reading from and writing to files using character-oriented
operations.
6. BufferedInputStream and BufferedOutputStream: These classes provide buffering capabilities, which can
significantly improve I/O performance by reducing the number of system calls.
7. BufferedReader and BufferedWriter: These classes offer buffered reading and writing of character data,
enhancing I/O efficiency when working with character-based streams.

Practical Applications of Java I/O


Java I/O is employed in various real-world scenarios, including:

1. File Handling: Java I/O is extensively used for reading from and writing to files. Developers can manipulate files,
create directories, and perform file-related operations using Java's file I/O classes.
2. Network Communication: Java's socket classes (Socket and ServerSocket) facilitate network communication by
enabling data exchange between client and server applications over TCP/IP.
3. Serialization: Java's serialization mechanism allows objects to be converted into a stream of bytes for storage or
transmission. It is particularly useful for storing object state or transferring objects between applications.
4. Data Processing: Java I/O is integral to data processing tasks such as parsing text files, processing CSV data, and
interacting with databases through JDBC (Java Database Connectivity).

ByteStream Classes in Java


ByteStream classes are used to read bytes from the input stream and write bytes to the output stream. In other words, we can
say that ByteStream classes read/write the data of 8-bits. We can store video, audio, characters, etc., by using ByteStream
classes. These classes are part of the java.io package.

The ByteStream classes are divided into two types of classes, i.e., InputStream and OutputStream. These classes are abstract
and the super classes of all the Input/Output stream classes.

InputStream Class

The InputStream class provides methods to read bytes from a file, console or memory. It is an abstract class and can't be
instantiated; however, various classes inherit the InputStream class and override its methods. The subclasses of InputStream
class are given in the following table.

SN Class Description

This class provides methods to read


1 BufferedInputStream
bytes from the buffer.

This class provides methods to read


2 ByteArrayInputStream
bytes from the byte array.

This class provides methods to read Java


3 DataInputStream
primitive data types.
This class provides methods to read
4 FileInputStream
bytes from a file.

This class contains methods to read


bytes from the other input streams,
5 FilterInputStream
which are used as the primary source of
data.

This class provides methods to read


6 ObjectInputStream
objects.

This class provides methods to read from


7 PipedInputStream a piped output stream to which the piped
input stream must be connected.

This class provides methods to connect


8 SequenceInputStream multiple Input Stream and read data
from them.

The InputStream class contains various methods to read the data from an input stream. These methods are overridden by the
classes that inherit the InputStream class. However, the methods are given in the following table.

SN Method Description

This method returns an integer, an


integral representation of the next
1 int read() available byte of the input. The integer -
1 is returned once the end of the input is
encountered.

This method is used to read the specified


buffer length bytes from the input and
2 int read (byte buffer []) returns the total number of bytes
successfully read. It returns -1 once the
end of the input is encountered.

This method is used to read the 'nBytes'


bytes from the buffer starting at a
int read (byte buffer [], int loc, int specified location, 'loc'. It returns the
3
nBytes) total number of bytes successfully read
from the input. It returns -1 once the end
of the input is encountered.

This method returns the number of bytes


4 int available ()
that are available to read.

This method is used to mark the current


5 Void mark(int nBytes) position in the input stream until the
specified nBytes are read.

This method is used to reset the input


6 void reset ()
pointer to the previously set mark.
This method is used to skip the nBytes
7 long skip (long nBytes) of the input stream and returns the total
number of bytes that are skipped.

This method is used to close the input


source. If an attempt is made to read
8 void close ()
even after the closing, IOException is
thrown by the method.

OutputStream Class

The OutputStream is an abstract class that is used to write 8-bit bytes to the stream. It is the superclass of all the output
stream classes. This class can't be instantiated; however, it is inherited by various subclasses that are given in the following
table.

SN Class Description

This class provides methods to write the


1 BufferedOutputStream
bytes to the buffer.

This class provides methods to write


2 ByteArrayOutputStream
bytes to the byte array.

This class provides methods to write the


3 DataOutputStream
java primitive data types.

This class provides methods to write


4 FileOutputStream
bytes to a file.

This class provides methods to write to


5 FilterOutputStream
other output streams.

This class provides methods to write


6 ObjectOutputStream
objects.

It provides methods to write bytes to a


7 PipedOutputStream
piped output stream.

It provides methods to print Java


8 PrintStream
primitive data types.

The OutputStream class provides various methods to write bytes to the output streams. The methods are given in the
following table.

SN Method Description

This method is used to write the


1 void write (int i) specified single byte to the output
stream.
It is used to write a byte array to the
2 void write (byte buffer [] )
output stream.

It is used to write nByte bytes to the


Void write(bytes buffer[],int loc, int
3 output stream from the buffer starting at
nBytes)
the specified location.

It is used to flush the output stream and


4 void flush ()
writes the pending buffered bytes.

It is used to close the output stream.


However, if we try to close the already
5 void close ()
closed output stream, the IOException
will be thrown by this method.

Example:

The following example uses the ByteArrayInputStream to create an input stream from a byte array "content". We use the
read() method to read the content from an input stream. We have also used the write() method on a FileOutputStream object
to write the byte array content in the file.

Consider the following example.

. import java.io.ByteArrayInputStream;
. import java.io.File;
. import java.io.FileInputStream;
. import java.io.FileNotFoundException;
. import java.io.FileOutputStream;
. import java.io.IOException;
.
.
. public class InputOutputStreamExample {
.
.
. public static void main(String[] args) throws IOException {
. // TODO Auto-generated method stub
. byte content[] = "Jtp is the best website to learn new technologies".getBytes();
. ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
.
. inputStream.read(content);
.
. File newFile = new File("/Users/MyUser/Desktop/MyNewFile.doc");
. FileOutputStream outputStream = new FileOutputStream(newFile);
. outputStream.write(content);
.
. }
.
.
. }
Output:

A new file MyNewFile.doc will be created on desktop with the content "Jtp is the best website to learn new technologies".

CharacterStream Classes in Java


The java.io package provides CharacterStream classes to overcome the limitations of ByteStream classes, which can only
handle the 8-bit bytes and is not compatible to work directly with the Unicode characters. CharacterStream classes are used
to work with 16-bit Unicode characters. They can perform operations on characters, char arrays and Strings.

However, the CharacterStream classes are mainly used to read characters from the source and write them to the destination.
For this purpose, the CharacterStream classes are divided into two types of classes, I.e., Reader class and Writer class.

Reader Class

Reader class is used to read the 16-bit characters from the input stream. However, it is an abstract class and can't be
instantiated, but there are various subclasses that inherit the Reader class and override the methods of the Reader class. All
methods of the Reader class throw an IOException. The subclasses of the Reader class are given in the following table.

SN Class Description

This class provides methods to read


1. BufferedReader
characters from the buffer.

This class provides methods to read


2. CharArrayReader
characters from the char array.

This class provides methods to read


3. FileReader
characters from the file.

This class provides methods to read


4. FilterReader characters from the underlying character
input stream.

This class provides methods to convert


5 InputStreamReader
bytes to characters.

This class provides methods to read


6 PipedReader characters from the connected piped
output stream.

This class provides methods to read


7 StringReader
characters from a string.

The Reader class methods are given in the following table.

SN Method Description

This method returns the integral


1 int read() representation of the next character
present in the input. It returns -1 if the
end of the input is encountered.

This method is used to read from the


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

This method is used to read the specified


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

This method is used to mark the current


4 void mark(int nchars) position in the input stream until nChars
characters are read.

This method is used to reset the input


5 void reset()
pointer to the previous set mark.

This method is used to skip the specified


nChars characters from the input stream
6 long skip(long nChars)
and returns the number of characters
skipped.

This method returns a boolean value true


7 boolean ready() if the next request of input is ready.
Otherwise, it returns false.

This method is used to close the input


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

Writer Class

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

SN Class Description

This class provides methods to write


1 BufferedWriter
characters to the buffer.

This class provides methods to write


2 FileWriter
characters to the file.

3 CharArrayWriter This class provides methods to write the


characters to the character array.

This class provides methods to convert


4 OutpuStreamWriter
from bytes to characters.

This class provides methods to write the


5 PipedWriter
characters to the piped output stream.

This class provides methods to write the


6 StringWriter
characters to the string.

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

SN Method Description

This method is used to write the data to


1 void write()
the output stream.

This method is used to write a single


2 void write(int i)
character to the output stream.

This method is used to write the array of


3 Void write(char buffer[])
characters to the output stream.

This method is used to write the nChars


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

This method is used to close the output


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

This method is used to flush the output


6 void flush () stream and writes the waiting buffered
characters.

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

The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The
serialization and deserialization process is platform-independent, it means you can serialize an object on one platform and
deserialize it on a different platform.
For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call
the readObject() method of ObjectInputStream class.

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

Advantages of Java Serialization

It is mainly used to travel object's state on the network (that is known as marshalling).

java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of
these classes may get a certain capability. The Cloneable and Remote are also marker interfaces.

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

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

Let's see the example given below:

Student.java

. import java.io.Serializable;
. public class Student implements Serializable{
. int id;
. String name;
. public Student(int id, String name) {
. this.id = id;
. this.name = name;
. }
. }
In the above example, Student class implements Serializable interface. Now its objects can be converted into stream. The
main class implementation of is showed in the next code.

ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputStream. Only objects that
support the java.io.Serializable interface can be written to streams.

Constructor

1) public ObjectOutputStream(OutputStream out) throws It creates an ObjectOutputStream that writes to the specified
IOException {} OutputStream.

Important Methods

Method Description

1) public final void writeObject(Object obj) throws


It writes the specified object to the ObjectOutputStream.
IOException {}

2) public void flush() throws IOException {} It flushes the current output stream.

3) public void close() throws IOException {} It closes the current output stream.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

Constructor

1) public ObjectInputStream(InputStream in) throws It creates an ObjectInputStream that reads from the specified
IOException {} InputStream.

Important Methods

Method Description

1) public final Object readObject() throws IOException,


It reads an object from the input stream.
ClassNotFoundException{}

2) public void close() throws IOException {} It closes ObjectInputStream.

Example of Java Serialization


In this example, we are going to serialize the object of Student class from above code. The writeObject() method of
ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file
named f.txt.

Persist.java
. import java.io.*;
. class Persist{
. public static void main(String args[]){
. try{
. //Creating the object
. Student s1 =new Student(211,"ravi");
. //Creating stream and writing the object
. FileOutputStream fout=new FileOutputStream("f.txt");
. ObjectOutputStream out=new ObjectOutputStream(fout);
. out.writeObject(s1);
. out.flush();
. //closing the stream
. out.close();
. System.out.println("success");
. }catch(Exception e){System.out.println(e);}
. }
. }
Output:

success

You might also like