0% found this document useful (0 votes)
0 views548 pages

Java Notes

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

Java Notes

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

UNIT-1 CHAPTER -1

TOPIC: A WAY OF VIEWING WORLD


A way of viewing the world is an idea to illustrate the object-oriented
programming concept with an example of a real-world situation.
Let us consider a situation, I am at my office and I wish to get food to
my family members who are at my home from a hotel. Because of the
distance from my office to home, there is no possibility of getting food
from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delivery
community), tell them the variety and quantity of food and the hotel
name from which I wish to delever the food to my family members.
Look at the following image.

Agents and Communities


To solve my food delivery problem, I used a solution by finding an
appropriate agent (Zomato) and pass a message containing my request. It
is the responsibility of the agent (Zomato) to satisfy my request. Here,
the agent uses some method to do this. I do not need to know the method
that the agent has used to solve my request. This is usually hidden from
me.
So, in object-oriented programming, problem-solving is the solution to
our problem which requires the help of many individuals in the
community. We may describe agents and communities as follows.
An object-oriented program is structured as a community of
interacting agents, called objects. Where each object provides a
service (data and methods) that is used by other members of the
community.
In our example, the online food delivery system is a community in
which the agents are zomato and set of hotels. Each hotel provides a
variety of services that can be used by other members like zomato,
myself, and my family in the community.

Messages and Methods


To solve my problem, I started with a request to the agent zomato, which
led to still more requestes among the members of the community until
my request has done. Here, the members of a community interact with
one another by making requests until the problem has satisfied.
In object-oriented programming, every action is initiated by passing
a message to an agent (object), which is responsible for the action.
The receiver is the object to whom the message was sent. In response
to the message, the receiver performs some method to carry out the
request. Every message may include any additional information as
arguments.

In our example, I send a request to zomato with a message that contains


food items, the quantity of food, and the hotel details. The receiver uses
a method to food get delivered to my home.
Responsibilities
In object-oriented programming, behaviors of an object described in
terms of responsibilities.
In our example, my request for action indicates only the desired outcome
(food delivered to my family). The agent (zomato) free to use any
technique that solves my problem. By discussing a problem in terms of
responsibilities increases the level of abstraction. This enables more
independence between the objects in solving complex problems.

Classes and Instances


In object-oriented programming, all objects are instances of a class. The
method invoked by an object in response to a message is decided by the
class. All the objects of a class use the same method in response to a
similar message.
In our example, the zomato a class and all the hotels are sub-classes of
it. For every request (message), the class creates an instance of it and
uses a suitable method to solve the problem.

Classes Hierarchies
A graphical representation is often used to illustrate the relationships
among the classes (objects) of a community. This graphical
representation shows classes listed in a hierarchical tree-like structure. In
this more abstract class listed near the top of the tree, and more specific
classes in the middle of the tree, and the individuals listed near the
bottom.
In object-oriented programming, classes can be organized into a
hierarchical inheritance structure. A child class inherits properties
from the parent class that higher in the tree.
Method Binding, Overriding, and Exception
In the class hierarchy, both parent and child classes may have the same
method which implemented individually. Here, the implementation of
the parent is overridden by the child. Or a class may provide multiple
definitions to a single method to work with different arguments
(overloading).
The search for the method to invoke in response to a request (message)
begins with the class of this receiver. If no suitable method is found, the
search is performed in the parent class of it. The search continues up the
parent class chain until either a suitable method is found or the parent
class chain is exhausted. If a suitable method is found, the method is
executed. Otherwise, an error message is issued.
UNIT-1 CHAPTER-1
TOPIC: OOP CONCEPTS
OOP stands for Object-Oriented Programming. OOP is a programming
paradigm in which every program is follows the concept of object. In other
words, OOP is a way of writing programs based on the object concept.
The object-oriented programming paradigm has the following core concepts.

 Encapsulation
 Inheritance
 Polymorphism
 Abstraction

The popular object-oriented programming languages are Smalltalk, C++,


Java, PHP, C#, Python, etc.

Encapsulation

Encapsulation is the process of combining data and code into a single unit
(object / class). In OOP, every object is associated with its data and code. In
programming, data is defined as variables and code is defined as methods.
The java programming language uses the class concept to implement
encapsulation.

Inheritance
Inheritance is the process of acquiring properties and behaviors from one
object to another object or one class to another class. In inheritance, we
derive a new class from the existing class. Here, the new class acquires the
properties and behaviors from the existing class. In the inheritance concept,
the class which provides properties is called as parent class and the class
which recieves the properties is called as child class. The parent class is also
known as base class or supre class. The child class is also known as derived
class or sub class.
In the inheritance, the properties and behaviors of base class extended to its
derived class, but the base class never receive properties or behaviors from its
derived class.
In java programming language the keyword extends is used to implement inheritance.
Polymorphism

Polymorphism is the process of defining same method with different implementation.


That means creating multiple methods with different behaviors.
The java uses method overloading and method overriding to implement polymorphism.
Method overloading - multiple methods with same name but different parameters.
Method overriding - multiple methods with same name and same parameters.

Abstraction
Abstraction is hiding the internal details and showing only esential functionality. In the
abstraction concept, we do not show the actual implemention to the end user, instead
we provide only esential things. For example, if we want to drive a car, we does not
need to know about the internal functionality like how wheel system works? how brake
system works? how music system works? etc.
UNIT-1 CHAPTER-1
TOPIC: JAVA BUZZWORDS
Java is the most popular object-oriented programming language. Java has many
advanced features, a list of key features is known as Java Buzz Words. The java team
has listed the following terms as java buzz words.

 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Architecture-neutral (or) Platform Independent
 Multi-threaded
 Interpreted
 High performance
 Distributed
 Dynamic

Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++. In a java programming language, many
complicated features like pointers, operator overloading, structures, unions, etc. have
been removed. One of the most useful features is the garbage collector it makes java
more simple.

Secure
Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a web
application. The applet in java does not allow access to other parts of the computer,
which keeps away from harmful programs like viruses and unauthorized access.

Portable
Portability is one of the core features of java which enables the java programs to run on
any computer or operating system. For example, an applet developed using java runs
on a wide variety of CPUs, operating systems, and browsers connected to the Internet.

Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is
an object. It supports all the features of the object-oriented programming paradigm. The
primitive data types java also implemented as objects using wrapper classes, but still, it
allows primitive data types to archive high-performance.
Robust
Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage collector),
java is a strictly typed language, it has a strong set of exception handling mechanism,
and many more.

Architecture-neutral (or) Platform Independent


Java has invented to archive "write once; run anywhere, any time, forever". The java
provides JVM (Java Virtual Machine) to to archive architectural-neutral or platform-
independent. The JVM allows the java program created using one operating system can
be executed on any other operating system.

Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do
multiple operations simultaneously.

Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. The byte code is interpreted to any machine code
so that it runs on the native machine.

High performance
Java provides high performance with the help of features like JVM, interpretation, and
its simplicity.

Distributed
Java programming language supports TCP/IP protocols which enable the java to
support the distributed environment of the Internet. Java also supports Remote Method
Invocation (RMI), this feature enables a program to invoke methods across a network.

Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on
a running system and it has a dynamic memory allocation and deallocation (objects and
garbage collector).
UNIT-1 CHAPTER-1
TOPIC: OVERVIEW OF JAVA
Java is a computer programming language. Java was created based on C
and C++. Java uses C syntax and many of the object-oriented features
are taken from C++. Before Java was invented there were other
languages like COBOL, FORTRAN, C, C++, Small Talk, etc. These
languages had few disadvantages which were corrected in Java. Java
also innovated many new features to solve the fundamental problems
which the previous languages could not solve. Java was invented by a
team of 13 employees of Sun Microsystems, Inc. which is lead by James
Gosling, in 1991. The team includes persons like Patrick Naughton,
Chris Warth, Ed Frank, and Mike Sheridan, etc., Java was developed as
a part of the Green project. Initially, it was called Oak, later it was
changed to Java in 1995.

History of Java

 The C language developed in 1972 by Dennis Ritchie had taken a


decade to become the most popular language.
 In 1979, Bjarne Stroustrup developed C++, an enhancement to the
C language with included OOP fundamentals and features.
 A project named “Green” was initiated in December of 1990,
whose aim was to create a programming tool that could render
obsolete the C and C++ programming languages.
 Finally in the year of 1991 the Green Team was created a new
Programming language named “OAK”.
 After some time they found that there is already a programming
language with the name “OAK”.
 So, the green team had a meeting to choose a new name. After so
many discussions they want to have a coffee. They went to a
Coffee Shop which is just outside of the Gosling’s office and there
they have decided name as “JAVA”.

Execution Process of Java Program


The following three steps are used to create and execute a java program.

 Create a source code (.java file).


 Compile the source code using javac command.
 Run or execute .class file uisng java command.
UNIT-1 CHAPTER-1

TOPIC: DATA TYPES

Java programming language has a rich set of data types. The data type is a category
of data stored in variables. In java, data types are classified into two types and they
are as follows.

 Primitive Data Types


 Non-primitive Data Types

Primitive Data Types


The primitive data types are built-in data types and they specify the type of value
stored in a variable and the memory size. The primitive data types do not have any
additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char,
and boolean.
The following table provides more description of each primitive data type.
Non-primitive Data Types
In java, non-primitive data types are the reference data types or user-created data
types. All non-primitive data types are implemented using object concepts. Every
variable of the non-primitive data type is an object. The non-primitive data types may
use additional methods to perform certain operations. The default value of non-primitive
data type variable is null.
In java, examples of non-primitive data types
are String, Array, List, Queue, Stack, Class, Interface, etc.
UNIT-1 CHAPTER-1

TOPIC: JAVA VARIABLES

A variable is a named memory location used to store a data value. A variable can be defined as a
container that holds a data value.
In java, we use the following syntax to create variables.

In java programming language variables are clasiffied as follows.

 Local variables
 Instance variables or Member variables or Global variables
 Static variables or Class variables
 Final variables

Local variables
The variables declared inside a method or a block are known as local variables. A local variable is visible
within the method in which it is declared. The local variable is created when execution control enters into
the method or block and destroyed after the method or block execution completed.
Let's look at the following example java program to illustrate local variable in java.
Instance variables or member variables or global variables
The variables declared inside a class and outside any method, constructor or block are known as
instance variables or member variables. These variables are visible to all the methods of the class. The
changes made to these variables by method affects all the methods in the class. These variables are
created separate copy for every object of that class.
Let's look at the following example java program to illustrate instance variable in java.
Static variables or Class variables
A static variable is a variable that declared using static keyword. The instance variables can be static
variables but local variables can not. Static variables are initialized only once, at the start of the program
execution. The static variable only has one copy per class irrespective of how many objects we create.
The static variable is access by using class name.
Let's look at the following example java program to illustrate static variable in java.
Final variables
A final variable is a variable that declared using final keyword. The final variable is initialized only once,
and does not allow any method to change it's value again. The variable created using final keyword acts
as constant. All variables like local, instance, and static variables can be final variables.
Let's look at the following example java program to illustrate final variable in java.
UNIT-1 CHAPTER-1
TOPIC: JAVA ARRAYS
An array is a collection of similar data values with a single name. An array can
also be defined as, a special type of variable that holds multiple values of the same
data type at a time.
In java, arrays are objects and they are created dynamically using new operator.
Every array in java is organized using index values. The index value of an array
starts with '0' and ends with 'zise-1'. We use the index value to access individual
elements of an array.
In java, there are two types of arrays and they are as follows.

 One Dimensional Array


 Multi Dimensional Array

Creating an array
In the java programming language, an array must be created using new operator
and with a specific size. The size must be an integer value but not a byte, short, or
long. We use the following syntax to create an array.
In java, an array can also be initialized at the time of its declaration. When an array
is initialized at the time of its declaration, it need not specify the size of the array
and use of the new operator. Here, the size is automatically decided based on the
number of values that are initialized.

NullPointerException with Arrays


In java, an array created without size and initialized to null remains null only. It
does not allow us to assign a value. When we try to assign a value it generates
a NullPointerException.
Look at the following example program.
ArrayIndexOutOfBoundsException with Arrays
In java, the JVM (Java Virtual Machine) throws
ArrayIndexOutOfBoundsException when an array is trying to access with an
index value of negative value, value equal to array size, or value more than the
array size.
Look at the following example program.

Looping through an array


An entire array is accessed using either simple for statement or for-each
statement. Look at the following example program to display sum of all the
lements in a list.

Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-
dimensional, 3-dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional
array variable, specify each additional index using another set of square brackets.
We use the following syntax to create two-dimensional array.
When we create a two-dimensional array, it created with a separate index for rows
and columns. The individual element is accessed using the respective row index
followed by the column index. A multidimensional array can be initialized while it
has created using the following syntax.

When an array is initialized at the time of declaration, it need not specify the size
of the array and use of the new operator. Here, the size is automatically decided
based on the number of values that are initialized.

The above statement creates a two-dimensional array of three rows and two
columns.
UNIT-1 CHAPTER-1
TOPIC: JAVA OPERATORS
An operator is a symbol used to perform arithmetic and logical operations. Java provides a rich set of
operators.
In java, operators are clasiffied into the following four types.

 Arithmetic Operqators
 Relational (or) Comparision Operators
 Logical Operators
 Assignment Operators
 Bitwise Operators
 Conditional Operators

Let's look at each operator in detail.

Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations like addition,
subtraction, multiplication, division, modulus, increment, decrement, etc.,

Note:

 The addition operator can be used with numerical data types and character or string data type.
When it is used with numerical values, it performs mathematical addition and when it is used with
character or string data type values, it performs concatination (appending).
 The modulus (remainder of the division) operator is used with integer data type only.
 The increment and decrement operators are used as pre-increment or pre-
decrement and post-increment or post-decrement.
 When they are used as pre, the value is get modified before it is used in the actual expresion and
when it is used as post, the value is get modified after the the actual expression evaluation.
Relational Operators (<, >, <=, >=, ==, !=)
The relational operators are the symbols that are used to compare two values. That means the relational
operators are used to check the relationship between two values. Every relational operator has two
posible results either TRUE or FALSE. In simple words, the relational operators are used to define
conditions in a program. The following table provides information about relational operators.
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one condition.
The following table provides information about logical operators.

Note:
 The operators &, |, and ^ can be used with both boolean and integer data type values.
When they are used with integers, performs bitwise operations and with boolean,
performs logical operations.
 Logical operators and Short-circuit operators both are similar, but in case of short-
circuit operators once the decision is finalized it does not evaluate remaining
expressions.
Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand
side variable (Lvalue). The assignment operator is used in different variants along with
arithmetic operators. The following table describes all the assignment operators in the java
programming language.
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming
language. When we use the bitwise operators, the operations are performed based on binary
values. The following table describes all the bitwise operators in the java programming
language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Conditional Operators
The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first, we verify a condition, then we
perform one operation out of the two operations based on the condition result. If the condition is
TRUE the first option is performed, if the condition is FALSE the second option is performed.
The conditional operator is used with the following syntax.
UNIT-1 CHAPTER-1
TOPIC: EXPRESSIONS
In any programming language, if we want to perform any calculation or to frame any condition
etc., we use a set of symbols to perform the task. These set of symbols makes an expression.
In the java programming language, an expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a
direct value or variable or address of memory location.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as
follows.
 Infix Expression
 Postfix Expression
 Prefix Expression
The above classification is based on the operator position in the expression.
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example

Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example

Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
UNIT-1 CHAPTER-1

TOPIC: CONTROL STATEMENTS

In java, the default execution flow of a program is a sequential order. But the sequential order of
execution flow may not be suitable for all situations. Sometimes, we may want to jump from line
to another line, we may want to skip a part of the program, or sometimes we may want to
execute a part of the program again and again. To solve this problem, java provides control
statements.

In java, the control statements are the statements which will tell us that in which order the
instructions are getting executed. The control statements are used to control the order of
execution according to our requirements. Java provides several control statements, and they
are classified as follows.

Types of Control Statements


In java, the control statements are classified as follows.

 Selection Control Statements ( Decision Making Statements )


 Iterative Control Statements ( Looping Statements )
 Jump Statements

Let's look at each type of control statements in java.

Selection Control Statements


In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed
based on a condition. Java provides the following selection statements.
 if statement
 if-else statement
 if-elif statement
 nested if statement
 switch statement

Iterative Control Statements


In java, the iterative statements are also known as looping statements or repetitive statements.
The iterative statements are used to execute a part of the program repeatedly as long as the
given condition is True. Using iterative statements reduces the size of the code, reduces the
code complexity, makes it more efficient, and increases the execution speed. Java provides the
following iterative statements.

 while statement
 do-while statement
 for statement
 for-each statement

Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the
next iteration. Java provides the following jump statements.

 break
 continue
 return
TOPIC: ITERATIVE STATEMENT

The java programming language provides a set of iterative statements that are used to execute
a statement or a block of statements repeatedly as long as the given condition is true. The
iterative statements are also known as looping statements or repetitive statements. Java
provides the following iterative statements.

 while statement
 do-while statement
 for statement
 for-each statement

while statement in java


The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control looping
statement. The syntax and execution flow of while statement is as follows.
do-while statement in java
The do-while statement is used to execute a single statement or block of statements repeatedly
as long as given the condition is TRUE. The do-while statement is also known as the Exit
control looping statement. The do-while statement has the following syntax.
for statement in java
The for statement is used to execute a single statement or a block of statements repeatedly as
long as the given condition is TRUE. The for statement has the following syntax and execution
flow diagram.
In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of
statements executed otherwise it terminates the for-statement. After the block of statements
execution, the modification statement gets executed, followed by condition again.
for-each statement in java
The Java for-each statement was introduced since Java 5.0 version. It provides an approach to
traverse through an array or collection in Java. The for-each statement also known
as enhanced for statement. The for-each statement executes the block of statements for each
element of the given array or collection.
Note:In for-each statement, we can not skip any element of given array or collection

The for-each statement has the following syntax and execution flow diagram.
TOPIC: JUMP STATEMENT

The java programming language supports jump statements that used to transfer execution
control from one line to another line. The java programming language provides the following
jump statements.

 break statement
 continue statement
 labelled break and continue statements
 return statement

break statement in java


The break statement in java is used to terminate a switch or looping statement. That means the
break statement is used to come out of a switch statement and a looping statement like while,
do-while, for, and for-each.
🔔 Using the break statement outside the switch or loop statement is not allowed.

The following picture depictes the execution flow of the break statement.
continue statement in java
The continue statement is used to move the execution control to the beginning of the looping
statement. When the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly jumps to the beginning
of the loop. The continue statement can be used with looping statements like while, do-while,
for, and for-each.
When we use continue statement with while and do-while statements, the execution control
directly jumps to the condition. When we use continue statement with for statement the
execution control directly jumps to the modification portion (increment/decrement/any
modification) of the for loop. The continue statement flow of execution is as shown in the
following figure.
Labelled break and continue statement in java
The java programming langauge does not support goto statement, alternatively, the break and
continue statements can be used with label.
The labelled break statement terminates the block with specified label. The labbeled contonue
statement takes the execution control to the beginning of a loop with specified label.
Let's look at the following example java code.
return statement in java
In java, the return statement used to terminate a method with or without a value. The return
statement takes the execution control to the calling function. That means the return statement
transfer the execution control from called function to the calling function by carrying a value.
🔔 Java allows the use of return-statement with both, with and without return type methods.

In java, the return statement used with both methods with and without return type. In the case of
a method with the return type, the return statement is mandatory, and it is optional for a method
without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is
used without a return type, it does not carry any value. Instead, simply transfers the execution
control.
Let's look at the following example java code.
TOPIC: SELECTION STATEMENTS
In java, the selection statements are also known as decision making statements or branching
statements or conditional control statements. The selection statements are used to select a part
of the program to be executed based on a condition. Java provides the following selection
statements.

 if statement
 if-else statement
 nested if statement
 if-else if statement
 switch statement

if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result. The if statement checks, the given condition then
decides the execution of a block of statements. If the condition is True, then the block of
statements is executed and if it is False, then the block of statements is ignored. The syntax and
execution flow of if the statement is as follows.
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False
and the condition is evaluated to False. Then the if statement ignores the execution of its block
of statements.
When we enter a number which is divisible by 5, then it produces the output as follows.

if-else statement in java


In java, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result. The if-else statement checks the
given condition then decides which block of statements to be executed based on the condition
result. If the condition is True, then the true block of statements is executed and if it is False,
then the false block of statements is executed. The syntax and execution flow of if-else
statement is as follows.
Nested if statement in java
Writing an if statement inside another if-statement is called nested if statement. The general
syntax of the nested if-statement is as follows.
if-else if statement in java
Writing an if-statement inside else of an if statement is called if-else-if statement. The general
syntax of the an if-else-if statement is as follows.
switch statement in java
Using the switch statement, one can select only one option from more number of options very
easily. In the switch statement, we provide a value that is to be compared with a value
associated with each option. Whenever the given value matches the value associated with an
option, the execution starts from that option. In the switch statement, every option is defined as
a case.
The switch statement has the following syntax and execution flow diagram.
Note: In java, the case value of a switch statement can be a String value.
UNIT-1 CHAPTER-1

TOPIC: JAVA CLASSES

Java is an object-oriented programming language, so everything in java program must be based


on the object concept. In a java programming language, the class concept defines the skeleton
of an object.
The java class is a template of an object. The class defines the blueprint of an object. Every
class in java forms a new data type. Once a class got created, we can generate as many
objects as we want. Every class defines the properties and behaviors of an object. All the
objects of a class have the same properties and behaviors that were defined in the class.
Every class of java programming language has the following characteristics.

 Identity - It is the name given to the class.


 State - Represents data values that are associated with an object.
 Behavior - Represents actions can be performed by an object.

Look at the following picture to understand the class and object concept.

Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as
variables and behaviors as methods. Following is the syntax of class in the java.
T
he ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.

Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is
said to be instantiated. All the objects that are created using a single class have the same
properties and methods. But the value of properties is different for every object. Following is the
syntax of class in the java.

The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules.
UNIT-1 CHAPTER-1

TOPIC: JAVA METHODS

A method is a block of statements under a name that gets executes only when it is called. Every
method is used to perform a specific task. The major advantage of methods is code re-usability
(define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means,
every method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.

 returnType - Specifies the data type of a return value.


 name - Specifies a unique name to identify it.
 parameters - The data values it may accept or recieve.
 { } - Defienes the block belongs to the method.

Creating a method
A method is created inside the class and it may be created with any access specifier. However,
specifying access specifier is optional.
Following is the syntax for creating methods in java.

NOTE:
 The methodName must begin with an alphabet, and the Lower-case letter is preferred.
 The methodName must follow all naming rules.
 If you don't want to pass parameters, we ignore it.
 If a method defined with return type other than void, it must contain the return
statement, otherwise, it may be ignored.

Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot
operator. It may call directly if the method defined with the static modifier. Every method call
must be made, as to the method name with parentheses (), and it must terminate with a
semicolon.

NOTE:
 The method call must pass the values to parameters if it has.
 If the method has a return type, we must provide the receiver.

NOTE:
 The objectName must begin with an alphabet, and a Lower-case letter is
preferred.
 The objectName must follow all naming rules.
Variable arguments of a method
In java, a method can be defined with a variable number of arguments. That means creating a
method that receives any number of arguments of the same data type.

NOTE: When a method has both the normal parameter and variable-argument,
then the variable argument must be specified at the end in the parameters list.

Constructor
A constructor is a special method of a class that has the same name as the class name. The
constructor gets executes automatically on object creation. It does not require the explicit
method call. A constructor may have parameters and access specifiers too. In java, if you do not
provide any constructor the compiler automatically creates a default constructor.
Let's look at the following example java code.

NOTE: A constructor can not have return value.


UNIT-1 CHAPTER-1

TOPIC: STRING HANDLING

A string is a sequence of characters surrounded by double quotations. In a java programming


language, a string is the object of a built-in class String.
In the background, the string values are organized as an array of a character data type.
The string created using a character array can not be extended. It does not allow to append
more characters after its definition, but it can be modified.
Let's look at the following example java code.

The String class defined in the package java.lang package. The String class
implements Serializable, Comparable, and CharSequence interfaces.
The string created using the String class can be extended. It allows us to add more characters
after its definition, and also it can be modified.
Let's look at the following example java code.
String siteName=”gmail.com”;

siteName=www.gmail.com”;

Creating String object in java


In java, we can use the following two ways to create a string object.

 Using string literal


 Using String constructor

Let's look at the following example java code.


String title=”Java Programming”;

String siteName=new String(“www.jntuh.ac.in”);


String handling methods
In java programming language, the String class contails various methods that can be used to
handle string data values. It containg methods like concat( ), compareTo( ), split( ), join( ),
replace( ), trim( ), length( ), intern( ), equals( ), comparison( ), substring( ), etc.
The following table depicts all built-in methods of String class in java.
UNIT-1 CHAPTER-2

TOPIC: CONSTRUCTORS IN INHERITANCE

It is very important to understand how the constructors get executed in the inheritance concept.
In the inheritance, the constructors never get inherited to any child class.
In java, the default constructor of a parent class called automatically by the constructor of its
child class. That means when we create an object of the child class, the parent class
constructor executed, followed by the child class constructor executed.
Let's look at the following example java code.

However, if the parent class contains both default and parameterized constructor, then only the
default constructor called automatically by the child class constructor.
Let's look at the following example java code.
The parameterized constructor of parent class must be called explicitly using
the super keyword.
UNIT-1 CHAPTER-2
TOPIC: ACCESS MODIFIERS
In Java, the access specifiers (also known as access modifiers) used to restrict the scope or
accessibility of a class, constructor, variable, method or data member of class and interface.
There are four access specifiers, and their list is below.

 default (or) no modifier


 public
 protected
 private

In java, we can not employ all access specifiers on everything. The following table describes
where we can apply the access specifiers.
Let's look at the following example java code, which generates an error because a class does
not allow private access specifier unless it is an inner class.

In java, the accessibility of the members of a class or interface depends on its access specifiers.
The following table provides information about the visibility of both data members and methods.

🔔 The public members can be accessed everywhere.


🔔 The private members can be accessed only inside the same class.
🔔 The protected members are accessible to every child class (same package or other
packages).
🔔 The default members are accessible within the same package but not outside the package.
UNIT-1 CHAPTER-2

TOPIC: INHERITANCE BASICS

Inheritance Concept
The inheritance is a very useful and powerful concept of object-oriented programming. In java,
using the inheritance concept, we can use the existing features of one class in another class.
The inheritance provides a greate advantage called code re-usability. With the help of code re-
usability, the commonly used code in an application need not be written again and again.

The inheritance can be defined as follows.


The inheritance is the process of acquiring the properties of one class to another class.
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.
The Parent class is the class which provides features to another class. The parent class is also
known as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also
known as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the parent
class never acquires the features from its child class.

There are five types of inheritances, and they are as follows.

 Simple Inheritance (or) Single Inheritance


 Multiple Inheritance
 Multi-Level Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

The following picture illustrates how various inheritances are implemented.


The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.

Creating Child Class in java


In java, we use the keyword extends to create a child class. The following syntax used to create
a child class in java.

Syntax
class <ChildClassName> extends <ParentClassName>{
...
//Implementation of child class
...
}
In a java programming language, a class extends only one class. Extending multiple classes is
not allowed in java.

Let's look at individual inheritance types and how they get implemented in java with an example.

Single Inheritance in java


In this type of inheritance, one child class derives from one parent class. Look at the following
example code.

Multi-level Inheritance in java


In this type of inheritance, the child class derives from a class which already derived from
another class. Look at the following example java code.
Hierarchical Inheritance in java
In this type of inheritance, two or more child classes derive from one parent class. Look at the
following example java code.
Hybrid Inheritance in java
The hybrid inheritance is the combination of more than one type of inheritance. We may use any
combination as a single with multiple inheritances, multi-level with multiple inheritances, etc.,
UNIT-1 CHAPTER-2
TOPIC: FINAL KEYWORD
In java, the final is a keyword and it is used with the following things.

 With variable (to create constant)


 With method (to avoid method overriding)
 With class (to avoid inheritance)

Let's look at each of the above.

final with variables


When a variable defined with the final keyword, it becomes a constant, and it does not allow us
to modify the value. The variable defined with the final keyword allows only a one-time
assignment, once a value assigned to it, never allows us to change it again.
Let's look at the following example java code.

final with methods


When a method defined with the final keyword, it does not allow it to override. The final method
extends to the child class, but the child class can not override or re-define it. It must be used as
it has implemented in the parent class.
Let's look at the following example java code.
final with class
When a class defined with final keyword, it can not be extended by any other class.
Let's look at the following example java code.
UNIT-1 CHAPTER-2

TOPIC: SUPER KEYWORD

In java, super is a keyword used to refers to the parent class object. The super keyword came
into existence to solve the naming conflicts in the inheritance. When both parent class and child
class have members with the same name, then the super keyword is used to refer to the parent
class version.
In java, the super keyword is used for the following purposes.

 To refer parent class data members


 To refer parent class methods
 To call parent class constructor

🔔 The super keyword is used inside the child class only.

super to refer parent class data members


When both parent class and child class have data members with the same name, then the
super keyword is used to refer to the parent class data member from child class.
Let's look at the following example java code.
super to refer parent class method
When both parent class and child class have method with the same name, then the super
keyword is used to refer to the parent class method from child class.
Let's look at the following example java code.
super to call parent class constructor
When an object of child class is created, it automatically calls the parent class default-
constructor before it's own. But, the parameterized constructor of parent class must be called
explicitly using the super keyword inside the child class constructor.
Let's look at the following example java code.
To call the parameterized constructor of the parent class, the super keyword must be the first
statement inside the child class constructor, and we must pass the parameter values.
UNIT-1 CHAPTER-2

TOPIC: POLYMORPHISM

The polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviors.
In java, polymorphism implemented using method overloading and method overriding.

Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc
polymorphism carried out with a method overloading concept.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded with the
respective overloaded method based on the arguments.
The ad hoc polymorphism implemented within the class only.
Let's look at the following example java code.

Pure polymorphism
The pure polymorphism is a technique used to define the same method with the same
arguments but different implementations. In a java programming language, pure polymorphism
carried out with a method overriding concept.
In pure polymorphism, the method binding happens at run time. Pure polymorphism is also
known as run-time polymorphism. Every function call binding with the respective overridden
method based on the object reference.
When a child class has a definition for a member function of the parent class, the parent class
function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.
Let's look at the following example java code.
UNIT-1 CHAPTER-2

TOPIC: METHOD OVERRIDING

The method overriding is the process of re-defining a method in a child class that is already
defined in the parent class. When both parent and child classes have the same method, then
that method is said to be the overriding method.
The method overriding enables the child class to change the implementation of the method
which aquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The method
binding which happens at run time is known as late binding. So, the method overriding follows
late binding.
The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.
Let's look at the following example java code.
10 Rules for method overriding
While overriding a method, we must follow the below list of rules.

 Static methods can not be overridden.


 Final methods can not be overridden.
 Private methods can not be overridden.
 Constructor can not be overridden.
 An abstract method must be overridden.
 Use super keyword to invoke overridden method from child class.
 The return type of the overriding method must be same as the parent has it.
 The access specifier of the overriding method can be changed, but the visibility must
increase but not decrease. For example, a protected method in the parent class can be
made public, but not private, in the child class.
 If the overridden method does not throw an exception in the parent class, then the child
class overriding method can only throw the unchecked exception, throwing a checked
exception is not allowed.
 If the parent class overridden method does throw an exception, then the child class
overriding method can only throw the same, or subclass exception, or it may not throw
any exception.
UNIT-1 CHAPTER-2

TOPIC:ABSTRACT CLASS

An abstract class is a class that created using abstract keyword. In other words, a class prefixed
with abstract keyword is known as an abstract class.
In java, an abstract class may contain abstract methods (methods without implementation) and
also non-abstract methods (methods with implementation).
We use the following syntax to create an abstract class.
An abstract class can not be instantiated but can be referenced. That means we can not create
an object of an abstract class, but base reference can be created.
In the above example program, the child class objects are created to invoke the overridden
abstract method. But we may also create base class reference and assign it with child class
instance to invoke the same. The main method of the above program can be written as follows
that produce the same output.

8 Rules for method overriding


An abstract class must follow the below list of rules.

 An abstract class must be created with abstract keyword.


 An abstract class can be created without any abstract method.
 An abstract class may contain abstract methods and non-abstract methods.
 An abstract class may contain final methods that can not be overridden.
 An abstract class may contain static methods, but the abstract method can not be static.
 An abstract class may have a constructor that gets executed when the child class object
created.
 An abstract method must be overridden by the child class, otherwise, it must be defined
as an abstract class.
 An abstract class can not be instantiated but can be referenced.
UNIT-1 CHAPTER-2

TOPIC: OBJECT CLASS

In java, the Object class is the super most class of any class hierarchy. The Object class in the
java programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know.
Because it is the superclass of all other classes in java, it can refer to any type of object.

Methods of Object class


The following table depicts all built-in methods of Object class in java.
UNIT-1 CHAPTER-2

TOPIC: BENEFITS & COSTS OF INHERITANCE

The inheritance is the core and more useful concept Object Oriented Programming. It provides
with inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class. An
inheritance leads to less development and maintenance costs with lot of benefits and few of
them are listed below.

Benefits of Inheritance
 Inheritance helps in code reuse. The child class may use the code defined in the parent
class without re-writing it.
 Inheritance can save time and effort as the main code need not be written again.
 Inheritance provides a clear model structure which is easy to understand.
 An inheritance leads to less development and maintenance costs.
 With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived
class. An inheritance leads to less development and maintenance costs.
 In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.

Costs of Inheritance
 Inheritance decreases the execution speed due to the increased time and effort it takes,
the program to jump through all the levels of overloaded classes.
 Inheritance makes the two classes (base and inherited class) get tightly coupled. This
means one cannot be used independently of each other.
 The changes made in the parent class will affect the behavior of child class too.
 The overuse of inheritance makes the program more complex.
UNIT-1 CHAPTER-2

TOPIC:FORMS OF INHERITANCE

The inheritance concept used for the number of purposes in the java programming language.
One of the main purposes is substitutability. The substitutability means that when a child class
acquires properties from its parent class, the object of the parent class may be substituted with
the child class object. For example, if B is a child class of A, anywhere we expect an instance of
A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
The following are the differnt forms of inheritance in java.

 Specialization
 Specification
 Construction
 Eextension
 Limitation
 Combination

Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It
holds the principle of substitutability.

Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent class
just specifies which methods should be available to the child class but doesn't implement them.
The java provides concepts like abstract and interfaces to support this form of inheritance. It
holds the principle of substitutability.

Construction
This is another form of inheritance where the child class may change the behavior defined by
the parent class (overriding). It does not hold the principle of substitutability.

Extension
This is another form of inheritance where the child class may add its new properties. It holds the
principle of substitutability.

Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It does
not hold the principle of substitutability.

Combination
This is another form of inheritance where the subclass inherits properties from multiple parent
classes. Java does not support multiple inheritance type.
UNIT-1
1. What is a class?
2. What is an object?
3. What is Inheritance?
4. What is method binding?
5. What is method overriding?
6. What are Object oriented concepts.
7. Discuss Java buzzwords.
8. What are data types.
9. What is a variable?
10. What is an array?
11. Discuss about operators?
12. What is an Expression.
13. What are control statements.
14. What is a constructor.
15. Discuss about final and super keyword.
16. What is polymorphism?
17. What are the benefits & costs of Inheritance?
18. What are the forms of Inheritance?
19. What is an abstract class
20. What is string handling?
UNIT-1
1. Discuss about A WAY OF VIEWING WORLD in detail.
2. Explain about OOPS concepts.
3. Write about Java Buzzwords. Explain an overview of Java.
4. Discuss in detail about data types, variables and arrays.
5. Explain about operators in detail.
6. Discuss in detail about control statements.
7. What is Inheritance and explain in detail about it.
8. Write different forms of inheritance. What are the benefits and costs of inheritance.
9. What is polymorphism and explain in detail about it.
10. Write in detail about classes, methods and string handling.
Fill in the blanks:

1. Java was developed by GUIDO VAN ROSSUM in 1991.


2. JAVA is a multi-plaform, object- oriented and network centric language.
3. JAVAC & JAVA are two commands used for execution.
4. The extension of a java program is .java .
5. OOP is structured as a community of interacting objects called Objects.
6. Behaviors of an object is described in terms of responsibilities.
7. Objects are instance of a class.
8. Inheritance will inherits the properties of parent class to child class.
9. Polymorphism is the process of defining same method with different implementation.
10. Method overloading is multiple methods with same name but different parameters.
11. Method overriding is multiple methods with same name and same parameters.
12. Abstraction is hiding the internal details and showing only essential functionality.
13. Data type is a category of data stored in variables.
14. Primitive data types are built in data types.
15. Non-primitive data types are the user defined data types.
16. The variables declared inside a method or a block are known as Local Variables.
17. The variables declared inside a class and outside any method,constructor or block are known as
Global Variables.
18. A static variable is a variable that declared using static keyword.
19. The Final variable is initialized only once & does not allow any method to change its value again.
20. An array is a collection of similar data values with a single name.
21. An operator is a symbol used to perform arithmetic & logical operations.
22. An expression is a collection of operators & operands that represents a specific value.
23. A method is a block of statements under a name that gets executes only when it is called.
24. A constructor is a special method of a class that has the same name as the class name.
25. The expression in which the operator is used between operands is called INFIX expression.
26. The expression in which the operator is used after operands is called POSTFIX expression.
27. The expression in which the operator is used before operands is called PREFIX expression.
28. Selection statements are also known as decision making statements.
29. Iterative statements are used to execute a statement of block of statements repeatedly as long
as the given condition is true.
30. Jump statements are used to transfer execution control from one line to another line.
In java, a package is a container of classes, interfaces, and sub-packages. We may think of it as
a folder in a file directory.
We use the packages to avoid naming conflicts and to organize project-related classes,
interfaces, and sub-packages into a bundle.
In java, the packages have divided into two types.

 Built-in Packages
 User-defined Packages

Built-in Packages
The built-in packages are the packages from java API. The Java API is a library of pre-defined
classes, interfaces, and sub-packages. The built-in packages were included in the JDK.
There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax,
swing, net, sql, etc.
We need to import the built-in packages to use them in our program. To import a package, we
use the import statement.

User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their
own packages.

Definig a Package in java


We use the package keyword to create or define a package in java programming language.

NOTE:

 The package statement must be the first statement in the program.


 The package name must be a single word.
 The package name must use Camel case notation.

Let's consider the following code to create a user-defined package myPackage.


Now, save the above code in a file DefiningPackage.java, and compile it using the following
command.
javac -d . DefiningPackage.java
The above command creates a directory with the package name myPackage, and
the DefiningPackage.class is saved into it.
Run the program use the following command.
java myPackage.DefiningPackage

NOTE:
When we use IDE like Eclipse, Netbeans, etc. the package structure is created automatically.
In java, the access modifiers define the accessibility of the class and its members. For example,
private members are accessible within the same class members only. Java has four access
modifiers, and they are default, private, protected, and public.
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The
class acts as a container of data and methods. So, the access modifier decides the accessibility
of class members across the different packages.
In java, the accessibility of the members of a class or interface depends on its access specifiers.
The following table provides information about the visibility of both data members and methods.

NOTE:
 The public members can be accessed everywhere.
 The private members can be accessed only inside the same class.
 The protected members are accessible to every child class (same package or other
packages).
 The default members are accessible within the same package but not outside the
package.
Let's look at the following example java code.

class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

class ChildClass extends ParentClass{

void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}

}
public class AccessModifiersExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();
obj.accessData();

}
In java, the import keyword used to import built-in and user-defined packages. When a package
has imported, we can refer to all the classes of that package using their name directly.
The import statement must be after the package statement, and before any other statement.
Using an import statement, we may import a specific class or all the classes from a package.
NOTE:

 Using one import statement, we may import only one package or a class.
 Using an import statement, we can not import a class directly, but it must be a part of a
package.
 A program may contain any number of import statements.

Importing specific class


Using an importing statement, we can import a specific class. The following syntax is employed
to import a specific class.

Syntax
import packageName.ClassName;

Let's look at an import statement to import a built-in package and Scanner class.

Example
package myPackage;

import java.util.Scanner;

public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);


}
}

In the above code, the class ImportingExample belongs to myPackage package, and it also
importing all the classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from
the java.util package.
🔔 The import statement imports only classes of the package, but not sub-packages and its
classes.
🔔 We may also import sub-packages by using a symbol '.' (dot) to separate parent package and
sub-package.

Consider the following import statement.

import java.util.*;

The above import statement util is a sub-package of java package. It imports all the classes
of util package only, but not classes of java package.
In java, an interface is similar to a class, but it contains abstract methods and static final
variables only. The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the
interface has an implementation, and all the variables in the interface are constants.
All the methods of an interface, implemented by the class that implements it.
The interface in java enables java to support multiple-inheritance. An interface may extend only
one interface, but a class may implement any number of interfaces.

NOTE:

 An interface is a container of abstract methods and static final variables.


 An interface, implemented by a class. (class implements interface).
 An interface may extend another interface. (Interface extends Interface).
 An interface never implements another interface, or class.
 A class may implement any number of interfaces.
 We can not instantiate an interface.
 Specifying the keyword abstract for interface methods is optional, it automatically added.
 All the members of an interface are public by default.

Defining an interface in java


Defining an interface is similar to that of a class. We use the keyword interface to define an
interface. All the members of an interface are public by default. The following is the syntax for
defining an interface.

Syntax
interface InterfaceName{
...
members declaration;
...
}

Let's look at an example code to define an interface.

Example
interface HumanInterfaceExample {
void work();

int duration = 10;

In the above code defines an interface HumanInterfaceExample that contains two abstract
methods learn(), work() and one constant duration.
Every interface in Java is auto-completed by the compiler. For example, in the above example
code, no member is defined as public, but all are public automatically.
The above code automatically converted as follows.

Converted code
interface HumanInterfaceExample {

public abstract void learn(String str);


public abstract void work();

public static final int duration = 10;

}
In java, an interface is implemented by a class. The class that implements an interface must
provide code for all the methods defined in the interface, otherwise, it must be defined as an
abstract class.
The class uses a keyword implements to implement an interface. A class can implement any
number of interfaces. When a class wants to implement more than one interface, we use
the implements keyword is followed by a comma-separated list of the interfaces implemented
by the class.
The following is the syntax for defining a class that implements an interface.

Syntax
class className implements InterfaceName{
...
boby-of-the-class
...
}

Let's look at an example code to define a class that implements an interface.

Example
interface Human {

void learn(String str);


void work();

int duration = 10;

class Programmer implements Human{


public void learn(String str) {
System.out.println("Learn using " + str);
}
public void work() {
System.out.println("Develop applications");
}
}

public class HumanTest {

public static void main(String[] args) {


Programmer trainee = new Programmer();
trainee.learn("coding");
trainee.work();
}
}

In the above code defines an interface Human that contains two abstract methods learn(),
work() and one constant duration. The class Programmer implements the interface. As it
implementing the Human interface it must provide the body of all the methods those defined in
the Human interface.

Implementing multiple Interfaces


When a class wants to implement more than one interface, we use the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class.
The following is the syntax for defineing a class that implements multiple interfaces.

Syntax
class className implements InterfaceName1, InterfaceName2, ...{
...
boby-of-the-class
...
}

Let's look at an example code to define a class that implements multiple interfaces.

Example
interface Human {
void learn(String str);
}
interface Recruitment {
boolean screening(int score);
boolean interview(boolean selected);
}
class Programmer implements Human, Recruitment {
public void learn(String str) {
System.out.println("Learn using " + str);
}
public boolean screening(int score) {
System.out.println("Attend screening test");
int thresold = 20;
if(score > thresold)
return true;
return false;
}
public boolean interview(boolean selected) {
System.out.println("Attend interview");
if(selected)
return true;
return false;
}
public void work() {
System.out.println("Develop applications");
}
}
public class HumanTest {
public static void main(String[] args) {
Programmer trainee = new Programmer();
trainee.learn("Coding");
trainee.screening(30);
trainee.interview(true);
}
}

In the above code defines two interfaces Human and Recruitment, and a class Programmer
implements both the interfaces.
In java, an interface may be defined inside another interface, and also inside a class. The
interface that defined inside another interface or a class is konwn as nested interface. The
nested interface is also refered as inner interface.
🔔 The nested interface declared within an interface is public by default.
🔔 The nested interface declared within a class can be with any access modifier.
🔔 Every nested interface is static by default.

The nested interface cannot be accessed directly. We can only access the nested interface by
using outer interface or outer class name followed by dot( . ), followed by the nested interface
name.

Nested interface inside another interface


The nested interface that defined inside another interface must be accessed
as OuterInterface.InnerInterface.
Let's look at an example code to illustrate nested interfaces inside another interface.

Example
interface OuterInterface{
void outerMethod();

interface InnerInterface{
void innerMethod();
}
}

class OnlyOuter implements OuterInterface{


public void outerMethod() {
System.out.println("This is OuterInterface method");
}
}

class OnlyInner implements OuterInterface.InnerInterface{


public void innerMethod() {
System.out.println("This is InnerInterface method");
}

public class NestedInterfaceExample {

public static void main(String[] args) {


OnlyOuter obj_1 = new OnlyOuter();
OnlyInner obj_2 = new OnlyInner();

obj_1.outerMethod();
obj_2.innerMethod();
}

Nested interface inside a class


The nested interface that defined inside a class must be accessed
as ClassName.InnerInterface.
Let's look at an example code to illustrate nested interfaces inside a class.

Example
class OuterClass{

interface InnerInterface{
void innerMethod();
}
}

class ImplementingClass implements OuterClass.InnerInterface{


public void innerMethod() {
System.out.println("This is InnerInterface method");
}
}
public class NestedInterfaceExample {

public static void main(String[] args) {


ImplementingClass obj = new ImplementingClass();

obj.innerMethod();
}

}
In java, an interface is a completely abstract class. An interface is a container of abstract
methods and static final variables. The interface contains the static final variables. The variables
defined in an interface can not be modified by the class that implements the interface, but it may
use as it defined in the interface.
🔔 The variable in an interface is public, static, and final by default.
🔔 If any variable in an interface is defined without public, static, and final keywords then, the
compiler automatically adds the same.
🔔 No access modifier is allowed except the public for interface variables.
🔔 Every variable of an interface must be initialized in the interface itself.
🔔 The class that implements an interface can not modify the interface variable, but it may use
as it defined in the interface.

Let's look at an example code to illustrate variables in an interface.

Example
interface SampleInterface{

int UPPER_LIMIT = 100;

//int LOWER_LIMIT; // Error - must be initialised

public class InterfaceVariablesExample implements SampleInterface{

public static void main(String[] args) {

System.out.println("UPPER LIMIT = " + UPPER_LIMIT);

// UPPER_LIMIT = 150; // Can not be modified


}

}
In java, an interface can extend another interface. When an interface wants to extend another
interface, it uses the keyword extends. The interface that extends another interface has its own
members and all the members defined in its parent interface too. The class which implements a
child interface needs to provide code for the methods defined in both child and parent
interfaces, otherwise, it needs to be defined as abstract class.
🔔 An interface can extend another interface.
🔔 An interface can not extend multiple interfaces.
🔔 An interface can implement neither an interface nor a class.
🔔 The class that implements child interface needs to provide code for all the methods defined in
both child and parent interfaces.

Let's look at an example code to illustrate extending an interface.

Example
interface ParentInterface{
void parentMethod();
}

interface ChildInterface extends ParentInterface{


void childMethod();
}

class ImplementingClass implements ChildInterface{

public void childMethod() {


System.out.println("Child Interface method!!");
}

public void parentMethod() {


System.out.println("Parent Interface mehtod!");
}
}

public class ExtendingAnInterface {


public static void main(String[] args) {

ImplementingClass obj = new ImplementingClass();

obj.childMethod();
obj.parentMethod();

}
STREAMS IN JAVA
In java, the IO operations are performed using the concept of streams. Generally, a stream
means a continuous flow of data. In java, a stream is a logical container of data that allows us to
read from and write to it. A stream can be linked to a data source, or data destination, like a
console, file or network connection by java IO system. The stream-based IO operations are
faster than normal IO operations.
The Stream is defined in the java.io package.
To understand the functionality of java streams, look at the following picture.

In java, the stream-based IO operations are performed using two separate streams input stream
and output stream. The input stream is used for input operations, and the output stream is used
for output operations. The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to the
console.

 System.out: standard output stream for console output operations.


 System.in: standard input stream for console input operations.
 System.err: standard error stream for console error output operations.

The Java streams support many different kinds of data, including simple bytes, primitive data
types, localized characters, and objects.
Java provides two types of streams, and they are as follows.

 Byte Stream
 Character Stream

The following picture shows how streams are categorized, and various built-in classes used by
the java IO system.
Both character and byte streams essentially provides a convenient and efficient way to handle
data streams in Java.
In the next tutorial, we will explore different types of streams in java.

BYTE STREAM
In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8 bits of data.

In Java 1.0 version all IO operations were byte oriented, there was no other stream (character
stream).
The java byte stream is defined by two abstract classes, InputStream and OutputStream. The
InputStream class used for byte stream based input operations, and the OutputStream class
used for byte stream based output operations.
The InputStream and OutputStream classes have several concreate classes to perform various
IO operations based on the byte stream.
The following picture shows the classes used for byte stream operations.
InputStream class
The InputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

S.No. Method with Description

1 int available()

It returns the number of bytes that can be read from the input stream.

2 int read()
It reads the next byte from the input stream.

3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.

4 void close()
It closes the input stream and also frees any resources connected with this input stream.
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.

S.No. Method with Description

1 void write(int n)

It writes byte(contained in an int) to the output stream.

2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.

3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.

4 void close()
It closes the output stream and also frees any resources connected with this output stream.

Reading data using BufferedInputStream


We can use the BufferedInputStream class to read data from the console. The
BufferedInputStream class use a method read( ) to read a value from the console, or file, or
socket.
Let's look at an example code to illustrate reading data using BufferedInputStream.

Example 1 - Reading from console


import java.io.*;

public class ReadingDemo {

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

BufferedInputStream read = new BufferedInputStream(System.in);

try {
System.out.print("Enter any character: ");
System.out.println("You have entered '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
read.close();
}
}

When we run the above program, it produce the following output.


Example 2 - Reading from a file
import java.io.*;

public class ReadingDemo {

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

FileInputStream fileInputStream = new FileInputStream(new


File("C:\\Raja\\dataFile.txt"));
BufferedInputStream input = new
BufferedInputStream(fileInputStream);

try {
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
input.close();
}
}
}

Writing data using BufferedOutputStream


We can use the BufferedOutputStream class to write data into the console, file, socket. The
BufferedOutputStream class use a method write( ) to write data.
Let's look at an example code to illustrate writing data into a file using BufferedOutputStream.

Example - Writing data into a file


import java.io.*;
public class WritingDemo {

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

String data = "Welcome to Department";


BufferedOutputStream out = null;
try {
FileOutputStream fileOutputStream = new
FileOutputStream(new File("C:\\Raja\\dataFile.txt"));
out = new BufferedOutputStream(fileOutputStream);

out.write(data.getBytes());
System.out.println("Writing data into a file is success!");

}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}

CHARACTER STREAM:
In java, when the IO stream manages 16-bit Unicode characters, it is called a character stream.
The unicode set is basically a type of character set where each character corresponds to a
specific numeric value within the given character set, and every programming language has a
character set.
In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.
The character stream was introduced in Java 1.1 version. The charater stream
The java character stream is defined by two abstract classes, Reader and Writer. The Reader
class used for character stream based input operations, and the Writer class used for charater
stream based output operations.
The Reader and Writer classes have several concreate classes to perform various IO
operations based on the character stream.
The following picture shows the classes used for character stream operations.

Reader class
The Reader class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.

S.No. Method with Description

1 int read()

It reads the next character from the input stream.

2 int read(char[] cbuffer)


It reads a chunk of charaters from the input stream and store them in its byte array, cbuffer.

3 int read(char[] cbuf, int off, int len)


It reads charaters into a portion of an array.
S.No. Method with Description

4 int read(CharBuffer target)


It reads charaters into into the specified character buffer.

5 String readLine()
It reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), or a carriage returnfollowed immediately by a linefeed.

6 boolean ready()
It tells whether the stream is ready to be read.

7 void close()
It closes the input stream and also frees any resources connected with this input stream.

Writer class
The Writer class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.

S.No. Method with Description

1 void flush()

It flushes the output steam by forcing out buffered bytes to be written out.

2 void write(char[] cbuf)


It writes a whole array(cbuf) to the output stream.

3 void write(char[] cbuf, int off, int len)


It writes a portion of an array of characters.

4 void write(int c)
It writes single character.

5 void write(String str)


It writes a string.

6 void write(String str, int off, int len)


It writes a portion of a string.

7 Writer append(char c)
It appends the specified character to the writer.
S.No. Method with Description

8 Writer append(CharSequence csq)


It appends the specified character sequence to the writer

9 Writer append(CharSequence csq, int start, int end)


It appends a subsequence of the specified character sequence to the writer.

10 void close()
It closes the output stream and also frees any resources connected with this output stream.

Reading data using BufferedReader


We can use the BufferedReader class to read data from the console. The BufferedInputStream
class needs InputStreamReaderclass. The BufferedReader use a method read( ) to read a
value from the console, or file, or socket.
Let's look at an example code to illustrate reading data using BufferedReader.

Example 1 - Reading from console


import java.io.*;

public class ReadingDemo {

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

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader in = new BufferedReader(isr);

String name = "";

System.out.print("Please enter your name: ");

name = in.readLine();

System.out.println("Hello, " + name + "!");


}
}

Example 2 - Reading from a file


import java.io.*;

public class ReadingDemo {

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

Reader in = new FileReader();

try {
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
input.close();
}
}
}

Writing data using FileWriter


We can use the FileWriter class to write data into the file. The FileWriter class use a method
write( ) to write data.
Let's look at an example code to illustrate writing data into a file using FileWriter.

Example - Writing data into a file


import java.io.*;
public class WritingDemo {

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

Writer out = new FileWriter("C:\\Raja\\dataFile.txt");

String msg = "The sample data";

try {
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
Console IO Operations
Reading console input in java
In java, there are three ways to read console input. Using the 3 following ways, we can read
input data from the console.

 Using BufferedReader class


 Using Scanner class
 Using Console class

Let's explore the each method to read data with example.

1. Reading console input using BufferedReader class in java


Reading input data using the BufferedReader class is the traditional technique. This way of the
reading method is used by wrapping the System.in (standard input stream) in
an InputStreamReader which is wrapped in a BufferedReader, we can read input from the
console.
The BufferedReader class has defined in the java.io package.
Consider the following example code to understand how to read console input using
BufferedReader class.

Example

import java.io.*;

public class ReadingDemo {

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

BufferedReader in = new BufferedReader(new


InputStreamReader(System.in));

String name = "";

try {
System.out.print("Please enter your name : ");
name = in.readLine();
System.out.println("Hello, " + name + "!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
in.close();
}
}
}

2. Reading console input using Scanner class in java


Reading input data using the Scanner class is the most commonly used method. This way of
the reading method is used by wrapping the System.in (standard input stream) which is
wrapped in a Scanner, we can read input from the console.
The Scanner class has defined in the java.util package.
Consider the following example code to understand how to read console input using Scanner
class.

Example

import java.util.Scanner;

public class ReadingDemo {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

String name = "";


System.out.print("Please enter your name : ");
name = in.next();
System.out.println("Hello, " + name + "!");
}
}

3. Reading console input using Console class in java


Reading input data using the Console class is the most commonly used method. This class
was introduced in Java 1.6 version.
The Console class has defined in the java.io package.
Consider the following example code to understand how to read console input using Console
class.

Example

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) {

String name;
Console con = System.console();

if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}

Writing console output in java


In java, there are two methods to write console output. Using the 2 following methods, we can
write output data to the console.
 Using print() and println() methods
 Using write() method

Let's explore the each method to write data with example.

1. Writing console output using print() and println() methods


The PrintStream is a bult-in class that provides two methods print() and println() to write console
output. The print() and println() methods are the most widely used methods for console output.
Both print() and println() methods are used with System.out stream.
The print() method writes console output in the same line. This method can be used with
console output only.
The println() method writes console output in a separete line (new line). This method can be
used with console ans also with other output sources.
Let's look at the following code to illustrate print() and println() methods.

Example

public class WritingDemo {

public static void main(String[] args) {

int[] list = new int[5];

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


list[i] = i*10;

for(int i:list)
System.out.print(i); //prints in same line

System.out.println("");
for(int i:list)
System.out.println(i); //Prints in separate lines

}
}
2. Writing console output using write() method
Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to the
console, it also acept escape sequences.
Let's look at the following code to illustrate write() method.

Example

public class WritingDemo {

public static void main(String[] args) {

int[] list = new int[26];

for(int i = 0; i < 26; i++) {


list[i] = i + 65;
}

for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
}
}
The File is a built-in class in Java. In java, the File class has been defined in
the java.io package. The File class represents a reference to a file or directory. The File class
has various methods to perform operations like creating a file or directory, reading from a file,
updating file content, and deleting a file or directory.
The File class in java has the following constructors.

S.No. Constructor with Description

1 File(String pathname)

It creates a new File instance by converting the givenpathname string into an abstract pathname.
If the given string isthe empty string, then the result is the empty abstract pathname.

2 File(String parent, String child)


It Creates a new File instance from a parent abstractpathname and a child pathname string.
If parent is null then the new File instance is created as if by invoking thesingle-argument
File constructor on the given child pathname string.

3 File(File parent, String child)


It creates a new File instance from a parent abstractpathname and a child pathname string.
If parent is null then the new File instance is created as if by invoking thesingle-argument
File constructor on the given child pathname string.

4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract pathname.

The File class in java has the following methods.

S.No. Methods with Description

1 String getName()

It returns the name of the file or directory that referenced by the current File object.

2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not name a
parent directory.

3 String getPath()
It returns the path of curent File.

4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.
S.No. Methods with Description

5 String getAbsolutePath()
It returns the current file or directory path from the root.

6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.

7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.

8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.

9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.

10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the application; false otherwise.

11 boolean canWrite()
It returns true if and only if the file specified exists and the application is allowed to write to the file;
false otherwise.

12 long length()
It returns the length of the current file.

13 long lastModified()
It returns the time that specifies the file was last modified.

14 boolean createNewFile()
It returns true if the named file does not exist and was successfully created; false if the named
file already exists.

15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or directory is successfully
deleted; false otherwise.

16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the virtual machine terminates.

17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.
S.No. Methods with Description

18 boolean mkdirs()
It returns true if and only if the directory was created, along with all necessary parent
directories; false otherwise.

19 boolean renameTo(File dest)


It renames the current file. And returns true if and only if the renaming succeeded; false otherwise.

20 boolean setLastModified(long time)


It sets the last-modified time of the file or directory. And returns true if and only if the operation
succeeded; false otherwise.

21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and only if the operation
succeeded; false otherwise.

22 String[] list()
It returns an array of strings containing names of all the files and directories
in the current directory.

23 String[] list(FilenameFilter filter)


It returns an array of strings containing names of all the files and directories in the current
directory that satisfy the specified filter.

24 File[] listFiles()
It returns an array of file references containing names of all the files and directories in the
current directory.

25 File[] listFiles(FileFilter filter)


It returns an array of file references containing names of all the files and directories in the
current directory that satisfy the specified filter.

26 boolean equals(Object obj)


It returns true if and only if the argument is not null and is an abstract pathname that
denotes the same file or directory as this abstract pathname.

27 int compareTo(File pathname)


It Compares two abstract pathnames lexicographically. It returns zero if the argument is
equal to this abstract pathname, a value less than zero if this abstract pathname is
lexicographically less than the argument, or a value greater than zero if this abstract
S.No. Methods with Description

pathname is lexicographically greater than the argument.

28 int compareTo(File pathname)


Compares this abstract pathname to another object. Returns zero if the argument is equal
to this abstract pathname, a value less than zero if this abstract pathname is lexicographically
less than the argument, or a value greater than zero if this abstract pathname is lexicographically
greater than the argument.

Let's look at the following code to illustrate file operations.

Example
import java.io.*;
public class FileClassTest {

public static void main(String args[]) {


File f = new File("C:\\Raja\\datFile.txt");

System.out.println("Executable File : " + f.canExecute());


System.out.println("Name of the file : " + f.getName());
System.out.println("Path of the file : " + f.getAbsolutePath());
System.out.println("Parent name : " + f.getParent());
System.out.println("Write mode : " + f.canWrite());
System.out.println("Read mode : " + f.canRead());
System.out.println("Existance : " + f.exists());
System.out.println("Last Modified : " + f.lastModified());
System.out.println("Length : " + f.length());
//f.createNewFile()
//f.delete();
//f.setReadOnly()
}

}
Let's look at the following java code to list all the files in a directory including the files present in
all its subdirectories.

Example
import java.util.Scanner;
import java.io.*;

public class ListingFiles {


public static void main(String[] args) {

String path = null;


Scanner read = new Scanner(System.in);
System.out.print("Enter the root directory name: ");
path = read.next() + ":\\";
File f_ref = new File(path);
if (!f_ref.exists()) {
printLine();
System.out.println("Root directory does not exists!");
printLine();
} else {
String ch = "y";
while (ch.equalsIgnoreCase("y")) {
printFiles(path);
System.out.print("Do you want to open any sub-directory
(Y/N): ");
ch = read.next().toLowerCase();
if (ch.equalsIgnoreCase("y")) {
System.out.print("Enter the sub-directory name:
");
path = path + "\\\\" + read.next();
File f_ref_2 = new File(path);
if (!f_ref_2.exists()) {
printLine();
printLine();
int lastIndex =
path.lastIndexOf("\\");
path = path.substring(0,
lastIndex);
}
}
}
}
System.out.println("***** Program Closed *****");
}

public static void printFiles(String path) {


System.out.println("Current Location: " + path);
File f_ref = new File(path);
File[] filesList = f_ref.listFiles();
for (File file : filesList) {
if (file.isFile())
System.out.println("- " + file.getName());
else
System.out.println("> " + file.getName());
}
}

public static void printLine() {


System.out.println("----------------------------------------");
}
}
In java, there multiple ways to read data from a file and to write data to a file. The most
commonly used ways are as follows.

 Using Byte Stream (FileInputStream and FileOutputStream)


 Using Character Stream (FileReader and FileWriter)

Let's look each of these ways.

File Handling using Byte Stream


In java, we can use a byte stream to handle files. The byte stream has the following
built-in classes to perform various operations on a file.

 FileInputStream - It is a built-in class in java that allows reading data from a file.
This class has implemented based on the byte stream. The FileInputStream
class provides a method read() to read data from a file byte by byte.
 FileOutputStream - It is a built-in class in java that allows writing data to a file.
This class has implemented based on the byte stream. The FileOutputStream
class provides a method write() to write data to a file byte by byte.

Let's look at the following example program that reads data from a file and writes the
same to another file using FileInoutStream and FileOutputStream classes.

Example
import java.io.*;
public class FileReadingTest {

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


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("C:\\Raja\\Input-File.txt");
out = new FileOutputStream("C:\\Raja\\Output-File.txt");

int c;
while ((c = in.read()) != -1) {
}
System.out.println("Reading and Writing has been success!!!");
}
catch(Exception e){
System.out.println(e);
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

File Handling using Character Stream


In java, we can use a character stream to handle files. The character stream has the
following built-in classes to perform various operations on a file.

 FileReader - It is a built-in class in java that allows reading data from a file. This
class has implemented based on the character stream. The FileReader class
provides a method read() to read data from a file character by character.
 FileWriter - It is a built-in class in java that allows writing data to a file. This class
has implemented based on the character stream. The FileWriter class provides a
method write() to write data to a file character by character.

Let's look at the following example program that reads data from a file and writes the
same to another file using FIleReader and FileWriter classes.

Example
import java.io.*;
public class FileIO {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("C:\\Raja\\Input-File.txt");
out = new FileWriter("C:\\Raja\\Output-File.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
System.out.println("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
In java, the java.io package has a built-in class RandomAccessFile that enables a file
to be accessed randomly. The RandomAccessFile class has several methods used to
move the cursor position in a file.
A random access file behaves like a large array of bytes stored in a file.

RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.

S.No
. Constructor with Description

1 RandomAccessFile(File fileName, String mode)

It creates a random access file stream to read from, and optionally to write to, the file specifie
argument.

2 RandomAccessFile(String fileName, String mode)


It creates a random access file stream to read from, and optionally to write to, a file with the s

Access Modes
Using the RandomAccessFile, a file may created in th following modes.

 r - Creates the file with read mode; Calling write methods will result in an
IOException.
 rw - Creates the file with read and write mode.
 rwd - Creates the file with read and write mode - synchronously. All updates to
file content is written to the disk synchronously.
 rws - Creates the file with read and write mode - synchronously. All updates to
file content or meta data is written to the disk synchronously.

RandomAccessFile methods
The RandomAccessFile class in java has the following methods.

S.No
. Methods with Description

1 int read()
S.No
. Methods with Description

It reads byte of data from a file. The byte is returned as an integer in the range 0-255.

2 int read(byte[] b)
It reads byte of data from file upto b.length, -1 if end of file is reached.

3 int read(byte[] b, int offset, int len)


It reads bytes initialising from offset position upto b.length from the buffer.

4 boolean readBoolean()
It reads a boolean value from from the file.

5 byte readByte()
It reads signed eight-bit value from file.

6 char readChar()
It reads a character value from file.

7 double readDouble()
It reads a double value from file.

8 float readFloat()
It reads a float value from file.

9 long readLong()
It reads a long value from file.

10 int readInt()
It reads a integer value from file.

11 void readFully(byte[] b)
It reads bytes initialising from offset position upto b.length from the buffer.

12 void readFully(byte[] b, int offset, int len)


It reads bytes initialising from offset position upto b.length from the buffer.

13 String readUTF()
S.No
. Methods with Description

t reads in a string from the file.

14 void seek(long pos)


It sets the file-pointer(cursor) measured from the beginning of the file, at which the next read

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

16 void write(int b)
It writes the specified byte to the file from the current cursor position.

17 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method in class Float, and then
value to the file as a four-byte quantity, high byte first.

18 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits method in class Doubl
that long value to the file as an eight-byte quantity, high byte first.

Let's look at the following example program.

Example
import java.io.*;

public class RandomAccessFileDemo


{
public static void main(String[] args)
{
try
{
double d = 1.5;
float f = 14.56f;
// Creating a new RandomAccessFile - "F2"
RandomAccessFile f_ref = new RandomAccessFile("C:\\Raja\\
Input-File.txt", "rw");

// Writing to file
f_ref.writeUTF("Hello, Good Morning!");

// File Pointer at index position - 0


f_ref.seek(0);

// read() method :
System.out.println("Use of read() method : " + f_ref.read());

f_ref.seek(0);

byte[] b = {1, 2, 3};

// Use of .read(byte[] b) method :


System.out.println("Use of .read(byte[] b) : " + f_ref.read(b));

// readBoolean() method :
System.out.println("Use of readBoolean() : " +
f_ref.readBoolean());

// readByte() method :
System.out.println("Use of readByte() : " + f_ref.readByte());

f_ref.writeChar('c');
f_ref.seek(0);

// readChar() :
f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);

// read double
System.out.println("Use of readDouble() : " + f_ref.readDouble());

f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);

// readFloat() :
System.out.println("Use of readFloat() : " + f_ref.readFloat());

f_ref.seek(0);
// Create array upto geek.length
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);

String str1 = new String(arr);


System.out.println("Use of readFully() : " + str1);

f_ref.seek(0);

// readFully(byte[] b, int off, int len) :


f_ref.readFully(arr, 0, 8);

String str2 = new String(arr);


System.out.println("Use of readFully(byte[] b, int off, int len) : " +
str2);
}
catch (IOException ex)
{
System.out.println("Something went Wrong");
ex.printStackTrace();
}
}
}
In java, the java.io package has a built-in class Console used to read from and write to
the console, if one exists. This class was added to the Java SE 6. The Console class
implements teh Flushable interface.
In java, most the input functionalities of Console class available through System.in, and
the output functionalities available through System.out.

Console class Constructors


The Console class does not have any constructor. We can obtain the Console class
object by calling System.console().

Console class methods


The Console class in java has the following methods.

S.No
. Methods with Description

1 void flush( )

It causes buffered output to be written physically to the console.

2 String readLine( )
It reads a string value from the keyboard, the input is terminated on pressing enter key.

3 String readLine(String promptingString, Object...args)


It displays the given promptingString, and reads a string fron the keyboard; input is terminated
Enter key.

4 char[ ] readPassword( )
It reads a string value from the keyboard, the string is not displayed; the input is terminated o
key.

5 char[ ] readPassword(String promptingString, Object...args)


It displays the given promptingString, and reads a string value from the keyboard, the string is
the input is terminated on pressing enter key.

6 Console printf(String str, Object....args)


It writes the given string to the console.

7 Console format(String str, Object....args)


S.No
. Methods with Description

It writes the given string to the console.

8 Reader reader( )
It returns a reference to a Reader connected to the console.

9 PrintWriter writer( )
It returns a reference to a Writer connected to the console.

Let's look at the following example program for reading a string using Console class.

Example
import java.io.*;

public class ReadingDemo {

public static void main(String[] args) {

String name;
Console con = System.console();

if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}
Let's look at the following example program for writing to the console using Console
class.

Example
import java.io.*;

public class WritingDemo {

public static void main(String[] args) {

int[] list = new int[26];

for(int i = 0; i < 26; i++) {


list[i] = i + 65;
}

for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
}
}
In java, the Serialization is the process of converting an object into a byte stream so
that it can be stored on to a file, or memory, or a database for future access. The
deserialization is reverse of serialization. The deserialization is the process of
reconstructing the object from the serialized state.
Using serialization and deserialization, we can transfer the Object Code from one Java
Virtual machine to another.

Serialization in Java
In a java programming language, the Serialization is achieved with the help of
interface Serializable. The class whose object needs to be serialized must implement
the Serializable interface.
We use the ObjectOutputStream class to write a serialized object to write to a
destination. The ObjectOutputStream class provides a method writeObject() to
serializing an object.
We use the following steps to serialize an object.

 Step 1 - Define the class whose object needs to be serialized; it must implement
Serializable interface.
 Step 2 - Create a file reference with file path using FileOutputStream class.
 Step 3 - Create reference to ObjectOutputStream object with file reference.
 Step 4 - Use writeObject(object) method by passing the object that wants to be
serialized.
 Step 5 - Close the FileOutputStream and ObjectOutputStream.

Let's look at the following example program for serializing an object.

Example
import java.io.*;

public class SerializationExample {

public static void main(String[] args) {

Student stud = new Student();


stud.studName = "Rama";
stud.studBranch = "IT";
try {
FileOutputStream fos = new
FileOutputStream("my_data.txt");
ObjectOutputStream oos = new
ObjectOutputStream(fos);

oos.writeObject(stud);
oos.close();
fos.close();
System.out.println("The object has been saved to my_data
file!");
}
catch(Exception e) {
System.out.println(e);
}
}
}

Deserialization in Java
In a java programming language, the Deserialization is achieved with the help of
class ObjectInputStream. This class provides a method readObject() to deserializing
an object.
We use the following steps to serialize an object.

 Step 1 - Create a file reference with file path in which serialized object is
available using FileInputStream class.
 Step 2 - Create reference to ObjectInputStream object with file reference.
 Step 3 - Use readObject() method to access serialized object, and typecaste it to
destination type.
 Step 4 - Close the FileInputStream and ObjectInputStream.

Let's look at the following example program for deserializing an object.

Example
import java.io.*;
public class DeserializationExample {

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

try {
FileInputStream fis = new
FileInputStream("my_data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);

Student stud2 = (Student) ois.readObject();


System.out.println("The object has been deserialized.");

fis.close();
ois.close();

System.out.println("Name = " + stud2.studName);


System.out.println("Department = " + stud2.studBranch);
}
catch(Exception e) {
System.out.println(e);
}
}
}
In java, an Enumeration is a list of named constants. The enum concept was
introduced in Java SE 5 version. The enum in Java programming the concept of
enumeration is greatly expanded with lot more new features compared to the other
languages like C, and C++.
In java, the enumeration concept was defined based on the class concept. When we
create an enum in java, it converts into a class type. This concept enables the java
enum to have constructors, methods, and instance variables.
All the constants of an enum are public, static, and final. As they are static, we can
access directly using enum name.
The main objective of enum is to define our own data types in Java, and they are said to
be enumeration data types.

Creating enum in Java


To create enum in Java, we use the keyword enum. The syntax for creating enum is
similar to that of class.
In java, an enum can be defined outside a class, inside a class, but not inside a method.
Let's look at the following example program for creating a basic enum.

Example
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY;
}

public class EnumerationExample {

public static void main(String[] args) {

WeekDay day = WeekDay.FRIDAY;

System.out.println("Today is " + day);

System.out.println("\nAll WeekDays: ");


for(WeekDay d:WeekDay.values())
System.out.println(d);

Every enum is converted to a class that extends the built-in class Enum.
🔔 Every constant of an enum is defined as an object.
🔔 As an enum represents a class, it can have methods, constructors. It also gets a few
extra methods from the Enum class, and one of them is the values() method.

Constructors in Java enum


In a java programming language, an enum can have both the type of constructors
default and parameterized. The execution of constructor depends on the constants we
defined in the enum. For every constant in an enum, the constructor is executed.
If an enum has a parameterized constructor, the parameter value should be passed
when we define constant.
Let's look at the following example program for illustrating constructors in enum.

Example
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");

String msg;

WeekDay(){
System.out.println("Default constructor!");
}

WeekDay(String str){
msg = str;
}
}

public class EnumerationExample {

public static void main(String[] args) {

WeekDay day = WeekDay.SUNDAY;

System.out.println("\nToday is " + day + " and its " + day.msg);

In the above example, the constant SUNDAY is created by calling the parameterized
constructor, other constants created by calling default constructor.

Methods in Java enum


In a java programming language, an enum can have methods. These methods are
similar to the methods of a class. All the methods defined in an enum can be used with
all the constants defined by the same enum.
Let's look at the following example program for illustrating methods in enum.

Example
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");

String msg;
WeekDay(){
System.out.println("Default constructor!");
}

WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
}

void printMessage() {
System.out.println("Today is also " + msg);
}
}

public class EnumerationExample {

public static void main(String[] args) {

WeekDay day = WeekDay.SUNDAY;

System.out.println("\nToday is " + day);


day.printMessage();
}
}

🔔 In java, enum can not extend another enum and a class.


🔔 In java, enum can implement interfaces.
🔔 In java, enum does not allow to create an object of it.
🔔 In java, every enum extends a built-in class Enum by default.
In java, all the primitive data types have defined using the class concept, these classes
known as wrapper classes. In java, every primitive type has its corresponding wrapper
class.
All the wrapper classes in Java were defined in the java.lang package.
The following table shows the primitive type and its corresponding wrapper class.

S.No. Primitive Type Wrapper class

1 byte Byte

2 short Short

3 int Interger

4 long Long

5 float Float

6 double Double

7 char Character

8 boolean Boolean

The Java 1.5 version introduced a concept that converts primitive type to corresponding
wrapper type and reverses of it.

Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding wrapper
class object is called autoboxing or simply boxing. For example, converting an int value
to an Integer class object.
The compiler automatically performs the autoboxing when a primitive type value has
assigned to an object of the corresponding wrapper class.
🔔 We can also perform autoboxing manually using the method valueOf( ), which is
provided by every wrapper class.
Let's look at the following example program for autoboxing.

Example - Autoboxing
import java.lang.*;

public class AutoBoxingExample {

public static void main(String[] args) {

// Auto boxing : primitive to Wrapper


int num = 100;
Integer i = num;
Integer j = Integer.valueOf(num);

System.out.println("num = " + num + ", i = " + i + ", j = " + j);


}
}

Auto un-boxing in Java


In java, the process of converting an object of a wrapper class type to a primitive type
value is called auto un-boxing or simply unboxing. For example, converting an Integer
object to an int value.
The compiler automatically performs the auto un-boxing when a wrapper class object
has assigned to aprimitive type.
🔔 We can also perform auto un-boxing manually using the method intValue( ), which is
provided by Integer wrapper class. Similarly every wrapper class has a method for auto
un-boxing.
Let's look at the following example program for autoboxing.

Example - Auto unboxing


import java.lang.*;

public class AutoUnboxingExample {


public static void main(String[] args) {

// Auto un-boxing : Wrapper to primitive


Integer num = 200;
int i = num;
int j = num.intValue();

System.out.println("num = " + num + ", i = " + i + ", j = " + j);

}
The java generics is a language feature that allows creating methods and class which
can handle any type of data values. The generic programming is a way to write
generalized programs, java supports it by java generics.
The java generics is similar to the templates in the C++ programming language.
🔔 Most of the collection framework classes are generic classes.
🔔 The java generics allows only non-primitive type, it does not support primitive types
like int, float, char, etc.
The java generics feature was introduced in Java 1.5 version. In java, generics used
angular brackets “< >”. In java, the generics feature implemented using the following.

 Generic Method
 Generic Classes

Generic methods in Java


The java generics allows creating generic methods which can work with a different type
of data values.
Using a generic method, we can create a single method that can be called with
arguments of different types. Based on the types of the arguments passed to the
generic method, the compiler handles each method call appropriately.
Let's look at the following example program for generic method.

Example - Generic method


public class GenericFunctions {

public <T, U> void displayData(T value1, U value2) {

System.out.println("(" + value1.getClass().getName() + ", " +


value2.getClass().getName() + ")");
}

public static void main(String[] args) {

GenericFunctions obj = new GenericFunctions();


obj.displayData(10, 10);
obj.displayData("Hi", 'c');
}

In the above example code, the method displayData( ) is a generic method that allows a
different type of parameter values for every function call.

Generic Class in Java


In java, a class can be defined as a generic class that allows creating a class that can
work with different types.
A generic class declaration looks like a non-generic class declaration, except that the
class name is followed by a type parameter section.
Let's look at the following example program for generic class.

Example - Generic class


public class GenericsExample<T> {
T obj;
public GenericsExample(T anotherObj) {
this.obj = anotherObj;
}
public T getData() {
return this.obj;
}

public static void main(String[] args) {

GenericsExample<Integer> actualObj1 = new


GenericsExample<Integer>(100);
System.out.println(actualObj1.getData());
GenericsExample<String> actualObj2 = new
GenericsExample<String>("Java");
System.out.println(actualObj2.getData());

GenericsExample<Float> actualObj3 = new


GenericsExample<Float>(25.9f);
System.out.println(actualObj3.getData());
}
}
1. A package is a container of classes, interfaces, and sub-packages.
2. The built-in packages are the packages from java API.
3. The user-defined packages are the packages created by the user.

4. The package name must use Camel case notation.


5. The access modifiers define the accessibility of the class and its
members.

6. The public members can be accessed everywhere.


7. The private members can be accessed only inside the same class.
8. The protected members are accessible to every child class (same
package or other packages).
9. The default members are accessible within the same package but not
outside the package.
10. The import keyword used to import built-in and user-defined
packages.
11. an interface is similar to a class, but it contains abstract methods
and static final variables only.
12. The class uses a keyword implements to implement an interface.
13. an interface may be defined inside another interface, and also
inside a class is called as Nested Interface
14. The variables defined in an interface can not be modified by the
class that implements the interface, but it may use as it defined in the
interface.
15. When an interface wants to extend another interface, it uses the
keyword extends.
16. In java, the IO operations are performed using the concept of
streams.
17. The File class represents a reference to a file or directory.
18. RandomAccessFile that enables a file to be accessed randomly.
19. Serialization is the process of converting an object into a byte
stream
20. an Enumeration is a list of named constants.
21. the process of converting a primitive type value into its
corresponding wrapper class object is called autoboxing
22. Generics is a language feature that allows creating methods and
class which can handle any type of data values.
1. What is a package?
2. Define an access protection.
3. What is an interface?
4. Write about importing packages.
5. How to implement an interface.
6. How to extend an interface.
7. Define variables in interface.
8. What is stream>
9. What are console IO operations.
10. What is File class.
11. What is Concole class.
12. Define serialization.
13. Define Enumeration.
14. What is Autoboxing?
15. Write about Generics.
CHP-1
EXCEPTION HANDLING
An exception in java programming is an abnormal situation that is araised during the program
execution. In simple words, an exception is a problem that arises at the time of program
execution.
When an exception occurs, it disrupts the program execution flow. When an exception occurs,
the program execution gets terminated, and the system generates an error. We use the
exception handling mechanism to avoid abnormal termination of program execution.
Java programming language has a very powerful and efficient exception handling mechanism
with a large number of built-in classes to handle most of the exceptions automatically.
Java programming language has the following class hierarchy to support the exception handling
mechanism.
Reasons for Exception Occurrence
Several reasons lead to the occurrence of an exception. A few of them are as follows.
 When we try to open a file that does not exist may lead to an exception.
 When the user enters invalid input data, it may lead to an exception.
 When a network connection has lost during the program execution may lead to an
exception.
 When we try to access the memory beyond the allocated range may lead to an
exception.
 The physical device problems may also lead to an exception.
Types of Exception
In java, exceptions have categorized into two types, and they are as follows.
 Checked Exception - An exception that is checked by the compiler at the time of
compilation is called a checked exception.
 Unchecked Exception - An exception that can not be caught by the compiler but
occurrs at the time of program execution is called an unchecked exception.
How exceptions handled in Java?
In java, the exception handling mechanism uses five keywords
namely try, catch, finally, throw, and throws.
CHP-1
EXCEPTION TYPES
In java, exceptions are mainly categorized into two types, and they are as follows.

 Checked Exceptions
 Unchecked Exceptions

Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not
handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.

 IOException
 FileNotFoundException
 ClassNotFoundException
 SQLException
 DataAccessException
 InstantiationException
 UnknownHostException

🔔 In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.

Example - Checked Exceptions


import java.io.*;

public class CheckedExceptions {

public static void main(String[] args) {

File f_ref = new File("C:\\Users\\User\\Desktop\\Today\\Sample.txt");


try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {
System.out.println(e);
}

Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use
of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.

 ArithmeticException
 NullPointerException
 NumberFormatException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException

🔔 In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.

Example - Unchecked Exceptions


public class UncheckedException {

public static void main(String[] args) {

int list[] = {10, 20, 30, 40, 50};

System.out.println(list[6]);
//ArrayIndexOutOfBoundsException
String msg=null;
System.out.println(msg.length()); //NullPointerException

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

Exception class hierarchy


In java, the built-in classes used to handle exceptions have the following class hierarchy.
CHP-1
EXCEPTION MODELS
In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java suports are as follows.

 Termination Model
 Resumptive Model

Let's look into details of each exception model.

Termination Model
In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the
type of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to get
back to where the exception occurred.

Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the exception
handler is expected to do something to stable the situation, and then the faulting method is
retried. In resumptive model we hope to continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior. We may
also place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.
CHP-1
UNCAUGHT EXCEPTIONS
In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints a exception message with the help of
uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us to
handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions. Look at the
following code.

Example
import java.util.Scanner;

public class UncaughtExceptionExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);

}
}
CHP-1
TRY &CATCH EXCEPTION
In java, the try and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
can not use try without atleast one catch, and catch alone can be used (catch without try is not
allowed).
The following is the syntax of try and catch blocks.

Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}

Consider the following example code to illustrate try and catch blocks in Java.

Example
import java.util.Scanner;

public class TryCatchExample {


public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.println("Enter the a and b values: ");
try {
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO");
}
}
}

In the above example code, when an exception occurs in the try block the execution control
transfered to the catch block and the catch block handles it.

Multiple catch clauses


In java programming language, a try block may has one or more number of catch blocks. That
means a single try statement can have multiple catch clauses.
When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.
The multipe catch clauses are defined when the try block contains the code that may lead to
different type of exceptions.
🔔 The try block generates only one exception at a time, and at a time only one catch block is
executed.
🔔 When there are multiple catch blocks, the order of catch blocks must be from the most
specific exception handler to most general.
🔔 The catch block with Exception class handler must be defined at the last.

Let's look at the following example Java code to illustrate multiple catch clauses.

Example
public class TryCatchExample {

public static void main(String[] args) {

try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

Nested try statements


The java allows to write a try statement inside another try statement. A try block within another
try block is known as nested try block.
When there are nested try blocks, each try block must have one or more seperate catch blocks.
Let's look at the following example Java code to illustrate nested try statements.

Example
public class TryCatchExample {
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try {
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

In case of nested try blocks, if an exception occured in the inner try block and it's catch blocks
are unable to handle it then it transfers the control to the outer try's catch block to handle it.
CHP-1
THROW,THROWS AND FINALLY
In java, the keywords throw, throws, and finally are used in the exception handling concept.
Let's look at each of these keywords.

throw keyword in Java


The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.
The throw keyword must be used inside the try blcok. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
🔔 Using throw keyword only object of Throwable class or its sub classes can be thrown.
🔔 Using throw keyword only one exception can be thrown.
🔔 The throw keyword must followed by an throwable instance.

The following is the general syntax for using throw keyword in a try block.

Syntax
throw instance;

Here the instace must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.

Example
import java.util.Scanner;

public class Sample {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);


int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero is not posible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}

throws keyword in Java


The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception
automatically, we use throws keyword followed by method declaration
🔔 When a method throws an exception, we must put the calling statement of method in try-
catch block.

Let's look at the following example Java code to illustrate throws keyword.

Example
import java.util.Scanner;

public class ThrowsExample {

int num1, num2, result;


Scanner input = new Scanner(System.in);

void division() throws ArithmeticException {


System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}

public static void main(String[] args) {

try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}

finally keyword in Java


The finally keyword used to define a block that must be executed irrespective of exception
occurence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
🔔 Only one finally block is allowed for each try block.
🔔 Use of finally block is optional.

Let's look at the following example Java code to illustrate throws keyword.

Example
import java.util.Scanner;

public class FinallyExample {

public static void main(String[] args) {


int num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
finally {
System.out.println("The finally block executes always");
}
System.out.println("End of the program");
}

}
CHP-1
BUILT IN EXCEPTION
The Java programming language has several built-in exception class that support exception
handling. Every exception class is suitable to explain certain error situations at run time.
All the built-in exception classes in Java were defined a package java.lang.
Few built-in exceptions in Java are shown in the following image.

List of checked exceptions in Java


The following table shows the list of several checked exceptions.
S.
No. Exception Class with Description

1 ClassNotFoundException

It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in
the classpath.

2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object, but that the object's class does
not implement the Cloneable interface.

3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers do not allow.

4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance method in class Class , but
the specified class object cannot be instantiated because it is an interface or is an abstract class.

5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.

6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.

7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile time, a NoSuchMethodException
occurs during reflection when we try to access a method that does not exist.

List of unchecked exceptions in Java


The following table shows the list of several unchecked exceptions.

S.
No. Exception Class with Description

1 ArithmeticException

It handles the arithmetic exceptions like dividion by zero

2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The index is either negative or greater than
or equal to the size of the array.

3 ArrayStoreException
S.
No. Exception Class with Description

It handles the situations like when an attempt has been made to store the wrong type of object into an array of objects

4 AssertionError
It is used to indicate that an assertion has failed

5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.

6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or inappropriate argument.

7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has attempted to notify other threads
that wait on an object's monitor, without owning the specified monitor.

8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.

9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify the state of the thread when it is
illegal.

10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an array , vector , string , and so forth.

11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.

12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.

13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer, but the format of the input string is
not appropriate or illegal.

14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.

15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either negative, or greater than the size
of the string itself.

16 UnsupportedOperationException
S.
No. Exception Class with Description

It is thrown to indicate that the requested operation is not supported.


CHP-1
CREATING OWN EXCEPTION
The Java programming language allow us to create our own exception classes which are
basically subclasses built-in class Exception.
To create our own exception class simply create a class as a subclass of built-in Exception
class.
We may create constructor in the user-defined exception class and pass a string to Exception
class constructor using super(). We can use getMessage() method to access the string.
Let's look at the following Java code that illustrates the creation of user-defined exception.

Example
import java.util.Scanner;

class NotEligibleException extends Exception{


NotEligibleException(String msg){
super(msg);
}
}

class VoterList{
int age;
VoterList(int age){
this.age = age;
}

void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under
age.");
}
System.out.println("Congrates! You are eligible for vote.");
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {

Scanner input = new Scanner(System.in);


System.out.println("Enter your age in years: ");
int age = input.nextInt();
VoterList person = new VoterList(age);
person.checkEligibility();
}
}
CHP-2
MULTI-THREADING
The java programming language allows us to create a program that contains one or more parts
that can run simultaneously at the same time. This type of program is known as a multithreading
program. Each part of this program is called a thread. Every thread defines a separate path of
execution in java. A thread is explained in different ways, and a few of them are as specified
below.
A thread is a light wieght process.
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.
In java, multiple threads can run at a time, which enables the java to write multitasking
programs. The multithreading is a specialized form of multitasking. All modern operating
systems support multitasking. There are two types of multitasking, and they are as follows.

 Process-based multitasking
 Thread-based multitasking

It is important to know the difference between process-based and thread-based multitasking.


Let's distinguish both.

Process-based multitasking Thread-based multitasking

It allows the computer to run two or more programs concurrently It allows the computer to run two or more threads concurrently

In this process is the smallest unit. In this thread is the smallest unit.

Process is a larger unit. Thread is a part of process.

Process is heavy weight. Thread is light weight.

Process requires seperate address space for each. Threads share same address space.

Process never gain access over idle time of CPU. Thread gain access over idle time of CPU.

Inter process communication is expensive. Inter thread communication is not expensive.


CHP-2
THREAD MODEL
The java programming language allows us to create a program that contains one or more parts
that can run simultaneously at the same time. This type of program is known as a multithreading
program. Each part of this program is called a thread. Every thread defines a separate path of
execution in java. A thread is explained in different ways, and a few of them are as specified
below.
A thread is a light wieght process.
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.
In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases. A thread may in any of the states like new, ready or runnable,
running, blocked or wait, and dead or terminated state. The life cycle of a thread in java is
shown in the following figure.

Let's look at each phase indetailed.

New
When a thread object is created using new, then the thread is said to be in the New state. This
state is also known as Born state.

Example
Thread t1 = new Thread();

Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This
state is also known as a Ready state.

Example
t1.start( );

Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a
thread called automatically by the start( ) method.

Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like
sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method
called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons
like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called, resume(
) method called, etc.

Example
Thread.sleep(1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();
Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated state.
CHP-2
CREATING THREADS
In java, a thread is a lightweight process. Every java program executes by a thread called the
main thread. When a java program gets executed, the main thread created automatically. All
other threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.

 Using Thread class (by extending Thread class)


 Uisng Runnable interface (by implementing Runnable interface)

Let's see how to create threads using each of the above.

Extending Thread class


The java contains a built-in class Thread inside the java.lang package. The Thread class
contains all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.

 Step-1: Create a class as a child of Thread class. That means, create a class that
extends Thread class.
 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Call the start( ) method on the object created in the above step.

Look at the following example program.

Example
class SampleThread extends Thread{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}
public class My_Thread_Test {

public static void main(String[] args) {


SampleThread t1 = new SampleThread();
System.out.println("Thread about to start...");
t1.start();
}
}

Implementng Runnable interface


The java contains a built-in interface Runnable inside the java.lang package. The Runnable
interface implemented by the Thread class that contains all the methods that are related to the
threads.
To create a thread using Runnable interface, follow the step given below.

 Step-1: Create a class that implements Runnable interface.


 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Create the Thread class object by passing above created object as parameter to
the Thread class constructor.
 Step-5: Call the start( ) method on the Thread class object created in the above step.

Look at the following example program.

Example
class SampleThread implements Runnable{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}
public class My_Thread_Test {

public static void main(String[] args) {


SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
}
}

Method Description Return Value

run( ) Defines actual task of the thread. void

start( ) It moves thre thread from Ready state to Running state by calling run( ) method. void

setName(String) Assigns a name to the thread. void

getName( ) Returns the name of the thread. String

setPriority(int) Assigns priority to the thread. void

getPriority( ) Returns the priority of the thread. int

getId( ) Returns the ID of the thread. long

activeCount() Returns total number of thread under active. int

currentThread( ) Returns the reference of the thread that currently in running state. void

sleep( long ) moves the thread to blocked state till the specified number of milliseconds. void

isAlive( ) Tests if the thread is alive. boolean


Method Description Return Value

yield( ) Tells to the scheduler that the current thread is willing to yield its current use of a processor. void

join( ) Waits for the thread to end. void

More about Thread class


The Thread class in java is a subclass of Object class and it implements Runnable interface.
The Thread class is available inside the java.lang package. The Thread class has the following
syntax.

class Thread extends Object implements Runnable{


...
}

The Thread class has the following consructors.

 Thread( )
 Thread( String threadName )
 Thread( Runnable objectName )
 Thread( Runnable objectName, String threadName )

The Thread classs contains the following methods.

🔔 The Thread class in java also contains methods like stop( ), destroy( ), suspend( ),
and resume( ). But they are depricated.
CHP-2
THREAD PRIORITIES
In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java, the
thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority 10 is
considered as the highest priority. The thread with more priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and they
are listed below.

 MAX_PRIORITY - It has the value 10 and indicates highest priority.


 NORM_PRIORITY - It has the value 5 and indicates normal priority.
 MIN_PRIORITY - It has the value 1 and indicates lowest priority.

🔔 The default priority of any thread is 5 (i.e. NORM_PRIORITY).

setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes an integer
range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.

Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);

getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It does not
takes anyargument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.

Example
String threadName = threadObject.getPriority();
Look at the following example program.

Example
class SampleThread extends Thread{
public void run() {
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " +
Thread.currentThread().getName());
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");

threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);

threadObject1.start();
threadObject2.start();

}
}

In java, it is not guaranteed that threads execute according to their priority because it depends
on JVM specification that which scheduling it chooses.
CHP-2
THREAD SYNCRONIZATION
The java programming language supports multithreading. The problem of shared resources
occurs when two or more threads get execute at the same time. In such a situation, we need
some way to ensure that the shared resource will be accessed by only one thread at a time, and
this is performed by using the concept called synchronization.
🔔 The synchronization is the process of allowing only one thread to access a shared resource
at a time.
In java, the synchronization is achieved using the following concepts.

 Mutual Exclusion
 Inter thread communication

In this tutorial, we discuss mutual exclusion only, and the interthread communication will be
discussed in the next tutorial.

Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another while
they accessing the shared resource. In java, mutual exclusion is achieved using the following
concepts.

 Synchronized method
 Synchronized block

Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it at
a time. When an object calls a synchronized method, it put a lock on that method so that other
objects or thread that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads
will be allocated to the shared resource.
In the above image, initially the thread-1 is accessing the synchronized method and other
threads (thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.

Example
class Table{
synchronized void printTable(int n) {
for(int i = 1; i <= 10; i++)
System.out.println(n + " * " + i + " = " + i*n);
}
}

class MyThread_1 extends Thread{


Table table = new Table();
int number;
MyThread_1(Table table, int number){
this.table = table;
this.number = number;
}
table.printTable(number);
}
}

class MyThread_2 extends Thread{

Table table = new Table();


int number;
MyThread_2(Table table, int number){
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}
public class ThreadSynchronizationExample {

public static void main(String[] args) {


Table table = new Table();
MyThread_1 thread_1 = new MyThread_1(table, 5);
MyThread_2 thread_2 = new MyThread_2(table, 10);
thread_1.start();
thread_2.start();
}
}

Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of lines
in a method. For example, let's consider a method with 20 lines of code where we want to
synchronize only a sequence of 5 lines code, we use the synchronized block.
The folllowing syntax is used to define a synchronized block.

Syntax
synchronized(object){
...
block code
...
}

Look at the following example code to illustrate synchronized block.

Example
import java.util.*;

class NameList {
String name = "";
public int count = 0;

public void addName(String name, List<String> namesList){


synchronized(this){
this.name = name;
count++;
}
namesList.add(name);
}

public int getCount(){


return count;
}
}
public class SynchronizedBlockExample {
public static void main (String[] args)
{
NameList namesList_1 = new NameList();
List<String> list = new ArrayList<String>();
namesList_1.addName("Rama", list);
namesList_2.addName("Seetha", list);
System.out.println("Thread1: " + namesList_1.name + ", " +
namesList_1.getCount() + "\n");
System.out.println("Thread2: " + namesList_2.name + ", " +
namesList_2.getCount() + "\n");
}
}

The complete code of a method may be written inside the synchronized block, where it works
similarly to the synchronized method.
CHP-2
INTER THREAD COMMUNICATION
Inter thread communication is the concept where two or more threads communicate to
solve the problem of polling. In java, polling is the situation to check some condition
repeatedly, to take appropriate action, once the condition is true. That means, in inter-
thread communication, a thread waits until a condition becomes true such that other
threads can execute its task. The inter-thread communication allows the synchronized
threads to communicate with each other.
Java provides the following methods to achieve inter thread communication.

 wait( )
 notify( )
 notifyAll( )

The following table gives detailed description about the above methods.

Method Description

void wait( ) It makes the current thread to pause its execution until other thread in the

same monitor calls notify( )

void notify( ) It wakes up the thread that called wait( ) on the same object.

void notifyAll() It wakes up all the threads that called wait( ) on the same object.

🔔 Calling notify( ) or notifyAll( ) does not actually give up a lock on a resource.


Let's look at an example problem of producer and consumer. The producer produces
the item and the consumer consumes the same. But here, the consumer can not
consume until the producer produces the item, and producer can not produce until the
consumer consumes the item that already been produced. So here, the consumer has
to wait until the producer produces the item, and the producer also needs to wait until
the consumer consumes the same. Here we use the inter-thread communication to
implement the producer and consumer problem.
The sample implementation of producer and consumer problem is as follows.

Example
class ItemQueue {
int item;
boolean valueSet = false;

synchronized int getItem()

{
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" + item);
valueSet = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
return item;
}

synchronized void putItem(int item) {


while (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
this.item = item;
valueSet = true;
System.out.println("Produced: " + item);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
}
}

class Producer implements Runnable{


ItemQueue itemQueue;
Producer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
itemQueue.putItem(i++);
}
}
}
class Consumer implements Runnable{

ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
}
public void run() {
while(true) {
itemQueue.getItem();
}
}
}

class ProducerConsumer{
public static void main(String args[]) {
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);

}
}

All the methods wait( ), notify( ), and notifyAll( ) can be used only inside the synchronized
methods only.
FILL IN THE BLANKS:

1. An Exception is an abnormal situation that is araised during the program execution.


2. When an exception occurs, the program execution gets terminated.

3. An exception that is checked by the compiler at the time of compilation is called a


checked exception.
4. An exception that can not be caught by the compiler but occurrs at the time of
program execution is called an unchecked exception.
5. the exception handling mechanism uses five keywords
namely try, catch, finally, throw, and throws.
6. In the termination model, when a method encounters an exception, further
processing in that method is terminated.
7. In resumptive model, the exception handler is expected to do something to stable the
situation, and then the faulting method is retried.
8. The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
9. The keyword try is used to define a block of code that will be tests the occurence of
an exception.
10. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
11. The throw keyword is used to throw an exception instance explicitly from a try block
to corresponding catch block.
12. The throws keyword specifies the exceptions that a method can throw to the default
handler and does not handle itself.
13. The finally keyword used to define a block that must be executed irrespective of
exception occurence.
14. All the built-in exception classes in Java were defined in a package java.lang.
15. Java allow us to create our own exception classes which are basically subclasses
built-in class Exception.
16. Thread is a subpart of a process that can run individually.
17. When a thread object is created using new, then the thread is said to be in the New
state.
18. When a thread calls start( ) method, then the thread is said to be in the Runnable
state.
19. When a thread calls run( ) method, then the thread is said to be Running.
20. We can create thread by extending thread class and by implementing Runnable
interface.
21. Thread class provides two methods setPriority(int), and getPriority( ) to handle
thread priorities.
22. The synchronization is the process of allowing only one thread to access a shared
resource at a time.
23. Inter thread communication is the concept where two or more threads
communicate to solve the problem of polling.
UNIT-3
SHORT QUESTIONS
1.What is an exception?
2. What are the types of exception?
3.What is termination or resumptive model?
4. What is uncaught exception?
5.What are the statements used for handling exception?
6. What is multi catch clause?
7.Write about nested try statements.
8. What is throw, throws and finally.
9.List out built-in exceptions.
10. What is user defined exception ?
11. What is multi threading?
12. List out few differences between thread based multi tasking
and process based multitasking.
13.Write a thread model.
14. How to create a thread?
15. Write about thread prioirities.
16. How to synchronize threads.
17. What is inter thread communication?

LONG QUESTIONS:
1. Explain in detail about Exceptions.
2. Explain in detail about Multithreading.
3. Explain in detail about how exceptions are handled.
4. Write about built-in exceptions in detail.
5. Explain about the models of exception and the types of
exceptions.
6. Write about the statements which are used to handle an
exception.
7. Explain about nested try statement and multi catch
statement.
8. Explain in detail about synchronization in thread .
9. What is Inter thread communication.Explain in detail
about it.
10. What is thread?Explain in detail about thread model
and how to create a threads.
1. COLLECTION FRAMEWORK
Java collection framework is a collection of interfaces and classes used to
storing and processing a group of individual objects as a single unit. The java
collection framework holds several classes that provide a large number of
methods to store and process a group of objects. These classes make the
programmer task super easy and fast.
Java collection framework was introduced in java 1.2 version.
Java collection framework has the following heirarchy.
Before the collection framework in java (before java 1.2 version), there was a
set of classes like Array, Vector, Stack, HashTable. These classes are
known as legacy classes.
The java collection framework contains List, Queue, Set, and Map as top-level
interfaces. The List, Queue, and Set stores single value as its element,
whereas Map stores a pair of a key and value as its element.
2.COLLECTION INTERFACE
The Collection interface is the root interface for most of the interfaces and
classes of collection framework. The Collection interface is available inside
the java.util package. It defines the methods that are commonly used by
almost all the collections.
The Collection interface defines the following methods.

🔔 The Collection interface extends Iterable interface.


Let's consider an example program on ArrayList to illustrate the methods of
Collection interface.

Example
import java.util.*;
public class CollectionInterfaceExample {

public static void main(String[] args) {

List list_1 = new ArrayList();


List<String> list_2 = new ArrayList<String>();

list_1.add(10);
list_1.add(20);
list_2.add("HELLO");
list_2.add("EVERYONE");
list_2.add("WELCOME ");

list_1.addAll(list_2);
System.out.println("Elements of list_1: " + list_1);

System.out.println("Search for HELLO: " +


list_1.contains("HELLO"));
System.out.println("Search for list_2 in list_1: " +
list_1.containsAll(list_2));

System.out.println("Check whether list_1 and list_2 are equal:


" + list_1.equals(list_2));

System.out.println("Check is list_1 empty: " +


list_1.isEmpty());

System.out.println("Size of list_1: " + list_1.size());


System.out.println("Hashcode of list_1: " +
list_1.hashCode());

list_1.remove(0);
System.out.println(list_1);

list_1.retainAll(list_2);
System.out.println(list_1);

list_1.removeAll(list_2);
System.out.println(list_1);

list_2.clear();
System.out.println(list_2);
}
}
3.ARRAYLIST
The ArrayList class is a part of java collection framework. It is available inside
the java.util package. The ArrayList class extends AbstractList class and
implements List interface.
The elements of ArrayList are organized as an array internally. The default
size of an ArrayList is 10.
The ArrayList class is used to create a dynamic array that can grow or shrunk
as needed.
🔔 The ArrayList is a child class of AbstractList
🔔 The ArrayList implements interfaces like List, Serializable, Cloneable,
and RandomAccess.
🔔 The ArrayList allows to store duplicate data values.
🔔 The ArrayList allows to access elements randomly using index-based
accessing.
🔔 The ArrayList maintains the order of insertion.

ArrayList class declaration


The ArrayList class has the following declaration.

Example
public class ArrayList<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable

ArrayList class constructors


The ArrayList class has the following constructors.

 ArrayList( ) - Creates an empty ArrayList.


 ArrayList(Collection c) - Creates an ArrayList with given collection of
elements.
 ArrayList(int size) - Creates an empty ArrayList with given size
(capacity).
Operations on ArrayList
The ArrayList class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.

Adding Items
The ArrayList class has the following methods to add items.

 boolean add(E element) - Appends given element to the ArrayList.


 boolean addAll(Collection c) - Appends given collection of elements to
the ArrayList.
 void add(int index, E element) - Inserts the given element at specified
index.
 boolean addAll(int index, Collection c) - Inserts the given collection of
elements at specified index.

Let's consider an example program to illustrate adding items to the ArrayList.

Example
import java.util.*;
public class ArrayListExample {

public static void main(String[] args) {

ArrayList<String> list_1 = new ArrayList<String>();


ArrayList list_2 = new ArrayList();

//Appending
list_1.add("HELLO");
System.out.println("list_1: " + list_1);
list_1.add("WORLD");
System.out.println("list_1: " + list_1);
//Inserting at specified index
list_1.add(1, "HIII");
System.out.println("list_1: " + list_1);

//Appending a collection of elements


list_2.addAll(list_1);
System.out.println("list_2: " + list_2);

//Inserting collection of elements at specified index


list_2.addAll(2, list_1);
System.out.println("list_2: " + list_2);
}
}

Accessing Items
The ArrayList class has the following methods to access items.

 E get(int index) - Returns element at specified index from the ArrayList.


 ArrayList subList(int startIndex, int lastIndex) - Returns an ArrayList
that contails elements from specified startIndex to lastIndex-1 from the
invoking ArrayList.
 int indexOf(E element) - Returns the index value of given element first
occurence in the ArrayList.
 int lastIndexOf(E element) - Returns the index value of given element
last occurence in the ArrayList.

Let's consider an example program to illustrate accessing items from the


ArrayList.

Example
import java.util.*;
public static void main(String[] args) {

ArrayList<String> list_1 = new ArrayList<String>();

list_1.add("HELLO");
list_1.add("EVERY");
list_1.add("ONE");
list_1.add("WELCOME");
list_1.add("TO");
list_1.add("CS/IOT");
list_1.add("DEPARTMENT");

System.out.println("Element at index 4 is " +


list_1.get(4));
System.out.println("Sublist from index 1 to 4: " +
list_1.subList(1, 5));
System.out.println("Index of element \"Class\" is " +
list_1.indexOf("ONE"));
System.out.println("Last index of element \"Class\" is " +
list_1.lastIndexOf("ONE"));

}
}

Updating Items
The ArrayList class has the following methods to update or change items.

 E set(int index, E newElement) - Replace the element at specified


index with newElement in the invoking ArrayList.
 ArrayList replaceAll(UnaryOperator e) - Replaces each element of
invoking ArrayList with the result of applying the operator to that
element.

Let's consider an example program to illustrate updating items in the


ArrayList.

Example
import java.util.*;
public class ArrayListExample {

public static void main(String[] args) {

ArrayList<String> list_1 = new ArrayList<String>();

list_1.add("HELLO");
list_1.add("EVERY");
list_1.add("ONE");
list_1.add("WELCOME");
list_1.add("TO");
list_1.add("CS/IOT");
list_1.add("DEPARTMENT");

System.out.println("\nList before update: " + list_1);

list_1.set(3, ":");
System.out.println("\nList after update: " + list_1);

list_1.replaceAll(e -> e.toUpperCase());


System.out.println("\nList after update: " + list_1);
}
}

Removing Items
The ArrayList class has the following methods to remove items.

 E remove(int index) - Removes the element at specified index in the


invoking ArrayList.
 boolean remove(Object element) - Removes the first occurence of the
given element from the invoking ArrayList.
 boolean removeAll(Collection c) - Removes the given collection of
elements from the invoking ArrayList.
 void retainAll(Collection c) - Removes all the elements except the
given collection of elements from the invoking ArrayList.
 boolean removeIf(Predicate filter) - Removes all the elements from
the ArrayList that satisfies the given predicate.
 void clear( ) - Removes all the elements from the ArrayList.

Let's consider an example program to illustrate removing items from the


ArrayList.

Example
import java.util.*;
public class ArrayListExample {

public static void main(String[] args) {

ArrayList<String> list_1 = new ArrayList<String>();


ArrayList list_2 = new ArrayList();
ArrayList list_3 = new ArrayList();

list_1.add("HELLO");
list_1.add("ONE");
list_1.add("WELCOME");
list_1.add("TO");
list_1.add("CS/IOT");
list_1.add("DEPARTMENT");
list_1.add("on");
list_1.add("Collection");
list_1.add("framwork");
list_1.add("-");
list_1.add("ArrayList");

list_2.add("HELLO");
list_2.add("WORLD");

list_3.add("JAVA");
list_3.add("PROGRAMMING");
list_3.add("LANGUAGE");

System.out.println("\nList_1 before remove:\n" + list_1);


System.out.println("\nList_2 before remove:\n" + list_2);
System.out.println("\nList_3 before remove:\n" + list_3);

list_1.remove(3);
System.out.println("\nList after removing element from index
3:\n" + list_1);

list_1.remove("WORLD");
System.out.println("\nList after removing \'Tutorial\' element:\
n" + list_1);

list_1.removeAll(list_2);
System.out.println("\nList after removing all elements of list_2
from list_1:\n" + list_1);

list_1.removeIf(n -> n.equals("LANGUAGE"));


System.out.println("\nList after removing all elements that are
equal to \'Classes\':\n" + list_1);

list_1.retainAll(list_3);
System.out.println("\nList after removing all elements from
list_1 except elements of list_3:\n" + list_1);

list_1.clear();
System.out.println("\nList after removing all elements from
list_1:\n" + list_1);

}
}

Other utility methods


The ArrayList class has the following methods to work with elements of it.

 int size( ) - Returns the total number of elements in the invoking


ArrayList.
 boolean isEmpty( ) - Returns true if the list is empty otherwise returns
false.
 boolean contains(Object element) - Returns true if the list contains
given element otherwise returns false.
 void sort(Comparator c) - Sorts all the elements of invoking list based
on the given comparator.
 List[ ] subList(int startIndex, int endIndex) - Returns list of elements
starting from startIndex to endIndex-1.
 Object clone( ) - Returns a shallow copy of an ArrayList.
 Object[ ] toArray( ) - Returns an array of Object instances that contains
all the elements from invoking ArrayList.
 Spliterator spliterator( ) - Creates spliterator over the elements in a
list.
 void trimToSize( ) - Used to trim a ArrayList instance to the number of
elements it contains.

Let's consider an example program to illustrate other utility methods of the


ArrayList.

Example
import java.util.*;
public class ArrayListExample {

public static void main(String[] args) {

ArrayList list = new ArrayList(20);


Random number = new Random();

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


list.add(number.nextInt(100));

System.out.println("\nList before remove:\n" + list);

System.out.println("\nList size: " + list.size());


System.out.println("\nList contains 10: " +
list.contains(10));

System.out.println("\nSublist from index 2 to 6: " +


list.subList(2, 7) + "\n");

Spliterator nums = list.spliterator();


nums.forEachRemaining((n) -> System.out.print(n + ", "));

Object[] objs = list.toArray();


System.out.println("\n");
for(Object obj:objs)
System.out.print(obj + ", ");

Object anotherList = new ArrayList();

anotherList = list.clone();
System.out.println("\n\nClonned object elements:\n" +
anotherList);

list.sort(null); // from ArrayList class


Collections.sort(list); // from Collections class
System.out.println("\n\nList_1 in sorted order:\n" + list);

list.trimToSize();

}
}
Consolidated list of methods
The following table providess a consolidated view of all methods of ArrayList.

Method Description

boolean add(E element) Appends given element to the ArrayList.

boolean addAll(Collection c) Appends given collection of elements to the Arra

void add(int index, E element) Inserts the given element at specified index.

boolean addAll(int index, Collection c) Inserts the given collection of elements at specifi

E get(int index) Returns element at specified index from the Arra

ArrayList subList(int startIndex, int lastIndex) Returns an ArrayList that contails elements from

specified startIndex to lastIndex-1 from the invok

ArrayList.

int indexOf(E element) Returns the index value of given element first occ

in the ArrayList.

int lastIndexOf(E element) Returns the index value of given element last occ

in the ArrayList.

E set(int index, E newElement) Replace the element at specified index with


Method Description

newElement in the invoking ArrayList.

ArrayList replaceAll(UnaryOperator e) Replaces each element of invoking ArrayList with

result of applying the operator to that element.

E remove(int index) Removes the element at specified index in the

invoking ArrayList.

boolean remove(Object element) Removes the first occurence of the given elemen

from the invoking ArrayList.

boolean removeAll(Collection c) Removes the given collection of elements from th

invoking ArrayList.

void retainAll(Collection c) Removes all the elements except the given

collection of elements from the invoking ArrayLis

boolean removeIf(Predicate filter) Removes all the elements from the ArrayList that

satisfies the given predicate.

void clear( ) Removes all the elements from the ArrayList.

int size( ) Returns the total number of elements in the invok


Method Description

ArrayList.

boolean isEmpty( ) Returns true if the list is empty otherwise returns

boolean contains(Object element) Returns true if the list contains given element oth

returns false.

void sort(Comparator c) Sorts all the elements of invoking list based on th

comparator.

List[ ] subList(int startIndex, int endIndex) Returns list of elements starting from startIndex t

endIndex-1.

Object clone( ) Returns a shallow copy of an ArrayList.

Object[ ] toArray( ) Returns an array of Object instances that contain

all the elements from invoking ArrayList.

Spliterator spliterator( ) Creates spliterator over the elements in a list.

void trimToSize( ) Used to trim a ArrayList instance to the number

of elements it contains.
4.LINKED LIST
The LinkedList class is a part of java collection framework. It is available
inside the java.util package. The LinkedList class
extends AbstractSequentialList class and implements List and Deque interface.
The elements of LinkedList are organized as the elements of linked list data
structure.
The LinkedList class is used to create a dynamic list of elements that can
grow or shrunk as needed.
🔔 The LinkedList is a child class of AbstractSequentialList
🔔 The LinkedList implements interfaces like List, Deque, Cloneable,
and Serializable.
🔔 The LinkedList allows to store duplicate data values.
🔔 The LinkedList maintains the order of insertion.

LinkedList class declaration


The LinkedList class has the following declaration.

Example
public class LinkedList<E> extends AbstractSequentialList<E> implements
List<E>, Deque<E>, Cloneable, Serializable

LinkedList class constructors


The LinkedList class has the following constructors.

 LinkedList( ) - Creates an empty List.


 LinkedList(Collection c) - Creates a List with given collection of
elements.

Operations on LinkedList
The LinkedList class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.

Adding Items
The LinkedList class has the following methods to add items.

 boolean add(E element) - Appends given element to the List.


 boolean addAll(Collection c) - Appends given collection of elements to
the List.
 void add(int position, E element) - Inserts the given element at specified
position.
 boolean addAll(int position, Collection c) - Inserts the given collection of
elements at specified position.
 void addFirst(E element) - Inserts the given element at beggining of the
list.
 void addLast(E element) - Inserts the given element at end of the list.
 boolean offer(E element) - Inserts the given element at end of the list.
 boolean offerFirst(E element) - Inserts the given element at beggining of
the list.
 boolean offerLast(E element) - Inserts the given element at end of the list.
 void push(E element) - Inserts the given element at beggining of the list.

Let's consider an example program to illustrate adding items to the LinkedList.

Example
import java.util.*;

public class LinkedListExample {

public static void main(String[] args) {

LinkedList<String> list_1 = new LinkedList<String>();


LinkedList list_2 = new LinkedList();
list_2.add(10);
list_2.add(20);
list_2.addFirst(5);
list_2.addLast(25);
list_2.offer(2);
list_2.offerFirst(1);
list_2.offerLast(10);
list_2.push(40);

list_1.addAll(list_2);

System.out.println("List_1: " + list_1);

System.out.println("List_2: " + list_2);

Accessing Items
The LinkedList class has the following methods to access items.

 E get(int position) - Returns element at specified position from the


LinkedList.
 E element( ) - Returns the first element from the invoking LinkedList.
 E getFirst( ) - Returns the first element from the invoking LinkedList.
 E getLast( ) - Returns the last element from the invoking LinkedList.
 E peek( ) - Returns the first element from the invoking LinkedList.
 E peekFirst( ) - Returns the first element from the invoking LinkedList,
and returns null if list is empty.
 E peekLast( ) - Returns the last element from the invoking LinkedList,
and returns null if list is empty.
 int indexOf(E element) - Returns the index value of given element first
occurence in the LinkedList.
 int lastIndexOf(E element) - Returns the index value of given element
last occurence in the LinkedList.
 E pop( ) - Returns the first element from the invoking LinkedList.

Let's consider an example program to illustrate accessing items from the


LinkedList.

Example
import java.util.*;

public class LinkedListExample {

public static void main(String[] args) {

LinkedList list_1 = new LinkedList();

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


list_1.add(i);

System.out.println("List is " + list_1 + "\n");

System.out.println("get(position) - " + list_1.get(3));


System.out.println("getFirst() - " + list_1.getFirst());
System.out.println("getLast() - " + list_1.getLast());
System.out.println("element() - " + list_1.element());
System.out.println("peek() - " + list_1.peek());
System.out.println("peekFirst() - " + list_1.peekFirst());
System.out.println("peekLast() - " + list_1.peekLast());
System.out.println("pop() - " + list_1.pop());
System.out.println("indexOf(element) - " +
list_1.indexOf(5));
System.out.println("lastIndexOf(element) - " +
list_1.lastIndexOf(5));

Updating Items
The LinkedList class has the following methods to update or change items.

 E set(int index, E newElement) - Replace the element at specified


index with newElement in the invoking LinkedList.

Let's consider an example program to illustrate updating items in the


LinkedList.

Example
import java.util.*;

public class LinkedListExample {

public static void main(String[] args) {

LinkedList list_1 = new LinkedList();

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


list_1.add(i);
list_1.set(3, 50);

System.out.println("List after update at index 3 is\n" +


list_1 + "\n");

Removing Items
The LinkedList class has the following methods to remove items.

 E remove( ) - Removes the first element from the invoking LinkedList.


 E remove(int index) - Removes the element at specified index in the
invoking LinkedList.
 boolean remove(Object element) - Removes the first occurrence of
the given element from the invoking LinkedList.
 E removeFirst( ) - Removes the first element from the invoking
LinkedList.
 E removeLast( ) - Removes the last element from the invoking
LinkedList.
 boolean removeFirstOccurrence(Object element) - Removes from
the first occurrence of the given element from the invoking LinkedList.
 boolean removeLastOccurrence(Object element) - Removes from
the last occurrence of the given element from the invoking LinkedList.
 E poll( ) - Removes the first element from the LinkedList, and returns
null if the list is empty.
 E pollFirst( ) - Removes the first element from the LinkedList, and
returns null if the list is empty.
 E pollLast( ) - Removes the last element from the LinkedList, and
returns null if the list is empty.
 E pop( ) - Removes the first element from the LinkedList.
 void clear( ) - Removes all the elements from the LinkedList.
Let's consider an example program to illustrate removing items from the
LinkedList.

Example
import java.util.*;

public class LinkedListExample {

public static void main(String[] args) {

LinkedList list_1 = new LinkedList();

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


list_1.add(i);

System.out.println("List initially is " + list_1);

list_1.remove();
System.out.println("\nList after remove()\n" + list_1);

list_1.remove(3);
System.out.println("\nList after remove(index)\n" + list_1);

list_1.removeFirst();
System.out.println("\nList after removeFirst()\n" + list_1);

list_1.removeLast();
System.out.println("\nList after removeLast()\n" + list_1);
System.out.println("\nList after removeFirstOccurrence()\n" +
list_1);

list_1.removeLastOccurrence(7);
System.out.println("\nList after removeLastOccurrence()\n" +
list_1);

list_1.pop();
System.out.println("\nList after pop()\n" + list_1);

list_1.clear();
System.out.println("\nList after clear()\n" + list_1);
}
}

Other utility methods


The LinkedList class has the following methods to work with elements of it.

 int size( ) - Returns the total number of elements in the invoking


LinkedList.
 boolean isEmpty( ) - Returns true if the list is empty otherwise returns
false.
 boolean contains(Object element) - Returns true if the list contains
given element otherwise returns false.
 void sort(Comparator c) - Sorts all the elements of invoking list based
on the given comparator.
 List[ ] subList(int startIndex, int endIndex) - Returns list of elements
starting from startIndex to endIndex-1.
 Object clone( ) - Returns a shallow copy of an LinkedList.
 Object[ ] toArray( ) - Returns an array of Object instances that contains
all the elements from invoking LinkedList.
 Spliterator spliterator( ) - Creates spliterator over the elements in a
list.
 void trimToSize( ) - Used to trim a LinkedList instance to the number of
elements it contains.
Let's consider an example program to illustrate other utility methods of the
LinkedList.

Example
import java.util.*;

public class LinkedListExample {

public static void main(String[] args) {

LinkedList list_1 = new LinkedList();

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


list_1.add(i);

System.out.println("List initially is " + list_1);

System.out.println("Size() - " + list_1.size());

System.out.println("isEmpty() - " + list_1.isEmpty());

System.out.println("contains(4) - " + list_1.contains(4));

System.out.println("subList(start, end-1) - " +


list_1.subList(2, 6));
}
}

Consolidated list of methods


The following table providess a consolidated view of all methods of LinkedList.
Method Description

boolean add(E element) Appends given element to the List.

boolean addAll(Collection c) Appends given collection of elements

to the List.

void add(int index, E element) Inserts the given element at specified index.

boolean addAll(int index, Collection c) Inserts the given collection of elements at

specified index.

void addFirst(E element) Inserts the given element at beggining of

the list.

void addLast(E element) Inserts the given element at end of the list.

boolean offer(E element) Inserts the given element at end of the list.

boolean offerFirst(E element) Inserts the given element at beggining

of the list.

boolean offerLast(E element) Inserts the given element at end of the list.

void push(E element) Inserts the given element at beggining of the


Method Description

E get(int index) Returns element at specified index from the

E getFirst( ) Returns the first element from the list.

E getLast( ) Returns the last element from the list.

E element( ) Returns the first element from the list.

E peek( ) Returns the first element from the list.

E peekFirst( ) Returns the first element from the invoking

LinkedList, and returns null if list is empty.

E peekLast( ) Returns the last element from the invoking

LinkedList, and returns null if list is empty.

int indexOf(E element) Returns the index value of given element

first occurence in the list.

int lastIndexOf(E element) Returns the index value of given element

last occurence in the list.

E set(int index, E newElement) Replace the element at specified index


Method Description

with newElement in the invoking list.

E remove() Removes the first element from the

invoking list.

E remove(int index) Removes the element at specified index

in the invoking list.

boolean remove(Object element) Removes the first occurence of the

given element from the invoking list.

boolean removeAll(Collection c) Removes the given collection of elements

from the invoking LinkedList.

E removeFirst() Removes the first element from the invoking

list.

E removeLast() Removes the first element from the invoking

E removeFirstOccurrence(Object element) Removes from the first occurrence of the

given element from the invoking LinkedList.

E removeLastOccurrence(Object element) Removes from the last occurrence of the


Method Description

given element from the invoking LinkedList.

E poll( ) Removes the first element from the

LinkedList, and returns null if the list is empt

E pollFirst( ) Removes the first element from the

LinkedList, and returns null if the list is empty

E pollLast( ) Removes the last element from the

LinkedList, and returns null if the list is empty

E pop( ) Removes the first element from the

LinkedList.

void clear( ) Removes all the elements from the

LinkedList.

int size( ) Returns the total number of elements in the

invoking LinkedList.

boolean isEmpty( ) Returns true if the list is empty otherwise

returns false.
Method Description

boolean contains(Object element) Returns true if the list contains given

element otherwise returns false.

void sort(Comparator c) Sorts all the elements of invoking list

based on the given comparator.

List[ ] subList(int startIndex, int endIndex) Returns list of elements starting from

startIndex to endIndex-1.

Object clone( ) Returns a shallow copy of an LinkedList.

Object[ ] toArray( ) Returns an array of Object instances

that contains all the elements from

invoking LinkedList.

Spliterator spliterator( ) Creates spliterator over the elements in a

list.

void trimToSize( ) Used to trim a LinkedList instance to the num


5.HASH SET
The HashSet class is a part of java collection framework. It is available inside
the java.util package. The HashSet class extends AbstractSet class and
implements Set interface.
The elements of HashSet are organized using a mechanism called hashing.
The HashSet is used to create hash table for storing set of elements.
The HashSet class is used to create a collection that uses a hash table for
storing set of elements.
🔔 The HashSet is a child class of AbstractSet
🔔 The HashSet implements interfaces like Set, Cloneable, and Serializable.
🔔 The HashSet does not allows to store duplicate data values, but null values
are allowed.
🔔 The HashSet does not maintains the order of insertion.
🔔 The HashSet initial capacity is 16 elements.
🔔 The HashSet is best suitable for search operations.

HashSet class declaration


The HashSet class has the following declaration.

Example
public class HashSet<E> extends AbstractSet<E> implements Set<E>,
Cloneable, Serializable

HashSet class constructors


The HashSet class has the following constructors.

 HashSet( ) - Creates an empty HashSet with the default initial capacity


(16).
 HashSet(Collection c) - Creates a HashSet with given collection of
elements.
 HashSet(int initialCapacity) - Creates an empty HashSet with the
specified initial capacity.
 HashSet(int initialCapacity, float loadFactor) - Creates an empty HashSet
with the specified initial capacity and loadFactor.

Operations on HashSet
The HashSet class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.

Adding Items
The HashSet class has the following methods to add items.

 boolean add(E element) - Inserts given element to the HashSet.


 boolean addAll(Collection c) - Inserts given collection of elements to the
HashSet.

Let's consider an example program to illustrate adding items to the HashSet.

Example
import java.util.*;

public class HashSetExample {

public static void main(String[] args) {

HashSet set = new HashSet();


HashSet anotherSet = new HashSet();

set.add(10);
set.add(20);
set.add(30);
set.add(50);

System.out.println("\nHashSet is\n" + set);

anotherSet.addAll(set);

System.out.println("\nanotherSet is\n" + anotherSet);

Accessing Items
The HashSet class has no methods to access items, we can access whole set
using its name.

Updating Items
The HashSet class has no methods to update or change items.

Removing Items
The HashSet class has the following methods to remove items.

 boolean remove(Object o) - Removes the specified element from the


invoking HashSet.
 boolean removeAll(Collection c) - Removes all the elements of specified
collection from the invoking HashSet.
 boolean removeIf(Predicate p) - Removes all of the elements of HashSet
collection that satisfy the given predicate.
 boolean retainAll(Collection c) - Removes all of the elements of HashSet
collection except specified collection of elements.
 void clear( ) - Removes all the elements from the HashSet.

Let's consider an example program to illustrate removing items from the


HashSet.

Example
import java.util.*;

public class HashSetExample {

public static void main(String[] args) {

HashSet set = new HashSet();


HashSet anotherSet = new HashSet();

set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);

System.out.println("\nHashSet is\n" + set);

anotherSet.addAll(set);

System.out.println("\nanotherSet is\n" + anotherSet);

set.remove(20);
anotherSet.removeAll(set);
System.out.println("\nanotherSet after removeAll(set) is\n" +
anotherSet);

set.retainAll(anotherSet);
System.out.println("\nset after retainAll(anotherSet) is\n" +
set);

anotherSet.clear();
System.out.println("\nanotherSet after clear() is\n" +
anotherSet);

Other utility methods


The HashSet class has the following methods to work with elements of it.

 int size( ) - Returns the total number of elements in the invoking


HashSet.
 boolean isEmpty( ) - Returns true if the HashSet is empty otherwise
returns false.
 HashSet clone( ) - Returns a copy of the invoking HashSet.
 boolean contains(Object element) - Returns true if the HashSet contains
given element otherwise returns false.
 boolean containsAll(Collection c) - Returns true if the HashSet contains
given collection of elements otherwise returns false.
 boolean equals(Object o) - Compares the specified object with invoking
HashSet collection for equality.
 int hashCode( ) - Returns the hash code of the invoking HashSet.
 Object[ ] toArray( ) - Returns an array of Object instances that contains
all the elements from invoking HashSet.
 Spliterator spliterator( ) - Creates spliterator over the elements in a
HashSet.
 Iterator iterator( ) - Returns an iterator over the elements in the HashSet.
The iterator does not return the elements in any particular order.

Let's consider an example program to illustrate other utility methods of the


HashSet.

Example
import java.util.*;

public class HashSetExample {

public static void main(String[] args) {

HashSet set = new HashSet();

set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);

System.out.println("\nHashSet is\n" + set);

System.out.println("\nsize() - " + set.size());

System.out.println("\nisEmpty() - " + set.isEmpty());


System.out.println("\nequals(30) - " + set.equals(30));

System.out.println("\nhashCode() - " + set.hashCode());

Consolidated list of methods


The following table providess a consolidated view of all methods of HashSet.

Method Description

boolean add(E element) Appends given element to the HashSet.

boolean addAll(Collection c) Appends given collection of elements to the HashSet.

boolean remove(Object Removes the first occurence of the given element from th
element)

boolean removeAll(Collection Removes all the elements those are in the specified colle
c) HashSet.

boolean removeIf(Predicate Removes all of the elements of the HashSet collection tha
p)

boolean retainAll(Collection c) Removes all the elements except those are in the specifie
invoking HashSet.
Method Description

void clear( ) Removes all the elements from the HashSet.

int size( ) Returns the total number of elements in the invoking Has

boolean isEmpty( ) Returns true if the HashSet is empty otherwise returns fal

boolean equals( ) Compares the specified object with invoking HashSet coll

boolean contains(Object Returns true if the HashSet contains given element otherw
element)

boolean Returns true if the HashSet contains all elements of given


containsAll(Collection c) false.

int clone( ) Returns a copy of the invoking HashSet.

int hashCode( ) Returns the hash code of the invoking HashSet.

Object[ ] toArray( ) Returns an array of Object instances that contains all the
HashSet.

Spliterator spliterator( ) Creates spliterator over the elements in a HashSet.

Iterator iterator( ) Returns an iterator over the elements in the HashSet. The
elements in any particular order.
6.TREE SET
The TreeSet class is a part of java collection framework. It is available inside
the java.util package. The TreeSet class extends AbstractSet class and
implements NavigableSet, Cloneable, and Serializable interfaces.
The elements of TreeSet are organized using a mechanism called tree. The
TreeSet class internally uses a TreeMap to store elements. The elements in a
TreeSet are sorted according to their natural ordering.
🔔 The TreeSet is a child class of AbstractSet
🔔 The TreeSet implements interfaces like NavigableSet, Cloneable,
and Serializable.
🔔 The TreeSet does not allows to store duplicate data values, but null values
are allowed.
🔔 The elements in a TreeSet are sorted according to their natural ordering.
🔔 The TreeSet initial capacity is 16 elements.
🔔 The TreeSet is best suitable for search operations.

TreeSet class declaration


The TreeSet class has the following declaration.

Examplesorting order
public class TreeSet<E> extends AbstractSet<E> implements
NavigableSet<E>, Cloneable, Serializable

TreeSet class constructors


The TreeSet class has the following constructors.

 TreeSet( ) - Creates an empty TreeSet in which elements will get stored


in default natural sorting order.
 TreeSet(Collection c) - Creates a TreeSet with given collection of
elements.
 TreeSet(Comparator c) - Creates an empty TreeSet with the specified
sorting order.
 TreeSet(SortedSet s) - This constructor is used to convert SortedSet to
TreeSet.

Operations on TreeSet
The TreeSet class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.

Adding Items
The TreeSet class has the following methods to add items.

 boolean add(E element) - Inserts given element to the TreeSet if it does


not exist.
 boolean addAll(Collection c) - Inserts given collection of elements to the
TreeSet.

Let's consider an example program to illustrate adding items to the TreeSet.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {

TreeSet set = new TreeSet();


TreeSet anotherSet = new TreeSet();

set.add(10);
set.add(20);
set.add(15);
set.add(5);

System.out.println("\nset is\n" + set);

anotherSet.addAll(set);

System.out.println("\nanotherSet is\n" + anotherSet);

Accessing Items
The TreeSet class has provides the following methods to access items.

 E First( ) - Returns the first (smallest) element from the invoking


TreeSet.
 E last( ) - Returns the last (largest) element from the invoking TreeSet.
 E higher(E obj) - Returns the largest element e such that e>obj. If it does
not found returns null.
 E lower(E obj) - Returns the largest element e such that e<obj. If it does
not found returns null.
 E ceiling(E obj) - Returns the smallest element e such that e>=obj. If it
does not found returns null.
 E floor(E obj) - Returns the largest element e such that e<=obj. If it does
not found returns null.
 SortedSet subSet(E fromElement, E toElement) - Returns a set of
elements that lie between the given range which includes fromElement
and excludes toElement.
 NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement,
boolean toInclusive) - Returns a set of elements that lie between the
given range from the invoking TreeSet.
 SortedSet tailSet(E fromElement) - Returns a set of elements that are
greater than or equal to the specified fromElement from the invoking
TreeSet.
 NavigableSet tailSet(E fromElement, boolean inclusive) - Returns a set of
elements that are greater than or equal to (if, inclusive is true) the
specified element from the invoking TreeSet.
 SortedSet headSet(E fromElement) - Returns a set of elements that are
smaller than or equal to the specified fromElement from the invoking
TreeSet.
 NavigableSet headSet(E fromElement, boolean inclusive) - Returns a set
of elements that are smaller than or equal to (if, inclusive is true) the
specified element from the invoking TreeSet.

Let's consider an example program to illustrate accessing items from a


TreeSet.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {

TreeSet set = new TreeSet();


Random num = new Random();
for(int i = 0; i < 10; i++)
set.add(num.nextInt(100));

System.out.println("\nset is\n" + set);

System.out.println("\nfirst() - " + set.first());

System.out.println("\nlast() - " + set.last());


System.out.println("\nhigher(20) - " + set.higher(20));

System.out.println("\nlower(20) - " + set.lower(20));

System.out.println("\nceiling(30) - " + set.ceiling(30));

System.out.println("\nfloor(30) - " + set.floor(30));

System.out.println("\nsubSet(10, 50)\n" + set.subSet(10,


50));

System.out.println("\nsubSet(10, false, 50, true)\n" +


set.subSet(10, false, 50, true));

System.out.println("\nheadSet(20)\n" + set.headSet(20));

System.out.println("\nheadSet(20, false)\n" +
set.headSet(20, false));

System.out.println("\ntailSet(20)\n" + set.tailSet(20));

System.out.println("\ntailSet(20, false)\n" + set.tailSet(20,


false));
}
}

Updating Items
The TreeSet class has no methods to update or change items.
Removing Items
The TreeSet class has the following methods to remove items.

 boolean remove(Object o) - Removes the specified element from the


invoking TreeSet.
 boolean removeAll(Collection c) - Removes all the elements those are in
the specified collection from the invoking TreeSet.
 boolean removeIf(Predicate p) - Removes all of the elements of the
TreeSet collection that satisfy the given predicate.
 boolean retainAll(Collection c) - Removes all the elements except those
are in the specified collection from the invoking TreeSet.
 E pollFirst( ) - Removes the first (smallest) element from the invoking
TreeSet, and returns the same.
 E pollLast( ) - Removes the last (largest) element from the invoking
TreeSet, and returns the same.
 void clear( ) - Removes all the elements from the TreeSet.

Let's consider an example program to illustrate removing items from the


TreeSet.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {

TreeSet set = new TreeSet();


TreeSet anotherSet = new TreeSet();
Random num = new Random();
for(int i = 0; i < 10; i++)
set.add(num.nextInt(100));
anotherSet.add(20);
anotherSet.add(30);

System.out.println("\nset is\n" + set);


System.out.println("\nanotherSet is\n" + anotherSet);

set.remove(50);
System.out.println("\nset after remove(50) is\n" + set);

set.removeIf(n->n.equals(60));
System.out.println("\nset after removeIf(n->n.equals(60)) is\n"
+ set);

set.pollFirst();
System.out.println("\nset after pollFirst( ) is\n" + set);

set.pollLast();
System.out.println("\nset after pollLast( ) is\n" + set);

set.removeAll(anotherSet);
System.out.println("\nset after removeAll(anotherSet) is\n" +
set);

set.retainAll(anotherSet);
System.out.println("\nset after retainAll(anotherSet) is\n" +
set);
}
}
Other utility methods
The TreeSet class has the following methods to work with elements of it.

 int size( ) - Returns the total number of elements in the invoking TreeSet.
 boolean isEmpty( ) - Returns true if the TreeSet is empty otherwise
returns false.
 TreeSet clone( ) - Returns a copy of the invoking TreeSet.
 boolean contains(Object element) - Returns true if the TreeSet contains
given element otherwise returns false.
 boolean containsAll(Collection c) - Returns true if the TreeSet contains
given collection of elements otherwise returns false.
 boolean equals(Object o) - Compares the specified object with invoking
TreeSet collection for equality.
 int hashCode( ) - Returns the hash code of the invoking TreeSet.
 Object clone( ) - Returns a shallow copy of invoking TreeSet instance.
 Spliterator spliterator( ) - Creates spliterator over the elements in a
TreeSet.
 Iterator iterator( ) - Returns an iterator over the elements in the TreeSet.
The iterator does not return the elements in any particular order.

Let's consider an example program to illustrate other utility methods of the


TreeSet.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {

TreeSet set = new TreeSet();


TreeSet anotherSet = new TreeSet();
Random num = new Random();
for(int i = 0; i < 10; i++)
anotherSet.add(10);
anotherSet.add(20);
anotherSet.add(30);

System.out.println("\nset is\n" + set);


System.out.println("\nanotherSet is\n" + anotherSet);

System.out.println("\nset size() - " + set.size());

System.out.println("\nset isEmpty() - " + set.isEmpty());

System.out.println("\nset contains(50) - " +


set.contains(50));

System.out.println("\nset contains(anotherSet) - " +


set.containsAll(anotherSet));

System.out.println("\nset equals(anotherSet) - " +


set.equals(anotherSet));

System.out.println("\nset hashCode() - " + set.hashCode());

}
}

Consolidated list of methods


The following table providess a consolidated view of all methods of TreeSet.
Method Description

boolean add(E element) Appends given element to the TreeSet.

boolean addAll(Collection c) Appends given collection of elements

to the TreeSet.

E First( ) Returns the first (smallest) element from

the invoking TreeSet.

E last( ) Returns the last (largest) element from

the invoking TreeSet.

E higher(E obj) Returns the largest element e such that

e>obj. If it does not found returns null.

E lower(E obj) Returns the largest element e such

that e<obj. If it does not found returns null.

E ceiling(E obj) Returns the smallest element e such

that e>=obj. If it does not found returns null

E floor(E obj) Returns the largest element e such

that e<=obj. If it does not found returns null


Method Description

SortedSet subSet(E fromElement, E toElement) Returns a set of elements that lie between

the given range which includes fromElemen

and excludes toElement.

NavigableSet subSet(E fromElement, boolean Returns a set of elements that lie between
fromInclusive, E toElement, boolean toInclusive)
the given range from the invoking TreeSet.

SortedSet tailSet(E fromElement) Returns a set of elements that are greater

than or equal to the specified fromElement

from the invoking TreeSet.

NavigableSet tailSet(E fromElement, boolean inclusive) Returns a set of elements that are greater

than or equal to (if, inclusive is true) the

specified element from the invoking TreeSet

SortedSet headSet(E fromElement) Returns a set of elements that are smaller

than or equal to the specified fromElement

from the invoking TreeSet.

NavigableSet headSet(E fromElement, boolean Returns a set of elements that are smaller
inclusive)
than or equal to (if, inclusive is true) the
Method Description

specified element from the invoking

TreeSet.

boolean remove(Object element) Removes the first occurence of the given

element from the invoking TreeSet.

boolean removeAll(Collection c) Removes all the elements those are in

the specified collection from the invoking

TreeSet.

boolean removeIf(Predicate p) Removes all of the elements of the

TreeSet collection that satisfy the given

predicate.

boolean retainAll(Collection c) Removes all the elements except those

are in the specified collection from the

invoking TreeSet.

void clear( ) Removes all the elements from the TreeSet

int size( ) Returns the total number of elements in


Method Description

the invoking TreeSet.

boolean isEmpty( ) Returns true if the TreeSet is empty

otherwise returns false.

boolean equals( ) Compares the specified object with

invoking TreeSet collection for equality.

boolean contains(Object element) Returns true if the HashSet contains

given element otherwise returns false.

boolean containsAll(Collection c) Returns true if the TreeSet contains all

elements of given collection otherwise

returns false.

int clone( ) Returns a copy of the invoking TreeSet.

int hashCode( ) Returns the hash code of the

invoking TreeSet.

Spliterator spliterator( ) Creates spliterator over the elements in a

TreeSet.
Method Description

Iterator iterator( ) Returns an iterator over the

elements in the TreeSet. The iterator


does not return the elements in any

particular order.
PRIORITY QUEUE
The PriorityQueue class is a part of java collection framework. It is available
inside the java.util package. The PriorityQueue class
extends AbstractQueue class and implements Serializable interface.
The elements of PriorityQueue are organized as the elements of queue data
structure, but it does not follow FIFO principle. The PriorityQueue elements
are organized based on the priority heap.
The PriorityQueue class is used to create a dynamic queue of elements that
can grow or shrunk as needed.
🔔 The PriorityQueue is a child class of AbstractQueue
🔔 The PriorityQueue implements interface Serializable.
🔔 The PriorityQueue allows to store duplicate data values, but not null values.
🔔 The PriorityQueue maintains the order of insertion.
🔔 The PriorityQueue used priority heap to organize its elements.

PriorityQueue class declaration


The PriorityQueue class has the following declaration.

Example
public class PriorityQueue<E> extends AbstractQueue<E> implements
Serializable

PriorityQueue class constructors


The PriorityQueue class has the following constructors.

 PriorityQueue( ) - Creates an empty PriorityQueue with the default initial


capacity (11) that orders its elements according to their natural ordering.
 PriorityQueue(Collection c) - Creates a PriorityQueue with given
collection of elements.
 PriorityQueue(int initialCapacity) - Creates an empty PriorityQueue with
the specified initial capacity.
 PriorityQueue(int initialCapacity, Comparator comparator) - Creates an
empty PriorityQueue with the specified initial capacity that orders its
elements according to the specified comparator.
 PriorityQueue(PriorityQueue pq) - Creates a PriorityQueue with the
elements in the specified priority queue.
 PriorityQueue(SortedSet ss) - Creates a PriorityQueue with the elements
in the specified SortedSet.

Operations on PriorityQueue
The PriorityQueue class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.

Adding Items
The PriorityQueue class has the following methods to add items.

 boolean add(E element) - Appends given element to the PriorityQueue.


 boolean addAll(Collection c) - Appends given collection of elements to
the PriorityQueue.
 boolean offer(E element) - Appends given element to the PriorityQueue.

Let's consider an example program to illustrate adding items to the


PriorityQueue.

Example
import java.util.*;

public class PriorityQueueExample {

public static void main(String[] args) {

PriorityQueue queue = new PriorityQueue();


PriorityQueue anotherQueue = new PriorityQueue();
queue.add(10);
queue.add(20);
queue.add(15);

System.out.println("\nQueue is " + queue);

anotherQueue.addAll(queue);

System.out.println("\nanotherQueue is " + anotherQueue);

anotherQueue.offer(25);

System.out.println("\nanotherQueue is " + anotherQueue);

Accessing Items
The PriorityQueue class has the following methods to access items.

 E element( ) - Returns the first element from the invoking PriorityQueue.


 E peek( ) - Returns the first element from the invoking PriorityQueue,
returns null if this queue is empty.

Let's consider an example program to illustrate accessing items from the


PriorityQueue.

Example
import java.util.*;

public class PriorityQueueExample {

public static void main(String[] args) {

PriorityQueue queue = new PriorityQueue();

queue.add(10);
queue.add(20);
queue.add(15);

System.out.println("\nQueue is " + queue);

System.out.println("\nelement() - " + queue.element());

System.out.println("\npeek() - " + queue.peek());

Updating Items
The PriorityQueue class has no methods to update or change items.

Removing Items
The PriorityQueue class has the following methods to remove items.
 E remove( ) - Removes the first element from the invoking PriorityQueue.
 boolean remove(Object element) - Removes the first occurrence of the
given element from the invoking PriorityQueue.
 boolean removeAll(Collection c) - Removes all the elements of specified
collection from the invoking PriorityQueue.
 boolean removeIf(Predicate p) - Removes all of the elements of this
collection that satisfy the given predicate.
 boolean retainAll(Collection c) - Removes all the elements except those
are in the specified collection from the invoking PriorityQueue.
 E poll( ) - Removes the first element from the PriorityQueue, and returns
null if the list is empty.
 void clear( ) - Removes all the elements from the PriorityQueue.

Let's consider an example program to illustrate removing items from the


PriorityQueue.

Example
import java.util.*;

public class PriorityQueueExample {

public static void main(String[] args) {

PriorityQueue queue = new PriorityQueue();


PriorityQueue anotherQueue = new PriorityQueue();

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


queue.add(i);
anotherQueue.add(5);
anotherQueue.add(7);
anotherQueue.add(8);
System.out.println("\nQueue initially is\n" + queue);
queue.remove();
System.out.println("\nQueue after remove() is\n" + queue);

queue.remove(8);
System.out.println("\nQueue after remove(8) is\n" + queue);

queue.poll();
System.out.println("\nQueue after poll() is\n" + queue);

queue.removeIf(n->n.equals(6));
System.out.println("\nQueue after removeIf(n->n.equals(6) is\
n" + queue);

queue.retainAll(anotherQueue);
System.out.println("\nQueue after retainAll(anotherQueue) is\
n" + queue);

queue.removeAll(anotherQueue);
System.out.println("\nQueue after removeAll(anotherQueue)
is\n" + queue);

queue.clear();
System.out.println("\nQueue after clear() is\n" + queue);
}
}

Other utility methods


The PriorityQueue class has the following methods to work with elements of it.
 int size( ) - Returns the total number of elements in the invoking
PriorityQueue.
 boolean isEmpty( ) - Returns true if the list is empty otherwise returns
false.
 boolean contains(Object element) - Returns true if the list contains given
element otherwise returns false.
 Object[ ] toArray( ) - Returns an array of Object instances that contains
all the elements from invoking LinkedList.
 Spliterator spliterator( ) - Creates spliterator over the elements in a list.
 void trimToSize( ) - Used to trim a LinkedList instance to the number of
elements it contains.
 Iterator iterator( ) - Returns an iterator over the elements in the
PriorityQueue. The iterator does not return the elements in any
particular order.

Let's consider an example program to illustrate other utility methods of the


PriorityQueue.

Example
import java.util.*;

public class PriorityQueueExample {

public static void main(String[] args) {

PriorityQueue queue = new PriorityQueue();

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


queue.add(i);

System.out.println("\nQueue initially is\n" + queue);

System.out.println("\nsize() - " + queue.size());


System.out.println("\nisEmpty() - " + queue.isEmpty());

System.out.println("\ncontains(3) - " + queue.contains(3));


}
}

Consolidated list of methods


The following table providess a consolidated view of all methods of
PriorityQueue.

Method Description

boolean add(E element) Appends given element to the PriorityQueue.

boolean addAll(Collection c) Appends given collection of elements to the

PriorityQueue.

boolean offer(E element) Inserts the given element at end of the PriorityQueue.

E element( ) Returns the first element from the PriorityQueue.

E peek( ) Returns the first element from the PriorityQueue.

E remove() Removes the first element from the invoking


Method Description

PriorityQueue.

boolean remove(Object element) Removes the first occurence of the given element

from the invoking PriorityQueue.

boolean removeAll(Collection c) Removes the given collection of elements from the

invoking PriorityQueue.

boolean removeIf(Predicate p) Removes all of the elements of this collection that

satisfy the given predicate.

boolean retainAll(Collection c) Removes all the elements except those are in the

specified collection from the invoking PriorityQueue.

E poll( ) Removes the first element from the PriorityQueue,

and returns null if the PriorityQueue is empty.

void clear( ) Removes all the elements from the PriorityQueue.

int size( ) Returns the total number of elements in the invoking

PriorityQueue.

boolean isEmpty( ) Returns true if the PriorityQueue is empty otherwise


Method Description

returns false.

boolean contains(Object element) Returns true if the PriorityQueue contains given

element otherwise returns false.

Object[ ] toArray( ) Returns an array of Object instances that contains

all

the elements from invoking PriorityQueue.

Spliterator spliterator( ) Creates spliterator over the elements in a

PriorityQueue.

void trimToSize( ) Used to trim a PriorityQueue instance to the number

of elements it contains.
ARRAY DEQUE
The ArrayDeque class is a part of java collection framework. It is available
inside the java.util package. The ArrayDeque class
extends AbstractCollection class and implements Deque, Cloneable,
and Serializable interfaces.
The elements of ArrayDeque are organized as the elements of double ended
queue data structure. The ArrayDeque is a special kind of array that grows
and allows users to add or remove an element from both the sides of the
queue.
The ArrayDeque class is used to create a dynamic double ended queue of
elements that can grow or shrunk as needed.
🔔 The ArrayDeque is a child class of AbstractCollection
🔔 The ArrayDeque implements interfaces like Deque, Cloneable,
and Serializable.
🔔 The ArrayDeque allows to store duplicate data values, but not null values.
🔔 The ArrayDeque maintains the order of insertion.
🔔 The ArrayDeque allows to add and remove elements at both the ends.
🔔 The ArrayDeque is faster than LinkedList and Stack.

ArrayDeque class declaration


The ArrayDeque class has the following declaration.

Example
public class ArrayDeque<E> extends AbstractCollection<E> implements
Deque<E>, Cloneable, Serializable

ArrayDeque class constructors


The PriorityQueue class has the following constructors.

 ArrayDeque( ) - Creates an empty ArrayDeque with the default initial


capacity (16).
 ArrayDeque(Collection c) - Creates a ArrayDeque with given collection of
elements.
 ArrayDeque(int initialCapacity) - Creates an empty ArrayDeque with the
specified initial capacity.

Operations on ArrayDeque
The ArrayDeque class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.

Adding Items
The ArrayDeque class has the following methods to add items.

 boolean add(E element) - Appends given element to the ArrayDeque.


 boolean addAll(Collection c) - Appends given collection of elements to
the ArrayDeque.
 void addFirst(E element) - Adds given element at front of the
ArrayDeque.
 void addLast(E element) - Adds given element at end of the ArrayDeque.
 boolean offer(E element) - Adds given element at end of the ArrayDeque.
 boolean offerFirst(E element) - Adds given element at front of the
ArrayDeque.
 boolean offerLast(E element) - Adds given element at end of the
ArrayDeque.
 void push(E element) - Adds given element at front of the ArrayDeque.

Let's consider an example program to illustrate adding items to the


ArrayDeque.

Example
import java.util.*;

public class ArrayDequeExample {

public static void main(String[] args) {


ArrayDeque deque = new ArrayDeque();
ArrayDeque anotherDeque = new ArrayDeque();

deque.add(10);
deque.addFirst(5);
deque.addLast(15);
deque.offer(20);
deque.offerFirst(10);
deque.offerLast(30);

System.out.println("\nDeque is\n" + deque);

anotherDeque.addAll(deque);

System.out.println("\nanotherDeque is\n" +
anotherDeque);

anotherDeque.push(40);

System.out.println("\nanotherDeque after push(40) is\n" +


anotherDeque);
}

Accessing Items
The ArrayDeque class has the following methods to access items.

 E element( ) - Returns the first element from the invoking ArrayDeque.


 E getFirst( ) - Returns the first element from the invoking ArrayDeque.
 E getLast( ) - Returns the last element from the invoking ArrayDeque.
 E peek( ) - Returns the first element from the invoking ArrayDeque,
returns null if this queue is empty.
 E peekFirst( ) - Returns the first element from the invoking ArrayDeque,
returns null if this queue is empty.
 E peekLast( ) - Returns the last element from the invoking ArrayDeque,
returns null if this queue is empty.

Let's consider an example program to illustrate accessing items from the


ArrayDeque.

Example
import java.util.*;

public class ArrayDequeExample {

public static void main(String[] args) {

ArrayDeque deque = new ArrayDeque();

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


deque.add(i);

System.out.println("\nDeque is\n" + deque);

System.out.println("\nelement() - " + deque.element());

System.out.println("\ngetFirst() - " + deque.getFirst());

System.out.println("\ngetLast() - " + deque.getLast());


System.out.println("\npeek() - " + deque.peek());

System.out.println("\npeekFirst() - " + deque.peekFirst());

System.out.println("\npeekLast() - " + deque.peekLast());


}

Updating Items
The ArrayDeque class has no methods to update or change items.

Removing Items
The ArrayDeque class has the following methods to remove items.

 E remove( ) - Removes the first element from the invoking ArrayDeque.


 E removeFirst( ) - Removes the first element from the invoking
ArrayDeque.
 E removeLast( ) - Removes the last element from the invoking
ArrayDeque.
 boolean remove(Object o) - Removes the specified element from the
invoking ArrayDeque.
 boolean removeFirstOccurrence(Object o) - Removes the first occurrence
of the specified element in this ArrayDeque.
 boolean removeLastOccurrence(Object o) - Removes the last occurrence
of the specified element in this ArrayDeque.
 boolean removeIf(Predicate p) - Removes all of the elements of
ArrayDeque collection that satisfy the given predicate.
 boolean retainAll(Collection c) - Removes all of the elements of
ArrayDeque collection except specified collection of elements.
 E poll( ) - Removes the first element from the ArrayDeque, and returns
null if the list is empty.
 E pollFirst( ) - Removes the first element from the ArrayDeque, and
returns null if the list is empty.
 E pollLast( ) - Removes the last element from the ArrayDeque, and
returns null if the list is empty.
 E pop( ) - Removes the first element from the ArrayDeque.
 void clear( ) - Removes all the elements from the PriorityQueue.

Let's consider an example program to illustrate removing items from the


ArrayDeque.

Example
import java.util.*;

public class ArrayDequeExample {

public static void main(String[] args) {

ArrayDeque deque = new ArrayDeque();

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


deque.add(i);

System.out.println("\nDeque is\n" + deque);

deque.remove();
System.out.println("\nDeque after remove()\n" + deque);

deque.removeFirst();
System.out.println("\nDeque after removeFirst()\n" +
deque);
System.out.println("\nDeque after removeLast()\n" +
deque);

deque.remove(5);
System.out.println("\nDeque after remove(5)\n" + deque);

deque.poll();
System.out.println("\nDeque after poll()\n" + deque);

deque.pollFirst();
System.out.println("\nDeque after pollFirst()\n" + deque);

deque.pollLast();
System.out.println("\nDeque after pollLast()\n" + deque);

deque.pop();
System.out.println("\nDeque after pop()\n" + deque);

deque.clear();
System.out.println("\nDeque after clear()\n" + deque);
}
}

Other utility methods


The ArrayDeque class has the following methods to work with elements of it.

 int size( ) - Returns the total number of elements in the invoking


ArrayDeque.
 boolean isEmpty( ) - Returns true if the ArrayDeque is empty otherwise
returns false.
 ArrayDeque clone( ) - Returns a copy of the invoking ArrayDeque.
 boolean contains(Object element) - Returns true if the ArrayDeque
contains given element otherwise returns false.
 boolean containsAll(Collection c) - Returns true if the ArrayDeque
contains given collection of elements otherwise returns false.
 boolean equals(Object o) - Compares the specified object with invoking
ArrayDeque collection for equality.
 int hashCode( ) - Returns the hash code of the invoking ArrayDeque.
 Object[ ] toArray( ) - Returns an array of Object instances that contains
all the elements from invoking ArrayDeque.
 Spliterator spliterator( ) - Creates spliterator over the elements in a
ArrayDeque.
 Iterator iterator( ) - Returns an iterator over the elements in the
ArrayDeque. The iterator does not return the elements in any particular
order.

Let's consider an example program to illustrate other utility methods of the


ArrayDeque.

Example
import java.util.*;

public class ArrayDequeExample {

public static void main(String[] args) {

ArrayDeque deque = new ArrayDeque();

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


deque.add(i);

System.out.println("\nDeque is\n" + deque);


System.out.println("\nsize() - " + deque.size());

System.out.println("\nisEmpty() - " + deque.isEmpty());

System.out.println("\ncontains(6) - " + deque.contains(6));

System.out.println("\nhashCode() - " + deque.hashCode());

System.out.println("\nequals(6) - " + deque.equals(6));


}
}

Consolidated list of methods


The following table providess a consolidated view of all methods of
ArrayDeque.

Method Description

boolean add(E element) Appends given element to the ArrayDeque.

boolean addAll(Collection c) Appends given collection of elements to the

ArrayDeque.

void addFirst(E element) Inserts the given element at front of the

ArrayDeque.
Method Description

void addLast(E element) Inserts the given element at end of the

ArrayDeque.

boolean offer(E element) Inserts the given element at end of the

ArrayDeque.

boolean offerFirst(E element) Inserts the given element at front of the

ArrayDeque.

boolean offerLast(E element) Inserts the given element at end of the

ArrayDeque.

void push(E element) Inserts the given element at front of the

ArrayDeque.

E element( ) Returns the first element from the

ArrayDeque.

E getFirst( ) Returns the first element from the

ArrayDeque.

E getLast( ) Returns the last element from the


Method Description

ArrayDeque.

E peek( ) Returns the first element from the invoking

ArrayDeque, returns null if this queue is

empty.

E peekFirst( ) Returns the first element from the invoking

ArrayDeque, returns null if this queue is empty.

E peekLast( ) Returns the last element from the invoking

ArrayDeque, returns null if this queue is empty.

E remove() Removes the first element from the invoking

ArrayDeque.

E removeFirst() Removes the first element from the invoking

ArrayDeque.

E removeLast() Removes the last element from the invoking

ArrayDeque.

boolean remove(Object element) Removes the first occurence of the given


Method Description

element from the invoking ArrayDeque.

boolean removeFirstOccurrence(Object Removes the first occurrence of the specified


element)
element in this ArrayDeque.

boolean removLastOccurrence(Object Removes the last occurrence of the specified


element)
element in this ArrayDeque.

boolean removeIf(Predicate p) Removes all of the elements of the

ArrayDeque collection that satisfy the given

predicate.

boolean retainAll(Collection c) Removes all the elements except those are in

the specified collection from the invoking

ArrayDeque.

E poll( ) Removes the first element from the

ArrayDeque, and returns null if the

ArrayDeque is empty.

E pollFirst( ) Removes the first element from the


Method Description

ArrayDeque, and returns null if the

ArrayDeque is empty.

E pollLast( ) Removes the last element from the

ArrayDeque, and returns null if the

ArrayDeque is empty.

E pop() Removes the first element from the invoking

ArrayDeque.

void clear( ) Removes all the elements from the

ArrayDeque.

int size( ) Returns the total number of elements in the

invoking ArrayDeque.

boolean isEmpty( ) Returns true if the ArrayDeque is empty

otherwise returns false.

boolean equals( ) Compares the specified object with invoking

ArrayDeque collection for equality.


Method Description

boolean contains(Object element) Returns true if the ArrayDeque contains

given element otherwise returns false.

boolean containsAll(Collection c) Returns true if the ArrayDeque contains all

elements of given collection otherwise returns

false.

int hashCode( ) Returns the hash code of the invoking

ArrayDeque.

Object[ ] toArray( ) Returns an array of Object instances that

contains all the elements from invoking

ArrayDeque.

Spliterator spliterator( ) Creates spliterator over the elements in a

ArrayDeque.

Iterator iterator( ) Returns an iterator over the elements in the

ArrayDeque. The iterator does not return the elemen


particular order.
ITERATOR CLASS
The java collection framework often we want to cycle through the elements. For
example, we might want to display each element of a collection. The java provides an
interface Iterator that is available inside the java.util package to cycle through each
element of a collection.
🔔 The Iterator allows us to move only forward direction.
🔔 The Iterator does not support the replacement and addition of new elements.
We use the following steps to access a collection of elements using the Iterator.

 Step - 1: Create an object of the Iterator by calling collection.itertor( ) method.


 Step - 2: Use the method hasNext( ) to access to check does the collection has
the next element. (Use a loop).
 Step - 3: Use the method next( ) to access each element from the collection.
(use inside the loop).

The Iterator has the following methods.

Method Description

Iterator iterator( ) Used to obtain an iterator to the start of the collection.

boolean hasNext( ) Returns true if the collection has the next element, otherwise, it returns

false.

E next( ) Returns the next element available in the collection.

Let's consider an example program to illustrate accessing elements of a collection via


the Iterator.

Example
import java.util.*;

public class TreeSetExample {


public static void main(String[] args) {

TreeSet set = new TreeSet();

Random num = new Random();


for(int i = 0; i < 10; i++)
set.add(num.nextInt(100));

Iterator collection = set.iterator();

System.out.println("All the elements of TreeSet collection:");


while(collection.hasNext())
System.out.print(collection.next() + ", ");

}
}

Accessing a collection using for-each


We can use the for-each statement to access elements of a collection.
Let's consider an example program to illustrate accessing items from a collection using
a for-each statement.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {


TreeSet set = new TreeSet();
ArrayList list = new ArrayList();
PriorityQueue queue = new PriorityQueue();

Random num = new Random();


for(int i = 0; i < 10; i++) {
set.add(num.nextInt(100));
list.add(num.nextInt(100));
queue.add(num.nextInt(100));
}

System.out.println("\nAll the elements of TreeSet collection:");


for(Object element:set) {
System.out.print(element + ", ");
}

System.out.println("\n\nAll the elements of ArrayList collection:");


for(Object element:list) {
System.out.print(element + ", ");
}

System.out.println("\n\nAll the elements of PriorityQueue collection:");


for(Object element:queue) {
System.out.print(element + ", ");
}

}
}

The For-Each alternative


Using for-each, we can access the elements of a collection. But for-each can only be
used if we don't want to modify the contents of a collection, and we don't want any
reverse access.
Alternatively, we can use the Iterator to access or cycle through a collection of
elements.
Let's consider an example program to illustrate The for-each alternative.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {

ArrayList list = new ArrayList();


PriorityQueue queue = new PriorityQueue();

Random num = new Random();


for(int i = 0; i < 10; i++) {
list.add(num.nextInt(100));
queue.add(num.nextInt(100));
}

// Accessing using for-each statement


System.out.println("\n\nAll the elements of ArrayList collection:");
for(Object element:list) {
System.out.print(element + ", ");
}

// Accessing using Iterator


Iterator collection = queue.iterator();
System.out.println("\n\nAll the elements of PriorityQueue collection:");
while(collection.hasNext()) {
System.out.print(collection.next() + ", ");
}

}
}

Accessing elements using ListIterator


The ListIterator interface is used to traverse through a list in both forward and backward
directions. It does not support all types of collections. It supports only the collection
which implements the List interface.
The ListIterator provides the following methods to traverse through a list of elements.

Method Description

ListIterator listIterator( ) Used obtain an iterator of the list collection.

boolean hasNext( ) Returns true if the list collection has next element, otherwise it returns

false.

E next( ) Returns the next element available in the list collection.

boolean hasPrevious( ) Returns true if the list collection has previous element, otherwise it returns

false.

E previous( ) Returns the previous element available in the list collection.

int nextIndex( ) Returns the index of the next element. If there is no next element, returns
Method Description

the size of the list.

E previousIndex( ) Returns the index of the previous element. If there is no previous element

Let's consider an example program to illustrate ListIterator to access elements of a list.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {

ArrayList list = new ArrayList();

Random num = new Random();


for(int i = 0; i < 10; i++) {
list.add(num.nextInt(100));
}

// Accessing in forward direction using ListIterator


ListIterator collection = list.listIterator();
System.out.println("\n\nAll the elements of PriorityQueue collection:");
while(collection.hasNext()) {
System.out.print(collection.next() + ", ");
}
System.out.println("\n\neverse of the PriorityQueue collection:");
while(collection.hasPrevious()) {
System.out.print(collection.previous() + ", ");
}

}
}
MAP INTERFACE
The java collection framework has an interface Map that is available inside
the java.util package. The Map interface is not a subtype of Collection
interface.
🔔 The Map stores the elements as a pair of key and value.
🔔 The Map does not allows duplicate keys, but allows duplicate values.
🔔 In a Map, each key can map to at most one value only.
🔔 In a Map, the order of elements depends on specific implementations, e.g
TreeMap and LinkedHashMap have predictable order, while HashMap does
not.

The Map interface has the following child interfaces.

Interface Description

Map Maps unique key to value.

Map.Entry Describe an element in key and value pair in a map. Entry is sub

interface of Map.

SortedMap It is a child of Map so that key are maintained in an ascending orde

NavigableMap It is a child of SortedMap to handle the retrienal of entries based on

closest match searches.

The Map interface has the following three classes.


Class Description

HashMap It implements the Map interface, but it doesn't maintain any order.

LinkedHashMap It implements the Map interface, it also extends HashMap class.

It maintains the insertion order.

TreeMap It implements the Map and SortedMap interfaces. It maintains the

ascending order.

Map Interface methods


The Map interface contains methods for handling elements of a map. It has
the following methods.
The insertion of a key, value pair is said to be an entry in the map terminology.

Method Description

V put(Object key, Object value) Inserts an entry in the map.

void putAll(Map map) Inserts the specified map into the invok

V putIfAbsent(K key, V value) Inserts the specified value with the spe

in the map only if that key does not exi

Set keySet( ) Returns a Set that contains all the keys


Method Description

invoking Map.

Collection values( ) Returns a collection that contains all th

of invoking Map.

Set<Map.Entry<K,V>> entrySet() Returns a Set that contains all the keys

values of invoking Map.

V get(Object key) Returns the value associated with the s

key.

V getOrDefault(Object key, V defaultValue) Returns the value associated with the s

key, or defaultValue if the map does no

the key.

boolean containsValue(Object value) Returns true if specified value found in

else return false.

boolean containsKey(Object key) Returns true if specified key found in th

else return false.

V replace(K key, V value) Used to replace the specified value for


Method Description

specified key.

boolean replace(K key, V oldValue, V Used to replaces the oldValue with the
newValue)
newValue for a specified key.

void replaceAll(BiFunction function) Replaces each entry's value with the re

invoking the given function on that entr

entries have been processed or the fun

throws an exception.

V merge(K key, V value, BiFunction If the specified key is not already assoc
remappingFunction)
with a value or is associated with null,

associates it with the given non-null va

V compute(K key, BiFunction Used to compute a mapping for the spe


remappingFunction)
key and its current mapped value.

V computeIfAbsent(K key, Function Used to compute its value using the giv
mappingFunction)
mapping function, if the specified key is

already associated with a value, and en

it into this map unless null.


Method Description

V computeIfPresent(K key, BiFunction Used to compute a new mapping given


remappingFunction)
key and its current mapped value if the
is present and non-null.

void forEach(BiConsumer action) It performs the given action for each en

the map until all entries have been pro


an exception.

V remove(Object key) Removes an entry for the specified key

boolean remove(Object key, Object value) Removes the specified values with the

associated specified keys from the map

void clear() Removes all the entries from the map.

boolean equals(Object o) It is used to compare the specified

Object with the Map.

int hashCode() Returns the hash code for invoking the

Map.

boolean isEmpty() Returns true if the map is empty;

otherwise returns false.


Method Description

int size() Returns total number of entries in the in


MAP INTERFACE CLASSES
The java collection framework has an interface Map that is available inside
the java.util package. The Map interface is not a subtype of Collection
interface.
The Map interface has the following three classes.

Class Description

HashMap It implements the Map interface, but it doesn't maintain any order.

LinkedHashMap It implements the Map interface, it also extends HashMap class. It maintains

the insertion order.

TreeMap It implements the Map and SortedMap interfaces. It maintains the ascending

order.

Commonly used methods defined by Map interface

Method Description

Object put(Object k, Object v) It performs an entry into the Map.

Object putAll(Map m) It inserts all the entries of m into invoking Map.

Object get(Object k) It returns the value associated with given key.

boolean containsKey(Object k) It returns true if map contain k as key. Otherwise false.


Method Description

Set keySet() It returns a set that contains all the keys from the

invoking Map.

Set valueSet() It returns a set that contains all the values from the

invoking Map.

Set entrySet() It returns a set that contains all the entries from the

invoking Map.

Now, let's look at each class in detail with example programs.

HashMap Class
The HashMap class is a child class of AbstractMap, and it implements the
Map interface. The HashMap is used to store the data in the form of key,
value pair using hash table concept.

Key Properties of HashMap


 HashMap is a child class of AbstractMap class.
 HashMap implements the interfeaces Map, Cloneable, and Serializable.
 HashMap stores data as a pair of key and value.
 HashMap uses Hash table concept to store the data.
 HashMap does not allow duplicate keys, but values may be repeated.
 HashMap allows only one null key and multiple null values.
 HashMap does not follow any oreder.
 HashMap has the default capacity 16 entries.

Let's consider an example program to illustrate HashMap.

Example
import java.util.*;

public class HashMapExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

HashMap employeeInfo = new HashMap();


HashMap contactInfo = new HashMap();

employeeInfo.put(1, "Raja");
employeeInfo.put(2, "Gouthami");
employeeInfo.put(3, "Heyansh");
employeeInfo.put(4, "Yamini");
employeeInfo.put(5, "ManuTej");

System.out.println("Employee Information\n" +
employeeInfo);

System.out.println("\nPlease enter the ID and Contact


number");
System.out.println("Employee IDs : " +
employeeInfo.keySet());
System.out.print("Enter ID: ");
int id = read.nextInt();
System.out.print("Enter Contact Number: ");
long contactNo = read.nextLong();
if(employeeInfo.containsKey(id)) {
contactInfo.put(id, contactNo);
}

System.out.println("\n\nEmployee Contact Information\n");


System.out.println("ID - " + id);
System.out.println("Name - " + employeeInfo.get(id));
System.out.println("Contact Number - " +
contactInfo.get(id));

LinkedHashMap Class
The LinkedHashMap class is a child class of HashMap, and it implements the
Map interface. The LinkedHashMap is used to store the data in the form of
key, value pair using hash table and linked list concepts.

Key Properties of LinkedHashMap


 LinkedHashMap is a child class of HashMap class.
 LinkedHashMap implements the Map interface.
 LinkedHashMap stores data as a pair of key and value.
 LinkedHashMap uses Hash table concept to store the data.
 LinkedHashMap does not allow duplicate keys, but values may be
repeated.
 LinkedHashMap allows only one null key and multiple null values.
 LinkedHashMap follows the insertion oreder.
 LinkedHashMap has the default capacity 16 entries.

Let's consider an example program to illustrate LinkedHashMap.

Example
import java.util.*;

public class HashMapExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

LinkedHashMap employeeInfo = new LinkedHashMap();


LinkedHashMap contactInfo = new LinkedHashMap();

employeeInfo.put(1, "Raja");
employeeInfo.put(2, "Gouthami");
employeeInfo.put(3, "Heyansh");
employeeInfo.put(5, "ManuTej");

System.out.println("Employee Information\n" +
employeeInfo);

System.out.println("\nPlease enter the ID and Contact


number");
System.out.println("Employee IDs : " +
employeeInfo.keySet());
System.out.print("Enter ID: ");
int id = read.nextInt();
System.out.print("Enter Contact Number: ");
long contactNo = read.nextLong();
if(employeeInfo.containsKey(id)) {
contactInfo.put(id, contactNo);
}

System.out.println("\n\nEmployee Contact Information\n");


System.out.println("ID - " + id);
System.out.println("Name - " + employeeInfo.get(id));
System.out.println("Contact Number - " +
contactInfo.get(id));

}
TreeMap Class
The TreeMap class is a child class of AbstractMap, and it implements the
NavigableMap interface which is a child interface of SortedMap. The TreeMap
is used to store the data in the form of key, value pair using a red-black tree
concepts.

Key Properties of TreeMap


 TreeMap is a child class of AbstractMap class.
 TreeMap implements the NavigableMap interface which is a child
interface of SortedMap interface.
 TreeMap stores data as a pair of key and value.
 TreeMap uses red-black tree concept to store the data.
 TreeMap does not allow duplicate keys, but values may be repeated.
 TreeMap does not allow null key, but allows null values.
 TreeMap follows the ascending oreder based on keys.
Let's consider an example program to illustrate TreeMap.

Example
import java.util.*;

public class HashMapExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

TreeMap employeeInfo = new TreeMap();


TreeMap contactInfo = new TreeMap();

employeeInfo.put(1, "Raja");
employeeInfo.put(4, "Gouthami");
employeeInfo.put(5, "Heyansh");
employeeInfo.put(3, "Yamini");
employeeInfo.put(2, "ManuTej");

System.out.println("Employee Information\n" +
employeeInfo);

System.out.println("\nPlease enter the ID and Contact


number");
System.out.println("Employee IDs : " +
employeeInfo.keySet());
System.out.print("Enter ID: ");
int id = read.nextInt();
long contactNo = read.nextLong();
if(employeeInfo.containsKey(id)) {
contactInfo.put(id, contactNo);
}

System.out.println("\n\nEmployee Contact Information\n");


System.out.println("ID - " + id);
System.out.println("Name - " + employeeInfo.get(id));
System.out.println("Contact Number - " +
contactInfo.get(id));

}
12.COMPARATORS
The Comparator is an interface available in the java.util package. The
java Comparator is used to order the objects of user-defined classes. The
java Comparator can compare two objects from two different classes.
Using the java Comparator, we can sort the elements based on data members
of a class. For example, we can sort based on roolNo, age, salary, marks, etc.
The Comparator interface has the following methods.

Method Description

int compare(Object obj1, Object obj2) It is used to compares the obj1 with o bj2 .

boolean equals(Object obj) It is used to check the equity between current

object and argumented object.

The Comparator can be used in the following three ways.

 Using a seperate class that implements Comparator interface.


 Using anonymous class.
 Using lamda expression.

Using a seperate class


We use the following steps to use Comparator with a seperate class.

 Step - 1: Create the user-defined class.


 Step - 2: Create a class that implements Comparator interface.
 Step - 3: Implement the comapare( ) method of Comparator interface
inside the above defined class(step - 2).
 Step - 4: Create the actual class where we use the Compatator object
with sort method of Collections class.
 Step - 5: Create the object of Compatator interface using the class
crearted in step - 2.
 Step - 6: Call the sort method of Collections class by passing the object
created in step - 6.
 Step - 7: Use a for-each (any loop) to print the sorted information.
Let's consider an example program to illustrate Comparator using a separate
class.

Example
import java.util.*;

class Student{

String name;
float percentage;

Student(String name, float percentage){


this.name = name;
this.percentage = percentage;
}

class PercentageComparator implements Comparator<Student>{


public int compare(Student stud1, Student stud2) {
if(stud1.percentage < stud2.percentage)
return 1;
return -1;
}
}

public class StudentCompare{

public static void main(String args[]) {


ArrayList<Student> studList = new ArrayList<Student>();

studList.add(new Student("Gouthami", 90.61f));


studList.add(new Student("Raja", 83.55f));
studList.add(new Student("Honey", 85.55f));
studList.add(new Student("Teja", 77.56f));
studList.add(new Student("Varshith", 80.89f));

Comparator<Student> com = new PercentageComparator();

Collections.sort(studList, com);

System.out.println("Avg % --> Name");


System.out.println("---------------------");
for(Student stud:studList) {
System.out.println(stud.percentage + " --> " +
stud.name);
}
}
}
Using anonymous class
We use the following steps to use Comparator with anonymous class.

 Step - 1: Create the user-defined class.


 Step - 2: Create the actual class where we use the Compatator object
with sort method of Collections class.
 Step - 3: Create the object of Compatator interface using anonymous
class and implement compare method of Comparator interface.
 Step - 4: Call the sort method of Collections class by passing the object
created in step - 6.
 Step - 5: Use a for-each (any loop) to print the sorted information.

Let's consider an example program to illustrate Comparator using a separate


class.

Example
import java.util.*;

class Student{

String name;
float percentage;

Student(String name, float percentage){


this.name = name;
this.percentage = percentage;
}

public class StudentCompare{

public static void main(String args[]) {

ArrayList<Student> studList = new ArrayList<Student>();

studList.add(new Student("Gouthami", 90.61f));


studList.add(new Student("Raja", 83.55f));
studList.add(new Student("Honey", 85.55f));
studList.add(new Student("Teja", 77.56f));
studList.add(new Student("Varshith", 80.89f));

Comparator<Student> com = new Comparator<Student>() {


public int compare(Student stud1, Student stud2)
{
if(stud1.percentage <
stud2.percentage)
return 1;
return -1;
}
};

Collections.sort(studList, com);

System.out.println("Avg % --> Name");


System.out.println("---------------------");
for(Student stud:studList) {
System.out.println(stud.percentage + " --> " +
stud.name);
}
}
}
Using lamda expression
We use the following steps to use Comparator with lamda expression.

 Step - 1: Create the user-defined class.


 Step - 2: Create the actual class where we use the Compatator object
with sort method of Collections class.
 Step - 3: Create the object of Compatator interface using lamda
expression and implement the code for compare method of Comparator
interface.
 Step - 4: Call the sort method of Collections class by passing the object
created in step - 6.
 Step - 5: Use a for-each (any loop) to print the sorted information.

Let's consider an example program to illustrate Comparator using a separate


class.

Example
import java.util.*;

class Student{

String name;
float percentage;

Student(String name, float percentage){


this.name = name;
this.percentage = percentage;
}
}

public class StudentCompare{

public static void main(String args[]) {

ArrayList<Student> studList = new ArrayList<Student>();

studList.add(new Student("Gouthami", 90.61f));


studList.add(new Student("Raja", 83.55f));
studList.add(new Student("Honey", 85.55f));
studList.add(new Student("Teja", 77.56f));
studList.add(new Student("Varshith", 80.89f));

Comparator<Student> com = (stud1, stud2) -> {


if(stud1.percentage <
stud2.percentage)
return 1;
return -1;
};

Collections.sort(studList, com);

System.out.println("Avg % --> Name");


System.out.println("---------------------");
for(Student stud:studList) {
System.out.println(stud.percentage + " --> " +
stud.name);
}
}
}
13.COLLECTION ALGORITHMS
The java collection framework defines several algorithms as static methods
that can be used with collections and map objects.
All the collection algorithms in the java are defined in a class
called Collections which defined in the java.util package.
All these algorithms are highly efficient and make coding very easy. It is better
to use them than trying to re-implement them.
The collection framework has the following methods as algorithms.

Method Description

void sort(List list) Sorts the elements of the list as determined by thei

natural ordering.

void sort(List list, Comparator comp) Sorts the elements of the list as determined by

Comparator comp.

void reverse(List list) Reverses all the elements sequence in list.

void rotate(List list, int n) Rotates list by n places to the right. To rotate left,

use a negative value for n.

void shuffle(List list) Shuffles the elements in list.

void shuffle(List list, Random r) Shuffles the elements in the list by using r as a

source of random numbers.


Method Description

void copy(List list1, List list2) Copies the elements of list2 to list1.

List nCopies(int num, Object obj) Returns num copies of obj contained in an

immutable list. num can not be zero or negative.

void swap(List list, int idx1, int idx2) Exchanges the elements in the list at the indices

specified by idx1 and idx2.

int binarySearch(List list, Object value) Returns the position of value in the list (must be in

the sorted order), or -1 if value is not found.

int binarySearch(List list, Object value, Returns the position of value in the list ordered
Comparator c)
according to c, or -1 if value is not found.

int indexOfSubList(List list, List subList) Returns the index of the first match of subList in

the list, or -1 if no match is found.

int lastIndexOfSubList(List list, List subList) Returns the index of the last match of subList in

the list, or -1 if no match is found.

Object max(Collection c) Returns the largest element from the collection c

as determined by natural ordering.


Method Description

Object max(Collection c, Comparator comp) Returns the largest element from the collection c

as determined by Comparator comp.

Object min(Collection c) Returns the smallest element from the collection c

as determined by natural ordering.

Object min(Collection c, Comparator comp) Returns the smallest element from the collection c
by Comparator comp.

void fill(List list, Object obj) Assigns obj to each element of the list.

boolean replaceAll(List list, Object old, Object Replaces all occurrences of old with new in the list
new)

Enumeration enumeration(Collection c) Returns an enumeration over Collection c.

ArrayList list(Enumeration enum) Returns an ArrayList that contains the elements of

Set singleton(Object obj) Returns obj as an immutable set.

List singletonList(Object obj) Returns obj as an immutable list.

Map singletonMap(Object k, Object v) Returns the key(k)/value(v) pair as an immutable m

Collection synchronizedCollection(Collection c) Returns a thread-safe collection backed by c.


Method Description

List synchronizedList(List list) Returns a thread-safe list backed by list.

Map synchronizedMap(Map m) Returns a thread-safe map backed by m.

SortedMap synchronizedSortedMap(SortedMap Returns a thread-safe SortedMap backed by sm.


sm)

Set synchronizedSet(Set s) Returns a thread-safe set backed by s.

SortedSet synchronizedSortedSet(SortedSet ss) Returns a thread-safe set backed by ss.

Collection unmodifiableCollection(Collection c) Returns an unmodifiable collection backed by c.

List unmodifiableList(List list) Returns an unmodifiable list backed by list.

Set unmodifiableSet(Set s) Returns an unmodifiable thread-safe set backed by

SortedSet unmodifiableSortedSet(SortedSet ss) Returns an unmodifiable set backed by ss.

Map unmodifiableMap(Map m) Returns an unmodifiable map backed by m.

SortedMap unmodifiableSortedMap(SortedMap Returns an unmodifiable SortedMap backed by sm


sm)

Let's consider an example program to illustrate Collections algorithms.


Example
import java.util.*;

public class CollectionAlgorithmsExample {

public static void main(String[] args) {

ArrayList list = new ArrayList();


PriorityQueue queue = new PriorityQueue();
HashSet set = new HashSet();
HashMap map = new HashMap();

Random num = new Random();

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


list.add(num.nextInt(100));
queue.add(num.nextInt(100));
set.add(num.nextInt(100));
map.put(i, num.nextInt(100));
}

System.out.println("List => " + list);


System.out.println("Queue => " + queue);
System.out.println("Set => " + set);
System.out.println("Map => " + map);
System.out.println("---------------------------------------");

Collections.sort(list);
System.out.println("List in ascending order => " + list);

System.out.println("Largest element in set => " +


Collections.max(set));

System.out.println("Smallest element in queue => " +


Collections.min(queue));

Collections.reverse(list);
System.out.println("List in reverse order => " + list);

Collections.shuffle(list);
System.out.println("List after shuffle => " + list);
}
}
14.ARRAYS
The java collection framework has a class Arrays that provides methods for creating
dynamic array and perform various operations like search, asList, campare, etc.
The Arrays class in java is defined in the java.util package. All the methods defined by
Arrays class are static methods.
The Arrays class in java has the following methods.

Method Description

List<T> asList(T[] arr) It returns a fixed-size list backed by

the specified Arrays.

int binarySearch(T[] arr, element) It searches for the specified elemen

t in the array with the

help of Binary Search algorithm,

and returns the position.

int binarySearch(T[] arr, int fromIndex, int It searches a range of the specified
toIndex, T key, Comparator c)
array for the specified

object using the binary search

algorithm.

T[] copyOf(T[] originalArr, int newLength) It copies the specified array,

truncating or padding with

the default value (if necessary)

so the copy has the


Method Description

specified length.

T[] copyOfRange(T[] originalArr, int fromIndex, It copies the specified range of the
int endIndex)
specified array into a

new Arrays.

boolean equals(T[] arr1, T[] arr2) It returns true if the two specified

arrays of booleans are

equal to one another, otherwise

retruns false.

boolean deepEquals(T[] arr1, T[] arr2) It returns true if the two specified

arrays of booleans are

deeply equal to one another,

otherwise retruns false

(it compares including nested arrays)

int hashCode(T[] arr) It returns the hash code for the

specified array.

int deepHashCode(T[] arr) It returns the hash code for the

specified array including


Method Description

nested arrays.

String toString(T[] arr) It Returns a string representation

of the contents of the

specified array.

String deepToString(T[] arr) It Returns a string representation

of the contents of the

specified array including nested

arrays.

void fill(T[] arr, T value) It assigns the specified value to each

element of the

specified array.

void fill(T[] arr, int fromIndex, int toIndex, T It assigns the specified value to each
value)
element of the

specified range of the specified array.

The range to

be filled extends from fromIndex,

inclusive, to

toIndex, exclusive.
Method Description

void parallelPrefix(T[] arr, BinaryOperator o) It Cumulates, in parallel, each

element of the give

n array in place, using the supplied

function.

void setAll(T[] arr, FunctionGenerator) It sets all elements of the specified

array, using the

provided generator function to

compute each

element.

void parallelSetAll(T[] arr, FunctionGenerator) It Sets all elements of the specified

array, in

parallel, using the provided generator

function

to compute each element.

void sort(T[] arr) It sorts the specified array into

ascending order.

void parallelSort(T[] arr) It sorts the specified array of objects

into
Method Description

ascending order, according to the natural


ordering of its elements.

Of<T> spliterator(T[] arr) It returns a Spliterator.Of<T> covering

all of the specified array.

Stream<T> stream(T[] arr) It returns a sequential Stream with the

specified array as its source.

Let's consider an example program to illustrate methods of Arrays class.

Example
import java.util.*;

public class ArraysClassExample {

public static void main(String[] args) {

int[] arr1 = {10, 3, 50, 7, 30, 66, 28, 54, 42};

int[] arr2 = {67, 2, 54, 67, 13, 56, 98};

System.out.print("Array1 => ");


for(int i:arr1)
System.out.print(i + ", ");
System.out.print("\nArray2 => ");
for(int i:arr2)
System.out.print(i + ", ");
System.out.println("Array1 as List => " + Arrays.asList(arr1));

System.out.println("Position of 30 in Array1 => " +


Arrays.binarySearch(arr1, 30));

System.out.println("equity of array1 and array2 => " +


Arrays.equals(arr1, arr2));

System.out.println("Hash code of Array1 => " +


Arrays.hashCode(arr1));

Arrays.fill(arr1, 15);
System.out.print("fill Array1 with 15 => ");
for(int i:arr1)
System.out.print(i + ", ");

Arrays.sort(arr2);
System.out.print("\nArray2 in sorted order => ");
for(int i:arr2)
System.out.print(i + ", ");
}
}

When we execute the above code, it produce the following output.


15.DICTIONARY
In java, the package java.util contains a class
called Dictionary which works like a Map. The Dictionary is
an abstract class used to store and manage elements in the
form of a pair of key and value.
The Dictionary stores data as a pair of key and value. In the
dictionary, each key associates with a value. We can use the
key to retrieve the value back when needed.
🔔 The Dictionary class is no longer in use, it is obsolete.
🔔 As Dictionary is an abstract class we can not create its
object. It needs a child class like Hashtable.
The Dictionary class in java has the following methods.

S. No. Methods with Description

1 Dictionary( )
It's a constructor.

2 Object put(Object key, Object value)

Inserts a key and its value into the dictionary. Returns null on
success; returns the previous value associated with the key
if the key is already exist.
S. No. Methods with Description

3 Object remove(Object key)


It returns the value associated with given key and removes
the same; Returns null if the key does not exist.

4 Object get(Object key)


It returns the value associated with given key; Returns
null
if the key does not exist.

5 Enumeration keys( )
Returns an enumeration of the keys contained in the
dictionary.

6 Enumeration elements( )
Returns an enumeration of the values contained in the
dictionary.

7 boolean isEmpty( )
It returns true if dictionary has no elements; otherwise
returns false.

8 int size( )
S. No. Methods with Description

It returns the total number of elements in the dictionary.

Let's consider an example program to illustrate methods of


Dictionary class.

Example
import java.util.*;

public class DictionaryExample {

public static void main(String args[]) {

Dictionary dict = new Hashtable();

dict.put(1, "Rama");
dict.put(2, "Seetha");
dict.put(3, "Heyansh");
dict.put(4, "Varshith");
dict.put(5, "Manutej");

System.out.println("Dictionary\n=> " + dict);

// keys()
System.out.print("\nKeys in Dictionary\n=> ");
for (Enumeration i = dict.keys();
i.hasMoreElements();)
{
System.out.print(" " + i.nextElement());
}

// elements()
System.out.print("\n\nValues in Dictionary\n=> ");
for (Enumeration i = dict.elements();
i.hasMoreElements();)
{
System.out.print(" " + i.nextElement());
}

//get()
System.out.println("\n\nValue associated with
key 3 => " + dict.get(3));
System.out.println("Value associated with key 30
=> " + dict.get(30));

//size()
System.out.println("\nDictionary has " +
dict.size() + " elements");
System.out.println("\nIs Dictionary empty? " +
dict.isEmpty());
}
}

When we execute the above code, it produce the following


output.
16.HASHTABLE
In java, the package java.util contains a class
called Hashtable which works like a HashMap but it
is synchronized. The Hashtable is a concrete class
of Dictionary. It is used to store and manage
elements in the form of a pair of key and value.
The Hashtable stores data as a pair of key and
value. In the Hashtable, each key associates with a
value. Any non-null object can be used as a key or
as a value. We can use the key to retrieve the value
back when needed.
🔔 The Hashtable class is no longer in use, it is
obsolete. The alternate class is HashMap.
🔔 The Hashtable class is a concrete class of
Dictionary.
🔔 The Hashtable class is synchronized.
🔔 The Hashtable does no allow null key or value.
🔔 The Hashtable has the initial default capacity 11.
The Hashtable class in java has the following
constructors.
S. No. Constructor with Description

1 Hashtable( )

It creates an empty hashtable with the default


initial capacity 11.

2 Hashtable(int capacity)
It creates an empty hashtable with the specified
initial capacity.

3 Hashtable(int capacity, float loadFactor)


It creates an empty hashtable with the
specified
initial capacity and loading factor.

4 Hashtable(Map m)
It creates a hashtable containing elements
of Map m.

The Hashtable class in java has the following


methods.
S. No. Methods with Description

1 V put(K key, V value)

It inserts the specified key and value into the hash table

2 void putAll(Map m))


It inserts all the elements of Map m into the invoking
Hashtable.

3 V putIfAbsent(K key, V value)


If the specified key is not already associated with a valu
associates it with the given value and returns null, else
returns the current value.

4 V getOrDefault(Object key, V defaultValue)


It returns the value associated with given key; or
defaultValue if the hashtable contains no mapping for th
key.

5 V get(Object key)
S. No. Methods with Description

It returns the value associated with the given key.

6 Enumeration keys()
Returns an enumeration of the keys of the hashtable.

7 Set keySet()
Returns a set view of the keys of the hashtable.

8 Collection values()
It returns a collection view of the values contained in th
Hashtable.

9 Enumeration elements()
Returns an enumeration of the values of the hashtable.

10 Set entrySet()
It returns a set view of the mappings contained in the
hashtable.

11 int hashCode()
S. No. Methods with Description

It returns the hash code of the hashtable.

12 Object clone()
It returns a shallow copy of the Hashtable.

13 V remove(Object key)
It returns the value associated with given key and remo
the same.

14 boolean remove(Object key, Object value)


It removes the specified values with the associated
specified keys from the hashtable.

15 boolean contains(Object value)


It returns true if the specified value found within the
hash table, else return false.

16 boolean containsValue(Object value)


It returns true if the specified value found within the
S. No. Methods with Description

hash table, else return false.

17 boolean containsKey(Object key)


It returns true if the specified key found within the
hash table, else return false.

18 V replace(K key, V value)


It replaces the specified value for a specified key.

19 boolean replace(K key, V oldValue, V newValue)


It replaces the old value with the new value for a specif
key.

20 void replaceAll(BiFunction function)


It replaces each entry's value with the result of invoking
given function on that entry until all entries have been
processed or the function throws an exception.

21 void rehash()
S. No. Methods with Description

It is used to increase the size of the hash table and


rehashes all of its keys.

22 String toString()
It returns a string representation of the Hashtable objec

23 V merge(K key, V value, BiFunction remappingFunc


If the specified key is not already associated with a valu
or is associated with null, associates it with the given
non-null value.

24 void forEach(BiConsumer action)


It performs the given action for each entry in the map
until all entries have been processed or the action
throws an exception.

25 boolean isEmpty( )
It returns true if Hashtable has no elements; otherwise
S. No. Methods with Description

26 int size( )
It returns the total number of elements in the Hashtable

27 void clear()
It is used to remove all the lements of a Hashtable.

28 boolean equals(Object o)
It is used to compare the specified Object with the
Hashtable.

Let's consider an example program to illustrate


methods of Hashtable class.

Example
import java.util.*;

public class HashtableExample {

public static void main(String[] args) {


Random num = new Random();
Hashtable table = new Hashtable();

//put(key, value)
for(int i = 1; i <= 5; i++)
table.put(i, num.nextInt(100));

System.out.println("Hashtable => " +


table);

//get(key)
System.out.println("\nValue associated
with key 3 => " + table.get(3));
System.out.println("Value associated with
key 30 => " + table.get(30));

//keySet()
System.out.println("\nKeys => " +
table.keySet());

//values()
System.out.println("\nValues => " +
table.values());
//entrySet()
System.out.println("\nKey, Value pairs as
a set => " + table.entrySet());

//hashCode()
System.out.println("\nHash code => " +
table.hashCode());

//hashCode()
System.out.println("\nTotal number of
elements => " + table.size());

//isEmpty()
System.out.println("\nEmpty status of
Hashtable => " + table.isEmpty());
}
}

When we execute the above code, it produce the


following output.
17.PROPERTIES CLASS
In java, the package java.util contains a class
called Properties which is a child class of Hashtable class. It
implements interfaces like Map, Cloneable, and Serializable.
Java has this built-in class Properties which allow us to save
and load multiple values from a file. This makes the class
extremely useful for accessing data related to configuration.
The Properties class used to store configuration values
managed as key, value pairs. In each pair, both key and value
are String values. We can use the key to retrieve the value
back when needed.
The Properties class provides methods to get data from the
properties file and store data into the properties file. It can
also be used to get the properties of a system.
🔔 The Properties class is child class of Hashtable class.
🔔 The Properties class implements Map, Cloneable, and
Serializable interfaces.
🔔 The Properties class used to store configuration values.
🔔 The Properties class stores the data as key, value pairs.
🔔 In Properties class both key and value are String data type.
🔔 Using Properties class, we can load key, value pairs into a
Properties object from a stream.
🔔 Using Properties class, we can save the Properties object
to a stream.
The Properties class in java has the following constructors.
S. No. Constructor with Description

1 Properties( )

It creates an empty property list with no default values.

2 Properties(Properties defaults)
It creates an empty property list with the specified defaults.

The Properties class in java has the following methods.

S.No. Methods with Description

1 void load(Reader r)

It loads data from the Reader object.

2 void load(InputStream is)


It loads data from the InputStream object.

3 void store(Writer w, String comment)


It writes the properties in the writer object.

4 void store(OutputStream os, String comment)


It writes the properties in the OutputStream object.
S.No. Methods with Description

5 String getProperty(String key)


It returns value associated with the specified key.

6 String getProperty(String key, String defaultValue)


It returns the value associated with given key; or defaultValue if the
Properties contains no mapping for the key.

7 void setProperty(String key, String value)


It calls the put method of Hashtable.

8 Enumeration propertyNames())
It returns an enumeration of all the keys from the property list.

9 Set stringPropertyNames()
Returns a set view of the keys of the Properties.

10 void list(PrintStream out)


It is used to print the property list out to the specified output stream.

11 void loadFromXML(InputStream in)


It is used to load all of the properties represented by the XML
document on the specified input stream into this properties table.

12 void storeToXML(OutputStream os, String comment)


S.No. Methods with Description

It writes the properties in the writer object for generating XML


document.

13 void storeToXML(Writer w, String comment, String encoding)


It writes the properties in the writer object for generating XML
document with the specified encoding.

Let's consider an example program to illustrate methods of


Properties class to store a user configuration details to a
properties file.

Example
import java.io.*;
import java.util.*;

public class PropertiesClassExample {

public static void main(String[] args) {

FileOutputStream fos = null;


File configFile = null;
configFile = new
File("config.properties");
fos = new
FileOutputStream(configFile);
Properties configProperties = new
Properties();

configProperties.setProperty("userName",
"btechsmartclass");

configProperties.setProperty("password", "java");
configProperties.setProperty("email",
"user@btechsmartclass.com");

configProperties.store(fos, "Login
Details");

fos.close();

System.out.println("Configuration
saved!!!");
}
catch(Exception e) {
System.out.println("Something went wrong
while opening file");
}
}

When we execute the above code, it produce the following


output.

Let's consider another example program to illustrate methods


of Properties class using console.

Example
import java.util.*;
public class PropertiesClassExample {

public static void main(String[] args) {

Properties sites = new Properties();


String str;

sites.put("search", "www.google.com");
sites.put("learn", "www.btechsmartclass.com");
sites.put("mail", "www.gmail.com");
sites.put("social", "www.facebook.com");
sites.put("watch", "www.youtube.com");

System.out.println("Keys => " +


sites.keySet() + "\n");

Iterator itr = sites.keySet().iterator();


while(itr.hasNext())
{
str = (String)itr.next();
System.out.println("The link for " + str +
" is " + sites.getProperty(str));
}
System.out.println("\nThe link for learn is " +
sites.getProperty("learn"));
System.out.println("\nThe link for learning is " +
sites.getProperty("learning", "not found"));
}

When we execute the above code, it produce the following


output.
18.STACK CLASS
In java, the package java.util contains a class
called Stack which is a child class of Vector class. It
implements the standard principle Last-In-First-Out of stack
data structure.
The Stack has push method for inesrtion and pop method for
deletion. It also has other utility methods.
🔔 In Stack, the elements are added to the top of the stack and
removed from the top of the stack.
The Stack class in java has the following constructor.

S. No. Constructor with Description

1 Stack( )

It creates an empty Stack.

The Stack class in java has the following methods.

S.No. Methods with Description

1 Object push(Object element)

It pushes the element onto the stack and returns the same.

2 Object pop( )
It returns the element on the top of the stack and removes
S.No. Methods with Description

the same.

3 int search(Object element)


If element found, it returns offset from the top. Otherwise, -

4 Object peek( )
It returns the element on the top of the stack.

5 boolean empty()
It returns true if the stack is empty, otherwise returns false.

Let's consider an example program to illustrate methods of


Stack class.

Example
import java.util.*;

public class StackClassExample {

public static void main(String[] args) {

Stack stack = new Stack();


for(int i = 0; i < 5; i++)
stack.push(num.nextInt(100));

System.out.println("Stack elements => " +


stack);

System.out.println("Top element is " +


stack.peek());

System.out.println("Removed element is " +


stack.pop());

System.out.println("Element 50 availability => "


+ stack.search(50));

System.out.println("Stack is empty? - " +


stack.isEmpty());

When we execute the above code, it produce the following


output.
19. VECTOR CLASS
In java, the package java.util contains a class called Vector which implements
the List interface.
The Vector is similar to an ArrayList. Like ArrayList Vector also maintains the insertion order.
But Vector is synchronized, due to this reason, it is rarly used in the non-thread application. It
also lead to poor performance.
🔔 The Vector is a class in the java.util package.
🔔 The Vector implements List interface.
🔔 The Vector is a legacy class.
🔔 The Vector is synchronized.
The Vector class in java has the following constructor.

S. No. Constructor with Description

1 Vector( )

It creates an empty Vector with default initail capacity of 10.

2 Vector(int initialSize)
It creates an empty Vector with specified initail capacity.

3 Vector(int initialSize, int incr)


It creates a vector whose initial capacity is specified by size and whose increment is specified by
incr.

4 Vector(Collection c)
It creates a vector that contains the elements of collection c.

The Vector class in java has the following methods.

S.No. Methods with Description

1 boolean add(Object o)

It appends the specified element to the end of this Vector.

2 void add(int index, Object element)


It inserts the specified element at the specified position in this Vector.

3 void addElement(Object obj)


Adds the specified object to the end of the vector, increasing its size by one.

4 boolean addAll(Collection c)
S.No. Methods with Description

It appends all of the elements in the specified Collection to the end of the Vector.

5 boolean addAll(int index, Collection c)


It inserts all of the elements in in the specified Collection into the Vector at the specified position.

6 Object set(int index, Object element)


It replaces the element at the specified position in the vector with the specified element.

7 void setElementAt(Object obj, int index)


It sets the element at the specified index of the vector to be the specified object.

8 Object remove(int index)


It removes the element at the specified position in the vector.

9 boolean remove(Object o)
It removes the first occurrence of the specified element in the vector.

10 boolean removeElement(Object obj)


It removes the first occurrence of the specified element in the vector.

11 void removeElementAt(int index)


It removes the element at specified index in the vector.

12 void removeRange(int fromIndex, int toIndex)


It removes from the Vector all of the elements whose index is between fromIndex, inclusive and
toIndex, exclusive.

13 boolean removeAll(Collection c)
It removes from the vector all of its elements that are contained in the specified Collection.

14 void removeAllElements()
It removes all the elements from the vector.

15 boolean retainAll(Collection c)
It removes all the elements from the vector except elements those are in the given collection.

16 Object elementAt(int index)


It returns the element at specified index in the Vector.

17 Object get(int index)


It returns the element at specified index in the Vector.

18 Enumeration elements()
S.No. Methods with Description

It returns the Enumeration of all the elements of the Vector.

19 Object firstElement()
It returns the first element of the Vector.

20 Object lastElement()
It returns the last element of the Vector.

21 int indexOf(Object element)


It returns the index value of the first occurence of the given element in the Vector.

22 int indexOf(Object elem, int index)


It returns the index value of the first occurence of the given element, search beginning at specified
index in the Vector.

23 int lastIndexOf(Object elememnt)


It returns the index value of the last occurence of the given element, search beginning at specified
index in the Vector.

24 List subList(int fromIndex, int toIndex)


It returns a list containing elements fromIndex to toIndex in the Vector.

25 int capacity()
It returns the current capacity of the Vector.

26 void clear()
It removes all the elements from the Vector.

27 Object clone()
It returns a clone of the Vector.

28 boolean contains(Object element)


It returns true if element found in the Vector, otherwise returns false.

29 boolean containsAll(Collection c)
It returns true if all the elements of geven collection found in the Vector, otherwise returns false.

30 void ensureCapacity(int minCapacity)


It increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components
specified by the minimum capacity argument.

31 boolean equals(Object o)
S.No. Methods with Description

It compares the specified Object with this vector for equality.

32 int hashCode()
It returns the hash code of the Vector.

33 boolean isEmpty()
It returns true if Vector has no elements, otherwise returns false.

34 void setSize(int newSize)


It sets the size of the vector.

35 int size()
It returns total number of elements in the vector.

36 Object[] toArray()
It returns an array containing all the elements of the Vector.

37 String toString()
It returns a string representation of the Vector.

38 void trimToSize()
It trims the capacity of the vector to be the vector's current size.

Let's consider an example program to illustrate methods of Vector class.

Example
import java.util.*;

public class VectorClassExample {

public static void main(String[] args) {

Vector list = new Vector();

list.add(10);
list.add(30);
list.add(0, 100);
System.out.println("Vector => " + list);

System.out.println("get(2) => " + list.get(2));

System.out.println("firstElement() => " + list.firstElement());

System.out.println("indexOf(50) => " + list.indexOf(50));

System.out.println("contains(30) => " + list.contains(30));

System.out.println("capacity() => " + list.capacity());

System.out.println("size() => " + list.size());

System.out.println("isEmpty() => " + list.isEmpty());

When we execute the above code, it produce the following output.


20.STRING TOKENIZER
The StringTokenizer is a built-in class in java used to break a string into tokens. The
StringTokenizer class is available inside the java.util package.
The StringTokenizer class object internally maintains a current position within the string to be
tokenized.
🔔 A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.
The StringTokenizer class in java has the following constructor.

S. No. Constructor with Description

1 StringTokenizer(String str)

It creates StringTokenizer object for the specified string str with default delimeter.

2 StringTokenizer(String str, String delimeter)


It creates StringTokenizer object for the specified string str with specified delimeter.

3 StringTokenizer(String str, String delimeter, boolean returnValue)


It creates StringTokenizer object with specified string, delimeter and returnValue.

The StringTokenizer class in java has the following methods.

S.No. Methods with Description

1 String nextToken()

It returns the next token from the StringTokenizer object.

2 String nextToken(String delimeter)


It returns the next token from the StringTokenizer object based on the delimeter.

3 Object nextElement()
It returns the next token from the StringTokenizer object.

4 boolean hasMoreTokens()
It returns true if there are more tokens in the StringTokenizer object. otherwise returns false.

5 boolean hasMoreElements()
It returns true if there are more tokens in the StringTokenizer object. otherwise returns false.

6 int countTokens()
It returns total number of tokens in the StringTokenizer object.

Let's consider an example program to illustrate methods of StringTokenizer class.


Example
import java.util.StringTokenizer;

public class StringTokenizerExample {

public static void main(String[] args) {

String url = "www.GMAIL.com";


String title = "GMAIL ACCOUNT";

StringTokenizer tokens = new StringTokenizer(title);


StringTokenizer anotherTokens = new StringTokenizer(url, ".");

System.out.println("\nTotal tokens in title is " + tokens.countTokens());

System.out.print("Tokens in the title => ");


while(tokens.hasMoreTokens()) {
System.out.print(tokens.nextToken() + ", ");
}

System.out.println("\n\nTotal tokens in url is " +


anotherTokens.countTokens());

System.out.println("Tokens in the url with delimeter (.) => ");


while(anotherTokens.hasMoreElements()) {
System.out.print(anotherTokens.nextElement() + ", ");
}

}
21. BIT SET CLASS
The BitSet is a built-in class in java used to create a dynamic array of bits represented by
boolean values. The BitSet class is available inside the java.util package.
The BitSet array can increase in size as needed. This feature makes the BitSet similar to a
Vector of bits.
🔔 The bit values can be accessed by non-negative integers as an index.
🔔 The size of the array is flexible and can grow to accommodate additional bit as needed.
🔔 The default value of the BitSet is boolean false with a representation as 0 (off).
🔔 BitSet uses 1 bit of memory per each boolean value.
The BitSet class in java has the following constructor.

S. No. Constructor with Description

1 BitSet( )

It creates a default BitSet object.

2 BitSet(int noOfBits)
It creates a BitSet object with number of bits that it can hold. All bits are initialized to zero.

The BitSet class in java has the following methods.

S.No. Methods with Description

1 void and(BitSet bitSet)

It performs AND operation on the contents of the invoking BitSet object with those specified by bitSet.

2 void andNot(BitSet bitSet)


For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared.

3 void flip(int index)


It reverses the bit at specified index.

4 void flip(int startIndex, int endIndex)


It reverses all the bits from specified startIndex to endIndex.

5 void or(BitSet bitSet)


It performs OR operation on the contents of the invoking BitSet object with those specified by bitSet.

6 void xor(BitSet bitSet)


It performs XOR operation on the contents of the invoking BitSet object with those specified by bitSet.
S.No. Methods with Description

7 int cardinality( )
It returns the number of bits set to true in the invoking BitSet.

8 void clear( )
It sets all the bits to zeros of the invoking BitSet.

9 void clear(int index)


It set the bit specified by given index to zero.

10 void clear(int startIndex, int endIndex)


It sets all the bits from specified startIndex to endIndex to zero.

11 Object clone( )
It duplicates the invoking BitSet object.

12 boolean equals(Object bitSet)


It retruns true if both invoking and argumented BitSets are equal, otherwise returns false.

13 boolean get(int index)


It retruns the present state of the bit at given index in the invoking BitSet.

14 BitSet get(int startIndex, int endIndex)


It returns a BitSet object that consists all the bits from startIndex to endIndex.

15 int hashCode( )
It returns the hash code of the invoking BitSet.

16 boolean intersects(BitSet bitSet)


It returns true if at least one pair of corresponding bits within the invoking object and bitSet are 1.

17 boolean isEmpty( )
It returns true if all bits in the invoking object are zero, otherwise returns false.

17 int length( )
It returns the total number of bits in the invoking BitSet.

18 int nextClearBit(int startIndex)


It returns the index of the next cleared bit, (that is, the next zero bit), starting from the index specified by startInde

19 int nextSetBit(int startIndex)


It returns the index of the next set bit (that is, the next 1 bit), starting from the index specified by startIndex. If no b
-1 is returned.
S.No. Methods with Description

20 void set(int index)


It sets the bit specified by index.

21 void set(int index, boolean value)


It sets the bit specified by index to the value passed in value.

22 void set(int startIndex, int endIndex)


It sets all the bits from startIndex to endIndex.

23 void set(int startIndex, int endIndex, boolean value)


It sets all the bits to specified value from startIndex to endIndex.

24 int size( )
It returns the total number of bits in the invoking BitSet.

25 String toString( )
It returns the string equivalent of the invoking BitSet object.

Let's consider an example program to illustrate methods of BitSet class.

Example
import java.util.*;

public class BitSetClassExample {

public static void main(String[] args) {

BitSet bSet_1 = new BitSet();


BitSet bSet_2 = new BitSet(16);

bSet_1.set(10);
bSet_1.set(5);
bSet_1.set(0);
bSet_1.set(7);
bSet_1.set(20);
bSet_2.set(1);
bSet_2.set(15);
bSet_2.set(20);
bSet_2.set(77);
bSet_2.set(50);

System.out.println("BitSet_1 => " + bSet_1);


System.out.println("BitSet_2 => " + bSet_2);

bSet_1.and(bSet_2);
System.out.println("BitSet_1 after and with bSet_2 => " + bSet_1);

bSet_1.andNot(bSet_2);
System.out.println("BitSet_1 after andNot with bSet_2 => " + bSet_1);

System.out.println("Length of the bSet_2 => " + bSet_2.length());


System.out.println("Size of the bSet_2 => " + bSet_2.size());

System.out.println("Bit at index 2 in bSet_2 => " + bSet_2.get(2));

bSet_2.set(2);
System.out.println("Bit at index 2 after set in bSet_2 => " +
bSet_2.get(2));
}
}

When we execute the above code, it produce the following output.


22. DATE CLASS
The Date is a built-in class in java used to work with date and time in java. The Date class is
available inside the java.util package. The Date class represents the date and time with
millisecond precision.
The Date class implements Serializable, Cloneable and Comparable interface.
🔔 Most of the constructors and methods of Date class has been deprecated after Calendar
class introduced.
The Date class in java has the following constructor.

S.
No. Constructor with Description

1 Date( )

It creates a Date object that represents current date and time.

2 Date(long milliseconds)
It creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.

3 Date(int year, int month, int date) - Depricated


It creates a date object with the specified year, month, and date.

4 Date(int year, int month, int date, int hrs, int min) - Depricated
It creates a date object with the specified year, month, date, hours, and minuts.

5 Date(int year, int month, int date, int hrs, int min, int sec) - Depricated
It creates a date object with the specified year, month, date, hours, minuts and seconds.

5 Date(String s) - Depricated
It creates a Date object and initializes it so that it represents the date and time indicated by the string s, which is
interpreted as if by the parse(java.lang.String) method.

The Date class in java has the following methods.

S.No. Methods with Description

1 long getTime()

It returns the time represented by this date object.

2 boolean after(Date date)


It returns true, if the invoking date is after the argumented date.

3 boolean before(Date date)


S.No. Methods with Description

It returns true, if the invoking date is before the argumented date.

4 Date from(Instant instant)


It returns an instance of Date object from Instant date.

5 void setTime(long time)


It changes the current date and time to given time.

6 Object clone( )
It duplicates the invoking Date object.

7 int compareTo(Date date)


It compares current date with given date.

8 boolean equals(Date date)


It compares current date with given date for equality.

9 int hashCode()
It returns the hash code value of the invoking date object.

10 Instant toInstant()
It converts current date into Instant object.

11 String toString()
It converts this date into Instant object.

Let's consider an example program to illustrate methods of Date class.

Example
import java.time.Instant;
import java.util.Date;

public class DateClassExample {

public static void main(String[] args) {

Date time = new Date();


System.out.println("Current date => " + time);

System.out.println("Date => " + time.getTime() + " milliseconds");

System.out.println("after() => " + time.after(time) + " milliseconds");

System.out.println("before() => " + time.before(time) + " milliseconds");

System.out.println("hashCode() => " + time.hashCode());

When we execute the above code, it produce the following output.


23. CALENDER CLASS
The Calendar is a built-in abstract class in java used to convert date between a specific instant
in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. The Calendar class is
available inside the java.util package.
The Calendar class implements Serializable, Cloneable and Comparable interface.
🔔 As the Calendar class is an abstract class, we can not create an object using it.
🔔 We will use the static method Calendar.getInstance() to instantiate and implement a sub-
class.
The Calendar class in java has the following methods.

S.No. Methods with Description

1 Calendar getInstance()

It returns a calendar using the default time zone and locale.

2 Date getTime()
It returns a Date object representing the invoking Calendar's time value.

3 TimeZone getTimeZone()
It returns the time zone object associated with the invoking calendar.

4 String getCalendarType()
It returns an instance of Date object from Instant date.

5 int get(int field)


It rerturns the value for the given calendar field.

6 int getFirstDayOfWeek()
It returns the day of the week in integer form.

7 int getWeeksInWeekYear()
It retruns the total weeks in week year.

8 int getWeekYear()
It returns the week year represented by current Calendar.

9 void add(int field, int amount)


It adds the specified amount of time to the given calendar field.

10 boolean after (Object when)


It returns true if the time represented by the Calendar is after the time represented by when Object.

11 boolean before(Object when)


S.No. Methods with Description

It returns true if the time represented by the Calendar is before the time represented by when Object.

12 void clear(int field)


It sets the given calendar field value and the time value of this Calendar undefined.

13 Object clone()
It retruns the copy of the current object.

14 int compareTo(Calendar anotherCalendar)


It compares and retruns the time values (millisecond offsets) between two calendar object.

15 void complete()
It sets any unset fields in the calendar fields.

16 void computeFields()
It converts the current millisecond time value time to calendar field values in fields[].

17 void computeTime()
It converts the current calendar field values in fields[] to the millisecond time value time.

18 boolean equals(Object object)


It returns true if both invoking object and argumented object are equal.

19 int getActualMaximum(int field)


It returns the Maximum possible value of the specified calendar field.

20 int getActualMinimum(int field)


It returns the Minimum possible value of the specified calendar field.

21 Set getAvailableCalendarTypes()
It returns a string set of all available calendar type supported by Java Runtime Environment.

22 Locale[] getAvailableLocales()
It returns an array of all locales available in java runtime environment.

23 String getDisplayName(int field, int style, Locale locale)


It returns the String representation of the specified calendar field value in a given style, and local.

24 Map getDisplayNames(int field, int style, Locale locale)


It returns Map representation of the given calendar field value in a given style and local.

25 int getGreatestMinimum(int field)


It returns the highest minimum value of the specified Calendar field.
S.No. Methods with Description

26 int getLeastMaximum(int field)


It returns the highest maximum value of the specified Calendar field.

27 int getMaximum(int field)


It returns the maximum value of the specified calendar field.

28 int getMinimalDaysInFirstWeek()
It returns required minimum days in integer form.

29 int getMinimum(int field)


It returns the minimum value of specified calendar field.

30 long getTimeInMillis()
It returns the current time in millisecond.

31 int hashCode()
It returns the hash code of the invoking object.

32 int internalGet(int field)


It returns the value of the given calendar field.

33 boolean isLenient()
It returns true if the interpretation mode of this calendar is lenient; false otherwise.

34 boolean isSet(int field)


If not set then it returns false otherwise true.

35 boolean isWeekDateSupported()
It returns true if the calendar supports week date. The default value is false.

36 void roll(int field, boolean up)


It increase or decrease the specified calendar field by one unit without affecting the other field

37 void set(int field, int value)


It sets the specified calendar field by the specified value.

38 void setFirstDayOfWeek(int value)


It sets the first day of the week.

39 void setMinimalDaysInFirstWeek(int value)


It sets the minimal days required in the first week.

40 void setTime(Date date)


S.No. Methods with Description

It sets the Time of current calendar object.

41 void setTimeInMillis(long millis)


It sets the current time in millisecond.

42 void setTimeZone(TimeZone value)


It sets the TimeZone with passed TimeZone value.

43 void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek)


It sets the current date with specified integer value.

44 Instant toInstant()
It converts the current object to an instant.

45 String toString()
It returns a string representation of the current object.

Let's consider an example program to illustrate methods of Calendar class.

Example
import java.util.*;

public class CalendarClassExample {

public static void main(String[] args) {

Calendar cal = Calendar.getInstance();

System.out.println("Current date and time : \n=>" + cal);


System.out.println("Current Calendar type : " + cal.getCalendarType());
System.out.println("Current date and time : \n=>" + cal.getTime());
System.out.println("Current date time zone : \n=>" + cal.getTimeZone());
System.out.println("Calendar filed 1 (year): " + cal.get(1));
System.out.println("Calendar day in integer form: " + cal.getFirstDayOfWeek());
System.out.println("Calendar weeks in a year: " + cal.getWeeksInWeekYear());
System.out.println("Available Calendar types: " +
cal.getAvailableCalendarTypes());
System.out.println("Calendar hash code: " + cal.hashCode());
System.out.println("Is calendar supports week date? " +
cal.isWeekDateSupported());
System.out.println("Calendar string representation: " + cal.toString());
}
}

When we execute the above code, it produce the following output.


24. RANDOM CLASS
The Random is a built-in class in java used to generate a stream of pseudo-random numbers in
java programming. The Random class is available inside the java.util package.
The Random class implements Serializable, Cloneable and Comparable interface.
🔔 The Random class is a part of java.util package.
🔔 The Random class provides several methods to generate random numbers of type integer,
double, long, float etc.
🔔 The Random class is thread-safe.
🔔 Random number generation algorithm works on the seed value. If not provided, seed value is
created from system nano time.
The Random class in java has the following constructors.

S.No. Constructor with Description

1 Random()

It creates a new random number generator.

2 Random(long seedValue)
It creates a new random number generator using a single long seedValue.

The Random class in java has the following methods.

S.No. Methods with Description

1 int next(int bits)

It generates the next pseudo-random number.

2 Boolean nextBoolean()
It generates the next uniformly distributed pseudo-random boolean value.

3 double nextDouble()
It generates the next pseudo-random double number between 0.0 and 1.0.

4 void nextBytes(byte[] bytes)


It places the generated random bytes into an user-supplied byte array.

5 float nextFloat()
It generates the next pseudo-random float number between 0.0 and 1.0..

6 int nextInt()
It generates the next pseudo-random int number.
S.No. Methods with Description

7 int nextInt(int n)
It generates the next pseudo-random integer value between zero and n.

8 long nextLong()
It generates the next pseudo-random, uniformly distributed long value.

9 double nextGaussian()
It generates the next pseudo-random Gaussian distributed double number with mean 0.0 and standard deviation

10 void setSeed(long seedValue)


It sets the seed of the random number generator using a single long seedValue.

11 DoubleStream doubles()
It returns a stream of pseudo-random double values, each conforming between 0.0 and 1.0.

12 DoubleStream doubles(double start, double end)


It retruns an unlimited stream of pseudo-random double values, each conforming to the given start and end.

13 DoubleStream doubles(long streamSize)


It returns a stream producing the pseudo-random double values for the given streamSize number, each between
1.0.

14 DoubleStream doubles(long streamSize, double start, double end)


It returns a stream producing the given streamSizenumber of pseudo-random double values, each conforming to
given start and end.

15 IntStream ints()
It returns a stream of pseudo-random integer values.

16 IntStream ints(int start, int end)


It retruns an unlimited stream of pseudo-random integer values, each conforming to the given start and end.

17 IntStream ints(long streamSize)


It returns a stream producing the pseudo-random integer values for the given streamSize number.

18 IntStream ints(long streamSize, int start, int end)


It returns a stream producing the given streamSizenumber of pseudo-random integer values, each conforming to
given start and end.

19 LongStream longs()
It returns a stream of pseudo-random long values.

20 LongStream longs(long start, long end)


S.No. Methods with Description

It retruns an unlimited stream of pseudo-random long values, each conforming to the given start and end.

21 LongStream longs(long streamSize)


It returns a stream producing the pseudo-random long values for the given streamSize number.

22 LongStream longs(long streamSize, long start, long end)


It returns a stream producing the given streamSizenumber of pseudo-random long values, each conforming to th
start and end.

Let's consider an example program to illustrate methods of Random class.

Example
import java.util.Random;

public class RandomClassExample {

public static void main(String[] args) {

Random rand = new Random();

System.out.println("Integer random number - " + rand.nextInt());


System.out.println("Integer random number from 0 to 100 - " +
rand.nextInt(100));
System.out.println("Boolean random value - " + rand.nextBoolean());
System.out.println("Double random number - " + rand.nextDouble());
System.out.println("Float random number - " + rand.nextFloat());
System.out.println("Long random number - " + rand.nextLong());
System.out.println("Gaussian random number - " + rand.nextGaussian());

When we execute the above code, it produce the following output.


25.FORMATTER CLASS
The Formatter is a built-in class in java used for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output in java programming.
The Formatter class is defined as final class inside the java.util package.
The Formatter class implements Cloneable and Flushable interface.
The Formatter class in java has the following constructors.

S.No. Constructor with Description

1 Formatter()

It creates a new formatter.

2 Formatter(Appendable a)
It creates a new formatter with the specified destination.

3 Formatter(Appendable a, Locale l)
It creates a new formatter with the specified destination and locale.

4 Formatter(File file)
It creates a new formatter with the specified file.

5 Formatter(File file, String charset)


It creates a new formatter with the specified file and charset.

6 Formatter(File file, String charset, Locale l)


It creates a new formatter with the specified file, charset, and locale.

7 Formatter(Locale l)
It creates a new formatter with the specified locale.

8 Formatter(OutputStream os)
It creates a new formatter with the specified output stream.

9 Formatter(OutputStream os, String charset)


It creates a new formatter with the specified output stream and charset.

10 Formatter(OutputStream os, String charset, Locale l)


It creates a new formatter with the specified output stream, charset, and locale.

11 Formatter(PrintStream ps)
It creates a new formatter with the specified print stream.

12 Formatter(String fileName)
S.No. Constructor with Description

It creates a new formatter with the specified file name.

13 Formatter(String fileName, String charset)


It creates a new formatter with the specified file name and charset.

14 Formatter(String fileName, String charset, Locale l)


It creates a new formatter with the specified file name, charset, and locale.

The Formatter class in java has the following methods.

S.No. Methods with Description

1 Formatter format(Locale l, String format, Object... args)

It writes a formatted string to the invoking object's destination using the specified locale, format string, and argum

2 Formatter format(String format, Object... args)


It writes a formatted string to the invoking object's destination using the specified format string and arguments.

3 void flush()
It flushes the invoking formatter.

4 Appendable out()
It returns the destination for the output.

5 Locale locale()
It returns the locale set by the construction of the invoking formatter.

6 String toString()
It converts the invoking object to string.

7 IOException ioException()
It returns the IOException last thrown by the invoking formatter's Appendable.

8 void close()
It closes the invoking formatter.

Let's consider an example program to illustrate methods of Formatter class.

Example
import java.util.*;
public class FormatterClassExample {

public static void main(String[] args) {

Formatter formatter=new Formatter();


formatter.format("%2$5s %1$5s %3$5s", "JAVA", "PROGRAMMING",
"Class");
System.out.println(formatter);

formatter = new Formatter();


formatter.format(Locale.FRANCE,"%.5f", -1325.789);
System.out.println(formatter);

String name = "Everyone";


formatter = new Formatter();
formatter.format(Locale.US,"Hello %s !", name);
System.out.println("" + formatter + " " + formatter.locale());

formatter = new Formatter();


formatter.format("%.4f", 123.1234567);
System.out.println("Decimal floating-point notation to 4 places: " +
formatter);

formatter = new Formatter();


formatter.format("%010d", 88);
System.out.println("value in 10 digits: " + formatter);
}
}
26. SCANNER CLASS
The Scanner is a built-in class in java used for read the input from the user in java
programming. The Scanner class is defined inside the java.util package.
The Scanner class implements Iterator interface.
The Scanner class provides the easiest way to read input in a Java program.
🔔 The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter
is whitespace.
The Scanner class in java has the following constructors.

S.No. Constructor with Description

1 Scanner(InputStream source)

It creates a new Scanner that produces values read from the specified input stream.

2 Scanner(InputStream source, String charsetName)


It creates a new Scanner that produces values read from the specified input stream.

3 Scanner(File source)
It creates a new Scanner that produces values scanned from the specified file.

4 Scanner(File source, String charsetName)


It creates a new Scanner that produces values scanned from the specified file.

5 Scanner(String source)
It creates a new Scanner that produces values scanned from the specified string.

6 Scanner(Readable source)
It creates a new Scanner that produces values scanned from the specified source.

7 Scanner(ReadableByteChannel source)
It creates a new Scanner that produces values scanned from the specified channel.

8 Scanner(ReadableByteChannel source, String charsetName)


It creates a new Scanner that produces values scanned from the specified channel.

The Scanner class in java has the following methods.

S.No. Methods with Description

1 String next()

It reads the next complete token from the invoking scanner.


S.No. Methods with Description

2 String next(Pattern pattern)


It reads the next token if it matches the specified pattern.

3 String next(String pattern)


It reads the next token if it matches the pattern constructed from the specified string.

4 boolean nextBoolean()
It reads a boolean value from the user.

5 byte nextByte()
It reads a byte value from the user.

6 double nextDouble()
It reads a double value from the user.

7 float nextFloat()
It reads a floating-point value from the user.

8 int nextInt()
It reads an integer value from the user.

9 long nextLong()
It reads a long value from the user.

10 short nextShort()
It reads a short value from the user.

11 String nextLine()
It reads a string value from the user.

12 boolean hasNext()
It returns true if the invoking scanner has another token in its input.

13 void remove()
It is used when remove operation is not supported by this implementation of Iterator.

14 void close()
It closes the invoking scanner.

Let's consider an example program to illustrate methods of Scanner class.

Example
import java.util.Scanner;

public class ScannerClassExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in); // Input stream is used

System.out.print("Enter any name: ");


String name = read.next();

System.out.print("Enter your age in years: ");


int age = read.nextInt();

System.out.print("Enter your salary: ");


double salary = read.nextDouble();

System.out.print("Enter any message: ");


read = new Scanner(System.in);
String msg = read.nextLine();

System.out.println("\n------------------------------------------");
System.out.println("Hello, " + name);
System.out.println("You are " + age + " years old.");
System.out.println("You are earning Rs." + salary + " per month.");
System.out.println("Words from " + name + " - " + msg);
}
}

When we execute the above code, it produce the following output.


FILL IN THE BLANKS

1. Collection framework is a collection of interfaces and classes used to storing and


processing a group of individual objects as a single unit.
2. The Collection interface is available inside the java.util package.
3. The List interface is used by classes like ArrayList, LinkedList, Vector, and Stack.
4. The Queue Interface are commonly used by classes like PriorityQueue and
ArrayDeque.
5. The Deque interface is a child interface of the Queue interface.
6. Set is a generic interface.
7. The elements of ArrayList are organized as an array internally.
8. The elements of LinkedList are organized as the elements of linked list data structure.
9. The elements of PriorityQueue are organized as the elements of queue data structure,
10. The HashSet class is used to create a collection that uses a hash table for storing set of
elements.
11. The java Comparator is used to order the objects of user-defined classes.
12. The Dictionary is an abstract class used to store and manage elements in the form of a
pair of key and value.
13. The Hashtable is a concrete class of Dictionary.
14. The Properties class used to store configuration values managed as key, value pairs.
15. The StringTokenizer class object internally maintains a current position within the string
to be tokenized.
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract
Window Toolkit [AWT]. Swing offers much-improved functionality over AWT, new
components, expanded components features, and excellent event handling with drag-and-
drop support.

Introduction of Java Swing

Swing has about four times the number of User Interface [UI] components as AWT and is
part of the standard Java distribution. By today’s application GUI requirements, AWT is a
limited implementation, not quite capable of providing the components required for
developing complex GUI’s required in modern commercial applications. The AWT
component set has quite a few bugs and really does take up a lot of system resources
when compared to equivalent Swing resources. Netscape introduced its Internet
Foundation Classes [IFC] library for use with Java. Its Classes became very popular with
programmers creating GUI’s for commercial applications.
 Swing is a Set Of API ( API- Set Of Classes and Interfaces )
 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit)
 Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs’
 Swing can be used to build(Develop) The Standalone swing GUI Apps Also as Servlets
And Applets
 It Employs model/view design architecture
 Swing is more portable and more flexible than AWT, The Swing is built on top of the
AWT
 Swing is Entirely written in Java
 Java Swing Components are Platform-independent And The Swing Components are
lightweight
 Swing Supports a Pluggable look and feels And Swing provides more powerful
components
 such as tables, lists, Scrollpanes, Colourchooser, tabbedpane, etc
 Further Swing Follows MVC.
Many programmers think that JFC and Swing are one and the same thing, but that is not
so.
JFC contains Swing [A UI component package] and quite a number of other items:
 Cut and paste: Clipboard support
 Accessibility features: Aimed at developing GUI’s for users with disabilities
 The Desktop Colors Features Has been Firstly introduced in Java 1.1
 Java 2D: it has Improved colors, images, and also texts support
Features Of Swing Class
 Pluggable look and feel
 Uses MVC architecture
 Lightweight Components
 Platform Independent
 Advanced features such as JTable, JTabbedPane, JScollPane, etc.
 Java is a platform-independent language and runs on any client machine, the GUI look
and feel, owned and delivered by a platform-specific O/S, simply does not affect an
application’s GUI constructed using Swing components
 Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not depend
on any non-Java [O/s based) system classes. Swing components have their own view
supported by Java’s look and feel classes.
 Pluggable Look and Feel: This feature enables the user to switch the look and feel of
Swing components without restarting an application. The Swing library supports
components’ look and feels that remain the same across all platforms wherever the
program runs. The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
 Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
 Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.
Swing Classes Hierarchy

The MVC Connection

 In general, a visual component is a composite of three distinct aspects:


1. The way that the component looks when rendered on the screen
2. The way such that the component reacts to the user
3. The state information associated With the component
 Over the years, one component architecture has proven itself to be exceptionally
effective:- Model-View-Controller or MVC for short.
 In MVC terminology, the model corresponds to the state information associated with
the Component
 The view determines how the component is displayed on the screen, including any
aspects of the view that are affected by the current state of the model.
 The controller determines how the component reacts to the user
The simplest Swing components have capabilities far beyond AWT components as
follows:
 Swing buttons and labels can be displaying images instead of or in addition to text
 The borders around most Swing components can be changed easily. For example, it is
easy to put a 1 pixel border around the outside of a Swing label
 Swing components do not have to be rectangular. Buttons, for example, can be round
 Now The Latest Assertive technologies such as screen readers can easily get
information from Swing components. For example: A screen reader tool can easily
capture the text that is displayed on a Swing button or label

There are two ways of creating the window:

1.Example for how to create a frame(Direct instantiation):

import java.io.*;

import javax.swing.*;

class FirstFrame

public static void main(String[] args)

JFrame frame=new JFrame();

frame.setVisible(true);

2.Example to create a window by extending JFrame class:

import java.io.*;

import javax.swing.JFrame;

class FirstFrame extends JFrame

FirstFrame()

this.setVisible(true); //last statement . this keyword holds object address


}

public static void main(String[] args)

new FirstFrame();

3. Example to set size,title to the frame

import java.io.*;

import javax.swing.JFrame;

class FirstFrame extends JFrame

FirstFrame()

this.setSize(600,500);

this.setTitle(“My First Frame”);

this.setVisible(true); //last statement . this keyword holds object address

public static void main(String[] args)

new FirstFrame();

}
LIMITATIONS OF AWT:

1. AWT supports limited number of GUI components.


2. AWT components are heavy weight components.
3. AWT components are developed by using platform specific code.
4. AWT components behave differently in different operating systems.
5. AWT component is converted by the native code of the operating system.

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

What is MVC architecture in Java?


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

The MVC pattern architecture consists of three layers:

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


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

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

Advantages of MVC Architecture


The advantages of MVC architecture are as follows:

o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require
to deal with massive code.
o The extending and testing of application is easier.

Implementation of MVC using Java


To implement MVC pattern in Java, we are required to create the following three
classes.
o Employee Class, will act as model layer
o EmployeeView Class, will act as a view layer
o EmployeeContoller Class, will act a controller layer

MVC Architecture Layers


Model Layer
The Model in the MVC design pattern acts as a data layer for the application. It
represents the business logic for application and also the state of application. The
model object fetch and store the model state in the database. Using the model
layer, rules are applied to the data that represents the concepts of application.

Let's consider the following code snippet that creates a which is also the first step to
implement MVC pattern.
The above code simply consists of getter and setter methods to the Employee class.

View Layer
As the name depicts, view represents the visualization of data received from the
model. The view layer consists of output of application or user interface. It sends
the requested data to the client, that is fetched from model layer by controller.
Controller Layer
The controller layer gets the user requests from the view layer and processes them,
with the necessary validations. It acts as an interface between Model and View. The
requests are then sent to model for data processing. Once they are processed, the
data is sent back to the controller and then displayed on the view.

Let's consider the following code snippet that creates the controller using the
EmployeeController class.

EmployeeController.java
Main Class Java file
The following example displays the main file to implement the MVC architecture.
Here, we are using the MVCMain class.

MVCMain.java
COMPONENTS OF SWING:
Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class) helpful in developing
window-based applications. Java Swing is lightweight and platform-independent that contains
various components and container classes. Furthermore, the Java swing library is built on the
top of the AWT(Abstract Window Toolkit), an API completely written in Java. In every
application, users can find an interactive and user-friendly interface that gives them the freedom
to use the app.

In Java Swing, there are several components like a scroll bar, button, text field, text area,
checkbox, radio button, etc. These components jointly form a GUI that offers a rich set of
functionalities and allows high-level customization.

What are Swing Components in Java?


A component is independent visual control, and Java Swing Framework contains a large set of
these components, providing rich functionalities and allowing high customization. They all are
derived from JComponent class. All these components are lightweight components. This class
offers some standard functionality like pluggable look and feel, support for accessibility, drag
and drop, layout, etc.
A container holds a group of components. It delivers a space where a component can be
managed and displayed. Containers are of two types:

List of Swing components:

1. JButton

2. JLabel

3. JTextField
4. JCheckBox

5. JRadioButton

6. JComboBox

7. JTextArea

8. JPasswordField

9. JTable

10. JList

11. JOptionPane

12. JScrollBar

13. JMenuBar, JMenu and JMenuItem

14. JPopupMenu

15. JCheckboxMenuItem

16. JSeperator

17. JProgressBar

18. JTree

19.JFileChooser

20. JTabbedPane

21. JSlider

DESCRIPTION OF EACH COMPONENT:

JButton:
We use JButton class to create a push button on the UI. The button can include some display
text or images. It yields an event when clicked and double-clicked. We can implement a JButton
in the application by calling one of its constructors.

Syntax:
JButton okBtn = new JButton(“Click”);

This constructor returns a button with the text Click on it.


JButton homeBtn = new JButton(carIcon);

Returns a button with a car Icon on it.


JButton homeBtn2 = new JButton(carIcon, “Car”);

Returns a button with the car icon and text as Car.

Display:

JLabel

We use JLabel class to render a read-only text label or images on the UI. It does not generate
any event.

Syntax:
JLabel textLabel = new JLabel(“This is 1st L...”);

This constructor returns a label with specified text.


JLabel imgLabel = new JLabel(carIcon);

It returns a label with a car icon.

The JLabel Contains four constructors. They are as follows:


1. JLabel()
2. JLabel(String s)
3. JLabel(Icon i)
4. JLabel(String s, Icon i, int horizontalAlignment)

Display:

JTextField
The JTextField renders an editable single-line text box. Users can input non-formatted text in
the box. We can initialize the text field by calling its constructor and passing an optional integer
parameter. This parameter sets the box width measured by the number of columns. Also, it
does not limit the number of characters that can be input into the box.
Syntax:
JTextField txtBox = new JTextField(50);

It is the most widely used text component. It has three constructors:


1. JTextField(int cols)
2. JTextField(String str, int cols)
3. JTextField(String str)

Note: cols represent the number of columns in the text field.

Display:

JCheckBox

The JCheckBox renders a check-box with a label. The check-box has two states, i.e., on and
off. On selecting, the state is set to "on," and a small tick is displayed inside the box.
Syntax:
CheckBox chkBox = new JCheckBox(“Java Swing”, true);

It returns a checkbox with the label Pepperoni pizza. Notice the second parameter in the
constructor. It is a boolean value that denotes the default state of the check-box. True means
the check-box defaults to the "on" state.

Display:

JRadioButton

A radio button is a group of related buttons from which we can select only one. We use
JRadioButton class to create a radio button in Frames and render a group of radio buttons in the
UI. Users can select one choice from the group.

Syntax:
JRadioButton jrb = new JRadioButton("Easy");

Display:
JComboBox

The combo box is a combination of text fields and a drop-down list. We


use JComboBox component to create a combo box in Swing.

Syntax:
JComboBox jcb = new JComboBox(name);

Display:

JTextArea

In Java, the Swing toolkit contains a JTextArea Class. It is under package


javax.swing.JTextArea class. It is used for displaying multiple-line text.

Declaration:
public class JTextArea extends JTextComponent

Syntax:
JTextArea textArea_area=new JTextArea("Ninja! please write something in the text
area.");

The JTextArea Contains four constructors. They are as follows:


1. JTextArea()
2. JTextArea(String s)
3. JTextArea(int row, int column)
4. JTextArea(String s, int row, int column)

Display:
JPasswordField

In Java, the Swing toolkit contains a JPasswordField Class. It is under package


javax.swing.JPasswordField class. It is specifically used for the password, and we can edit
them.

Declaration:
public class JPasswordField extends JTextField

Syntax:
JPasswordField password = new JPasswordField();

The JPasswordFieldContains 4 constructors. They are as follows:


1. JPasswordField()
2. JPasswordField(int columns)
3. JPasswordField(String text)
4. JPasswordField(String text, int columns)

Display:

JTable

In Java, the Swing toolkit contains a JTable Class. It is under package javax.swing.JTable class.
It is used to draw a table to display data.

Syntax:
JTable table = new JTable(table_data, table_column);

The JTable contains two constructors. They are as follows:


1. JTable()
2. JTable(Object[][] rows, Object[] columns)

Display:

JList
In Java, the Swing toolkit contains a JList Class. It is under package javax.swing.JList
class. It is used to represent a list of items together. We can select one or more than
one items from the list.
Declaration:
public class JList extends JComponent implements Scrollable, Accessible

Syntax:
DefaultListModel<String> list1 = new DefaultListModel<>();
list1.addElement("Apple");
list1.addElement("Orange");
list1.addElement("Banan");
list1.addElement("Grape");
JList<String> list_1 = new JList<>(list1);

The JListContains 3 constructors. They are as follows:


1. JList()
2. JList(ary[] listData)
3. JList(ListModel<ary> dataModel)

Display:
JOptionPane

In Java, the Swing toolkit contains a JOptionPane Class. It is under package


javax.swing.JOptionPane class. It is used for creating dialog boxes for displaying a message,
confirm box, or input dialog box.

Declaration:
public class JOptionPane extends JComponent implements Accessible

Syntax:
JOptionPane.showMessageDialog(jframe_obj, "Good Morning, Evening & Night.");

The JOptionPaneContains 3 constructors. They are as following:


1. JOptionPane()
2. JOptionPane(Object message)
3. JOptionPane(Object message, intmessageType)

Display:

JScrollBar

In Java, the Swing toolkit contains a JScrollBar class. It is under package


javax.swing.JScrollBar class. It is used for adding horizontal and vertical scrollbars.

Declaration:
public class JScrollBar extends JComponent implements Adjustable, Accessible

Syntax:
JScrollBar scrollBar = new JScrollBar();

The JScrollBarContains 3 constructors. They are as following:


1. JScrollBar()
2. JScrollBar(int orientation)
3. JScrollBar(int orientation, int value, int extent, int min_, intmax_)

Display:
JMenuBar, JMenu and JMenuItem

In Java, the Swing toolkit contains a JMenuBar, JMenu, and JMenuItem class. It is under
package javax.swing.JMenuBar, javax.swing.JMenu and javax.swing.JMenuItem class. The
JMenuBar class is used for displaying menubar on the frame. The JMenu Object is used to pull
down the menu bar's components. The JMenuItem Object is used for adding the labeled menu
item.

JMenuBar, JMenu and JMenuItem Declarations:


public class JMenuBar extends JComponent implements MenuElement, Accessible

public class JMenu extends JMenuItem implements MenuElement, Accessible

public class JMenuItem extends AbstractButton implements Accessible, MenuElement

Syntax:
JMenuBar menu_bar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuItem1 = new JMenuItem("Never");
menuItem2 = new JMenuItem("Stop");
menuItem3 = new JMenuItem("Learing");
menu.add(menuItem1);
menu.add(menuItem2);
menu.add(menuItem3);
Display:

JPopupMenu
In Java, the Swing toolkit contains a JPopupMenu Class. It is under package
javax.swing.JPopupMenu class. It is used for creating popups dynamically on a specified
position.

Declaration:
public class JPopupMenu extends JComponent implements Accessible, MenuElement

Syntax:
final JPopupMenu popupmenu1 = new JPopupMenu("Edit");

The JPopupMenuContains 2 constructors. They are as follows:


1. JPopupMenu()
2. JPopupMenu(String label)

Display:

JCheckBoxMenuItem

In Java, the Swing toolkit contains a JCheckBoxMenuItem Class. It is under package


javax.swing.JCheckBoxMenuItem class. It is used to create a checkbox on a menu.

Syntax:
JCheckBoxMenuItem item = new JCheckBoxMenuItem("Option_1");

The JCheckBoxMenuItemContains 2 constructors. They are as following:


1. JCheckBoxMenuItem()
2. JCheckBoxMenuItem(Action a)
3. JCheckBoxMenuItem(Icon icon)
4. JCheckBoxMenuItem(String text)
5. JCheckBoxMenuItem(String text, boolean b)
6. JCheckBoxMenuItem(String text, Icon icon)
7. JCheckBoxMenuItem(String text, Icon icon, boolean b)

Display:
JSeparator

In Java, the Swing toolkit contains a JSeparator Class. It is under package


javax.swing.JSeparator class. It is used for creating a separator line between two
components.

Declaration:
public class JSeparator extends JComponent implements SwingConstants, Accessible

Syntax:
jmenu_Item.addSeparator();

The JSeparatorContains 2 constructors. They are as following:


1. JSeparator()
2. JSeparator(int orientation)

Display:
JProgressBar

In Java, the Swing toolkit contains a JProgressBar Class. It is under package


javax.swing.JProgressBarclass. It is used for creating a progress bar of a task.

Declaration:
public class JProgressBar extends JComponent implements SwingConstants, Accessible

Syntax:
JProgressBar progressBar = new JProgressBar(0,2000);

The JProgressBarContains 4 constructors. They are as following:


1. JProgressBar()
2. JProgressBar(int min, int max)
3. JProgressBar(int orient)
4. JProgressBar(int orient, int min, int max)

Display:

JTree

In Java, the Swing toolkit contains a JTree Class. It is under package javax.swing.JTreeclass. It
is used for creating tree-structured data. It is a very complex component.
Declaration:
public class JTree extends JComponent implements Scrollable, Accessible

Syntax:
JTree tree = new JTree(tree_style);

The JTreeContains 3 constructors. They are as follows:


1. JTree()
2. JTree(Object[] value)
3. JTree(TreeNode root)

Display:
JFileChooser

The JFileChooser class renders a file selection utility. This component lets a user select a file
from the local system.
Syntax:
JFileChooser fileChooser = new JFileChooser();
JButton fileBtn = new JButton(“Select File”);
fileBtn.AddEventListner(new ActionListner(){
fileChooser.showOpenDialog();
})
var selectedFile = fileChooser.getSelectedFile();

The above code creates a file chooser dialog and attaches it to the button. The button click
would open the file chooser dialog. The selected file is returned through the get file method
chosen.

Display:
JTabbedPane

The JTabbedPane is another beneficial component that lets the user switch between tabs in an
application. It is a handy utility as it allows users to browse more content without navigating to
different pages.
Syntax:
JTabbedPane jtabbedPane = new JTabbedPane();
jtabbedPane.addTab(“Tab_1”, new JPanel());
jtabbedPane.addTab(“Tab_2”, new JPanel());
The above code creates a two-tabbed panel with headings Tab_1 and Tab_2.

Display:

JSlider
The JSlider component displays a slider that the user can drag to change its value. The
constructor takes three arguments: minimum, maximum, and initial.
Syntax:
JSlider volumeSlider = new JSlider(0, 100, 20);
var volumeLevel = volumeSlider.getValue();

The above code makes a slider from 0 to 100 with an initial value set to 20. The value
specified by the user is returned by the getValue method.

Display:

Difference between AWT and Swing


AWT (Abstract Window Toolkit) and Swing are both Java GUI (Graphical User Interface) toolkits
that provide a set of classes and components to create desktop applications. The main
differences between AWT and Swing are listed below:
CONATINERS OF SWING:
Containers are an integral part of SWING GUI components. A container provides a space where
a component can be located. A Container in AWT is a component itself and it provides the
capability to add a component to itself. Following are certain noticable points to be considered.
 Sub classes of Container are called as Container. For example, JPanel, JFrame and
JWindow.
 Container can add only a Component to itself.
 A default layout is present in each container which can be overridden
using setLayout method.

SWING Containers
Following is the list of commonly used containers while designed GUI using SWING.
1. Panel: JPanel is the simplest container. It provides space in which any other component
can be placed, including other panels.
2. Frame: A JFrame is a top-level window with a title and a border.
3. Window: A JWindow object is a top-level window with no borders and no menubar.
LAYOUT MANAGERS:
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


Border.java
Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.

Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout
with the given rows and columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor


The GridLayout() constructor creates only one row. The following example shows the usage of
the parameterless constructor.
Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after
another (in a flow). It is the default layout of the applet or panel.

Fields of FlowLayout class

1. public static final int LEFT


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

Constructors of FlowLayout class

1. FlowLayout(): creates a flow layout with centered alignment and a default 5


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

Example of FlowLayout class: Using FlowLayout() constructor


Java CardLayout
The Java CardLayout class manages the components in such a manner that only
one component is visible at a time. It treats each component as a card that is why it
is known as CardLayout.

Constructors of CardLayout Class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.

Commonly Used Methods of CardLayout Class

o public void next(Container parent): is used to flip to the next card of the
given container.
o public void previous(Container parent): is used to flip to the previous
card of the given container.
o public void first(Container parent): is used to flip to the first card of the
given container.
o public void last(Container parent): is used to flip to the last card of the
given container.
o public void show(Container parent, String name): is used to flip to the
specified card with the given name.

Example of CardLayout Class: Using Default Constructor


The following program uses the next() method to move to the next card of the
container.
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or
along their baseline.

The components may not be of the same size. Each GridBagLayout object maintains
a dynamic, rectangular grid of cells. Each component occupies one or more cells
known as its display area. Each component associates an instance of
GridBagConstraints. With the help of the constraints object, we arrange the
component's display area on the grid. The GridBagLayout manages each
component's minimum and preferred sizes in order to determine the component's
size. GridBagLayout components are also arranged in the rectangular grid but can
have many different sizes and can occupy multiple rows or columns.
Constructor

GridBagLayout(): The parameterless constructor is used to create a grid


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

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


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

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

Event Processing in Java


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

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

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

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

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

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

o Events
o Events Sources
o Events Listeners

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

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

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

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

1. public void addTypeListener (TypeListener e1)

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

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

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


xception

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

A source should contain a method that unregisters a specific type of event from the
listener if not needed. Below is an example of the method that will remove the
event from the listener.

1. public void removeTypeListener(TypeListener e2?)

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

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

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

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

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

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

The Foreground Events:


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

The Background Events :

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

To handle these events, we need an event handling mechanism that provides


control over the events and responses.

The Delegation Model


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

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

o It is easy to learn and implement


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

Let's implement it with an example:

Java Program to Implement the Event Deligation Model


The below is a Java program to handle events implementing the event deligation
model:
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging mouse et
java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

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


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
3) Java event handling by anonymous class
Handling Keyboard
Events

A user interacts with the application by pressing either keys on the keyboard or by using
mouse. A programmer should know which key the user has pressed on the keyboard or
whether the mouse is moved, pressed, or released. These are also called ‘events’. Knowing
these events will enable the programmer to write his code according to the key pressed or
mouse event.

KeyListener interface of java.awt.event package helps to know which key is pressed or


released by the user. It has 3 methods

1. Public void keyPressed(KeyEvent ke): This method is called when a key is pressed on
the keyboard. This include any key on the keyboard along with special keys like
function keys, shift, alter, caps lock, home, end etc.

2. Public void keyTyped(keyEvent ke) : This method is called when a key is typed on the
keyboard. This is same as keyPressed() method but this method is called when general
keys like A to Z or 1 to 9 etc are typed. It cannot work with special keys.

3. Public void keyReleased(KeyEvent ke): this method is called when a key is release.

KeyEvent class has the following methods to know which key is typed by the user.

1. Char getKeyChar(): this method returns the key name (or character) related to the key
pressed or released.
2. Int getKeyCode(): this method returns an integer number which is the value of the
key presed by the user.

The follwing are the key codes for the keys on the keyboard. They are defined as
constants in KeyEvent class. Remember VK represents Virtual Key.

 To represent keys from a to z : VK_A to VK_Z.


 To represent keys from 1 to 9: VK_0 to VK_9.
 To represent keys from F1 to F12: VK_F1 to VK_F12.
 To represent home, end : VK_HOME, VK_END.
 To represent PageUp, PageDown: VK_PAGE_UP, VK_PAGE_DOWN
 To represent Insert, Delete: VK_INSERT, VK_DELETE
 To represent caps lock: VK_CAPS_LOCK
 To represent alter key: VK_ALT
 To represent Control Key: VK_CONTROL
 To represent shift: VK_SHIFT
 To represent tab key: VK_TAB
 To represent arrow keys: VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN
 To represent Escape key: VK_ESCAPE
 Static String getKeyText(int keyCode); this method returns a string describing the
keyCode such as HOME, F1 or A.
Program: to trap a key which is pressed on the keyboard and display
its name in the text area.

package com.myPack;

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

class KeyBoardEvents extends JFrame implements KeyListener

{
private static final Font Font =
null; Container c;

JTextArea a;

String str = "


";
KeyBoardEvents(
)
{
c=getContentPane();
a = new JTextArea("Press a Key");

a.setFont(new Font ("Times New Roman", Font.BOLD,30));


c.add(a);
a.addKeyListener(this
);
}
public void keyPressed(KeyEvent ke)

{
int keycode = ke.getKeyCode();
if(keycode == KeyEvent.VK_F1) str += "F1 Key";
if(keycode == KeyEvent.VK_F2) str += "F2 Key";
if(keycode == KeyEvent.VK_F3) str += "F3 Key";
if(keycode == KeyEvent.VK_PAGE_UP) str += "Page
UP"; if(keycode == KeyEvent.VK_PAGE_DOWN) str +=
"Page Down"; a.setText(str);
str =" " ;
}
public void keyRelease(KeyEvent ke)

{
}
public void keyTyped(KeyEvent ke)
{
}
public static void main(String args[])

{
KeyBoardEvents kbe = new
KeyBoardEvents();
kbe.setSize(400,400);
kbe.setVisible(true);
kbe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void keyReleased(KeyEvent
arg0) {

// TODO Auto-generated method stub

Output:

Handling Mouse Events


The user may click, release, drag, or move a mouse while interacting with athe
application. If the programmer knows what the user has done, he can write the code
according to the mouse events. To trap the mouse events, MouseListener and
MouseMotionListener interfaces of java.awt.event package are use.

MouseListener interface has the following methods.

1. void mouseClicked(MouseEvent e); void MouseClicked this method is invoked


when the mouse button has been clicked(pressed and released) on a component.
2. void mouseEntered(MouseEvent e): this method is invoked when the mouse
enters a component.
3. void mouseExited(MouseEvent e): this method is invoked when the mouse exits a
component
4. void mousePressed(MouseEvent e): this method is invoked when a mouse
button has been pressed on a component.
5. void mouseRelease(MouseEvent e): this method is invoked when a mouse
button has been released ona component.

MouseMotionListener interface has the following methods.

1. void mouseDragged(MouseEvent e): this method is invoked when a mouse button is


pressed on a component and then dragged.
2. void mouseMoved(MouseEvent e): this method is invoked when a mouse cursor
has been moved onto a component and then dragged.
The MouseEVent class has the following methods

1. int getButton(): this method returns a value representing a mouse button, when
it is clicked it retursn 1 if left button is clicked, 2 if middle button, and 3 if right
button is clicked.
2. int getX(); this method returns the horizontal x position of the event relative to
the source component.
3. int getY(); this method returns the vertical y postion of the event relative to the
source component.

Program to create a text area and display the mouse event when the
button on the mouse is clicke, when mouse is moved, etc. is done by
user.

package com.myPack;

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

class MouseEvents extends JFrame implements MouseListener, MouseMotionListener

{
String str =" ";
JTextArea ta;
Container c;
int x, y;

MouseEvents()
{
c=getContentPane();
c.setLayout(new FlowLayout());

ta = new JTextArea("Click the mouse or move it", 5, 20);


ta.setFont(new Font("Arial", Font.BOLD, 30));
c.add(ta);

ta.addMouseListener(this);
ta.addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)

{
int i = me.getButton();
if(i==1)

str+= "Clicked Button : Left";


else if(i==2)

str+= "Clicked Button : Middle";


else if(i==3)

str+= "Clicked Button : Right";


this.display();

}
public void mouseEntered(MouseEvent me)

{
str += "Mouse Entered";
this.display();

}
public void mouseExited(MouseEvent me)

{
str += "Mouse Exited";
this.display();

}
public void mousePressed(MouseEvent me)

{
x = me.getX();
y= me.getY();
str += "Mouse Pressed at :" +x + "\t" + y;
this.display();

}
public void mouseReleased(MouseEvent me)

{
x = me.getX();
y= me.getY();
str += "Mouse Released at :" +x + "\t" + y;
this.display();

}
public void mouseDragged(MouseEvent me)

{
x = me.getX();
y= me.getY();
str += "Mouse Dragged at :" +x + "\t" + y;
this.display();

}
public void mouseMoved(MouseEvent me)

{
x = me.getX();
y= me.getY();
str += "Mouse Moved at :" +x + "\t" + y;
this.display();

public void display()

{
ta.setText(str);
str=" ";
}

public static void main(String args[])

{
MouseEvents mes = new MouseEvents();
mes.setSize(400,400);
mes.setVisible(true);
mes.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}

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

Pros of using Adapter classes:

o It assists the unrelated classes to work combinedly.


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

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


java.awt.dnd and javax.swing.event packages. The Adapter classes with their
corresponding listener interfaces are given below.
Java WindowAdapter Example
In the following example, we are implementing the WindowAdapter class of AWT
and one its methods windowClosing() to close the frame window.
Java MouseAdapter Example
In the following example, we are implementing the MouseAdapter class. The
MouseListener interface is added into the frame to listen the mouse event in the
frame.
Java MouseMotionAdapter Example
In the following example, we are implementing the MouseMotionAdapter class and
its different methods to listen to the mouse motion events in the Frame window.
Java KeyAdapter Example
In the following example, we are implementing the KeyAdapter class and its
method.
Java Inner Classes (Nested Classes)
Java inner class or nested class is a class that is declared inside the class or
interface.

We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.

Additionally, it can access all the members of the outer class, including private data
members and methods.

Syntax of Inner class


1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

Advantage of Java inner classes


There are three advantages of inner classes in Java. They are as follows:

1. Nested classes represent a particular type of relationship that is it can


access all the members (data members and methods) of the outer
class, including private.
2. Nested classes are used to develop more readable and maintainable
code because it logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.

Need of Java Inner class


Sometimes users need to program a class in such a way so that no other class can
access it. Therefore, it would be better if you include it within other classes.

If all the class objects are a part of the outer object then it is easier to nest that
class inside the outer class. That way all the outer class can access all the objects of
the inner class.

Difference between nested class and inner class in Java


An inner class is a part of a nested class. Non-static nested classes are known as
inner classes.

Types of Nested classes


There are two types of nested classes non-static and static nested classes. The non-
static nested classes are also known as inner classes.

o Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class
Java Anonymous inner class
Java anonymous inner class is an inner class without a name and for which only a
single object is created. An anonymous inner class can be useful when making an
instance of an object with certain "extras" such as overloading methods of a class or
interface, without having to actually subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in
Java. It should be used if you have to override a method of class or interface. Java
Anonymous inner class can be created in two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class

Internal working of given code

1. Person p=new Person(){


2. void eat(){System.out.println("nice fruits");}
3. };
1. A class is created, but its name is decided by the compiler, which extends the
Person class and provides the implementation of the eat() method.
2. An object of the Anonymous class is created that is referred to by 'p,' a
reference variable of Person type.
Internal working of given code
It performs two main tasks behind this code:

1. Eatable p=new Eatable(){


2. void eat(){System.out.println("nice fruits");}
3. };
1. A class is created, but its name is decided by the compiler, which implements
the Eatable interface and provides the implementation of the eat() method.
2. An object of the Anonymous class is created that is referred to by 'p', a
reference variable of the Eatable type.
Java Applet
Applet is a special type of program that is embedded in the webpage to generate
the dynamic content. It runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.

Drawback of Applet

o Plugin is required at client browser to execute applet.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class
provides 1 life cycle methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?


Java Plug-in software.

How to run an Applet?


There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


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

Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet
tag in comment and compile it. After that run it by: appletviewer First.java. Now
Html file is not required but it is for testing purpose only.
SECURITY ISSUES OF APPLET:

Every browser implements security policies to keep applets from


compromising system security. This section describes the security policies that current
browsers adhere to. However, the implementation of the security policies differs from
browser to browser. Also, security policies are subject to change. For example, if a
browser is developed for use only in trusted environments, then its security policies
will likely be much more lax than those described here.

Current browsers impose the following restrictions on any applet that is loaded over
the network:

 An applet cannot load libraries or define native methods.


 It cannot ordinarily read or write files on the host that's executing it.
 It cannot make network connections except to the host that it came from.
 It cannot start any program on the host that's executing it.
 It cannot read certain system properties.
 Windows that an applet brings up look different than windows that an
application brings up.

Each browser has a SecurityManager object that implements its security policies.
When a SecurityManager detects a violation, it throws a SecurityException. Your
applet can catch this SecurityException and react appropriately.
APPLETS & APPLICATIONS:
Java Application is just like a Java program that runs on an underlying operating
system with the support of a virtual machine. It is also known as an application program.
The graphical user interface is not necessary to execute the java applications, it can be
run with or without it.
Java Applet is a Java program that can be embedded into a web page. It runs
inside the web browser and works on the client-side. An applet is embedded in an HTML
page using the APPLET or OBJECT tag and hosted on a web server. Applets are used to
make the website more dynamic and entertaining.

Parameters Java Application Java Applet

Applications are just like a Applets are small Java programs


Java program that can be that are designed to be included
Definition executed independently with the HTML web document.
without using the web They require a Java-enabled web
browser. browser for execution.

The application program The applet does not require the


main ()
requires a main() method for main() method for its execution
method
its execution. instead init() method is required.

The “javac” command is


Applet programs are compiled
used to compile application
with the “javac” command and run
Compilation programs, which are then
using either the “appletviewer”
executed using the “java”
command or the web browser.
command.

Java application programs


Applets don’t have local disk and
File access have full access to the local
network access.
file system and network.

Applications can access all Applets can only access browser-


Access level kinds of resources available specific services. They don’t have
on the system. access to the local system.

First and foremost, the


installation of a Java The Java applet does not need to
Installation
application on the local be installed beforehand.
computer is required.
Parameters Java Application Java Applet

Applications can execute the


Applets cannot execute programs
Execution programs from the local
from the local machine.
system.

An application program is An applet program is needed to


Program needed to perform some perform small tasks or part of
tasks directly for the user. them.

It cannot start on its own, but it


It cannot run on its own; it
Run can be executed using a Java-
needs JRE to execute.
enabled web browser.

Connection Connectivity with other It is unable to connect to other


with servers servers is possible. servers.

Read and It supports the reading and It does not support the reading
Write writing of files on the local and writing of files on the local
Operation computer. computer.

Application can access the Executed in a more restricted


system’s data and resources environment with tighter security.
Security
without any security They can only use services that
limitations. are exclusive to their browser.

Java applications are self-


Applet programs cannot run on
contained and require no
Restrictions their own, necessitating the
additional security because
maximum level of security.
they are trusted.
Parameter in Applet
The Applet tag allows you to pass parameters to your applet. To retrieve a
parameter , use the getParameter() method. It returns the value of the specified
parameter in the form of a String object. Thus, for numeric and Boolean values, you
need to convert their string representations into their internal formats.

Syntax:
Create a Swing Applet
The second type of program that commonly uses Swing is the applet. Swing-based
applets are similar to AWT-based applets, but with an important difference: A Swing applet
extends JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes
all of the functionality found in Applet and adds support for Swing. JApplet is a top-level
Swing container, which means that it is not derived from JComponent. Because JApplet is a
top-level container, it includes the various panes described earlier. This means that all
components are added to JApplet’s content pane in the same way that components are added
to JFrame’s content pane.
Swing applets use the same four life-cycle methods: init( ), start( ), stop( ), and destroy(
). Of course, you need override only those methods that are needed by your applet. Painting is
accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally
override the paint( ) method.

// A simple Swing-based applet

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

/*

This HTML can be used to launch the applet:

<applet code="MySwingApplet" width=220 height=90> </applet>

*/
public class MySwingApplet extends JApplet { JButton jbtnAlpha;

JButton jbtnBeta;

JLabel jlab;

// Initialize the applet.


public void init() {

try {

SwingUtilities.invokeAndWait(new Runnable () { public void run()


{

makeGUI(); // initialize the GUI

});

} catch(Exception exc) {

System.out.println("Can’t create because of "+ exc);

}
//This applet does not need to override start(), stop(),

//or destroy().

//Set up and initialize the GUI.

private void makeGUI() {

//Set the applet to use flow layout.


setLayout(new FlowLayout());

//Make two buttons.

jbtnAlpha = new JButton("Alpha"); jbtnBeta = new JButton("Beta");

Add action listener for Alpha. jbtnAlpha.addActionListener(new


ActionListener() {
public void actionPerformed(ActionEvent le) { jlab.setText("Alpha
was pressed.");

});

//Add action listener for Beta.


jbtnBeta.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent le) { jlab.setText("Beta


was pressed.");

});
//Add the buttons to the content pane.
add(jbtnAlpha);

add(jbtnBeta);

//Create a text-based label.

jlab = new JLabel("Press a button.");

// Add the label to the content pane.


add(jlab);

}
There are two important things to notice about this applet.
First, MySwingApplet extends JApplet. As explained, all Swing-based applets
extend JApplet rather than Applet. Second, the init( ) method initializes the
Swing components on the event dispatching thread by setting up a call
to makeGUI( ). Notice that this is accomplished through the use
of invokeAndWait( ) rather than invokeLater( ). Applets must
use invokeAndWait( ) because the init( ) method must not return until the entire
initialization process has been completed. In essence, the start( ) method cannot be
called until after initialization, which means that the GUI must be fully
constructed.

Inside makeGUI( ), the two buttons and label are created, and the action listeners
are added to the buttons. Finally, the components are added to the content pane.
Although this example is quite simple, this same general approach must be used
when building any Swing GUI that will be used by an applet.
Painting in Swing

Although the Swing component set is quite powerful, you are not limited to using
it because Swing also lets you write directly into the display area of a frame, panel,
or one of Swing’s other components, such as JLabel. Although many (perhaps
most) uses of Swing will not involve drawing directly to the surface of a
component, it is available for those applications that need this capability. To write
output directly to the surface of a component, you will use one or more drawing
methods defined by the AWT, such as drawLine( ) or drawRect( ).

Painting Fundamentals

Swing’s approach to painting is built on the original AWT-based mechanism, but


Swing’s implementation offers more finally grained control. Before examining the
specifics of Swing-based painting, it is useful to review the AWT-based
mechanism that underlies it.

The AWT class Component defines a method called paint( ) that is used to draw
output directly to the surface of a component. For the most part, paint( ) is not
called by your program. (In fact, only in the most unusual cases should it ever be
called by your program.) Rather, paint( ) is called by the run-time system
whenever a component must be rendered. This situation can occur for several
reasons. For example, the window in which the component is displayed can be
overwritten by another window and then uncovered. Or, the window might be
minimized and then restored. The paint( ) method is also called when a program
begins running. When writing AWT-based code, an application will
override paint( ) when it needs
to write output directly to the surface of the component.

Because JComponent inherits Component, all Swing’s lightweight components


inherit the paint( ) method. However, you will not override it to paint directly to
the surface of a component. The reason is that Swing uses a bit more sophisticated
approach to painting that involves three distinct
methods: paintComponent( ), paintBorder( ), and paintChildren( ). These
methods paint the indicated portion of a component and divide the painting process
into its three distinct, logical actions. In a lightweight component, the original
AWT method paint( ) simply executes calls to these methods, in the order just
shown.

To paint to the surface of a Swing component, you will create a subclass of the
component and then override its paintComponent( ) method. This is the method
that paints the interior of the component. You will not normally override the other
two painting methods. When overriding paintComponent( ), the first thing you
must do is call super.paintComponent( ), so that the superclass portion of the
painting process takes place. (The only time this is not required is when you are
taking complete, manual control over how a component is displayed.) After that,
write the output that you want to display. The paintComponent( ) method is
shown here:

protected void paintComponent(Graphics g)

The parameter g is the graphics context to which output is written.


To cause a component to be painted under program control, call repaint( ). It
works in Swing just as it does for the AWT. The repaint( ) method is defined
by Component. Calling it causes the system to call paint( ) as soon as it is
possible to do so. Because painting is a time-consuming operation, this mechanism
allows the run-time system to defer painting momentarily until some higher-
priority task has completed, for example. Of course, in Swing the call
to paint( ) results in a call to paintComponent( ). Therefore, to output to the
surface of a component, your program will store the output
until paintComponent( ) is called. Inside the overridden paintComponent( ), you
will draw the stored output.

Compute the Paintable Area

When drawing to the surface of a component, you must be careful to restrict your
output to the area that is inside the border. Although Swing automatically clips any
output that will exceed the boundaries of a component, it is still possible to paint
into the border, which will then get overwritten when the border is drawn. To
avoid this, you must compute the paintable area of the component. This is the area
defined by the current size of the component minus the space used by the border.
Therefore, before you paint to a component, you must obtain the width of the
border and then adjust your drawing accordingly.

To obtain the border width, call getInsets( ), shown here: Insets getInsets( )
This method is defined by Container and overridden by JComponent. It returns
an Insets object that contains the dimensions of the border. The inset values can be
obtained by using these fields:

int top; int bottom; int left;

int right;

These values are then used to compute the drawing area given the width and the
height of the component. You can obtain the width and height of the component by
calling getWidth( ) and getHeight( ) on the component. They are shown here:

int getWidth( ) int getHeight( )

By subtracting the value of the insets, you can compute the usable width and height
of the component.

A Paint Example
Here is a program that puts into action the preceding discussion. It creates a class
called PaintPanel that extends JPanel. The program then uses an object of that
class to display lines whose endpoints have been generated randomly.
// Paint lines to a panel.

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


import java.util.*;

//This class extends JPanel. It overrides

//the paintComponent() method so that random

//lines are plotted in the panel.

class PaintPanel extends JPanel {

Insets ins; // holds the panel’s insets

Random rand; // used to generate random numbers

// Construct a panel.
PaintPanel() {

// Put a border around the panel.


setBorder(
BorderFactory.createLineBorder(Color.RED, 5));

rand = new Random();

// Override the paintComponent() method.


protected void paintComponent(Graphics g) {

// Always call the superclass method first.


super.paintComponent(g);

int x, y, x2, y2;

// Get the height and width of the component.


int height = getHeight();

int width = getWidth();

//Get the insets.


ins = getInsets();

//Draw ten lines whose endpoints are randomly generated.


for(int i=0; i < 10; i++) {
}
//Obtain random coordinates that define

//the endpoints of each line.


x = rand.nextInt(width-ins.left);

y = rand.nextInt(height-ins.bottom); x2 = rand.nextInt(width-
ins.left); y2 = rand.nextInt(height-ins.bottom);

// Draw the line.


g.drawLine(x, y, x2, y2);
}

// Demonstrate painting directly onto a panel.


class PaintDemo {

JLabel jlab;

PaintPanel pp;

PaintDemo() {

//Create a new JFrame container.


JFrame jfrm = new JFrame("Paint Demo");

//Give the frame an initial size.

jfrm.setSize(200, 150);
//Terminate the program when the user closes the application.

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create the panel that will be painted.

pp = new PaintPanel();

//Add the panel to the content pane. Because the default

//border layout is used, the panel will automatically be

//sized to fit the center region.

jfrm.add(pp);

// Display the frame.


jfrm.setVisible(true);
}

public static void main(String args[]) {

// Create the frame on the event dispatching thread.


SwingUtilities.invokeLater(new Runnable() {

public void run() { new PaintDemo();

}
});

}
Let’s examine this program closely. The PaintPanel class extends JPanel. JPanel is one of
Swing’s lightweight containers, which means that it is a component that can be added to
the content pane of a JFrame. To handle painting, PaintPanel overrides
the paintComponent( ) method. This enables PaintPanel to write directly to the surface of
the component when painting takes place. The size of the panel is not specified because the
program uses the default border layout and the panel is added to the center. This results in
the panel being sized to fill the center. If you change the size of the window, the size of the
panel will be adjusted accordingly.

Notice that the constructor also specifies a 5-pixel wide, red border. This is
accomplished by setting the border by using the setBorder( ) method, shown here:

void setBorder(Border border)

Border is the Swing interface that encapsulates a border. You can obtain a border
by calling one of the factory methods defined by the BorderFactory class. The
one used in the program is createLineBorder( ), which creates a simple line
border. It is shown here:

static Border createLineBorder(Color clr, int width)


Here, clr specifies the color of the border and width specifies its width in pixels.

Inside the override of paintComponent( ), notice that it first


calls super.paintComponent( ). As explained, this is necessary to ensure that the
component is properly drawn. Next, the width and height of the panel are obtained
along with the insets. These values are used to ensure the lines lie within the
drawing area of the panel. The drawing area is the overall width and height of a
component less the border width. The computations are designed to work with
differently sized PaintPanels and borders. To prove this, try changing the size of
the window. The lines will still all lie within the borders of the panel.
The PaintDemo class creates a PaintPanel and then adds the panel to the content
pane. When the application is first displayed, the
overridden paintComponent( ) method is called, and the lines are drawn. Each
time you resize or hide and restore the window, a new set of lines are drawn. In all
cases, the lines fall within the paintable area.
Exploring Swing
The previous chapter described several of the core concepts relating to Swing and
showed the general form of both a Swing application and a Swing applet. This
chapter continues the discussion of Swing by presenting an overview of several
Swing components, such as buttons, check boxes, trees, and tables. The Swing
components provide rich functionality and allow a high level of customization.
Because of space limitations, it is not possible to describe all of their features and
attributes. Rather, the purpose of this overview is to give you a feel for the
capabilities of the Swing component set.
The Swing component classes described in this chapter are shown here:
JButton
JList
JTable
JCheckBox
JRadioButton
JTextField
JComboBox
JScrollPane
JToggleButton
JLabel
JTabbedPane
JTree
These components are all lightweight, which means that they are all derived from

JComponent.

Also discussed is the ButtonGroup class, which encapsulates a mutually exclusive


set of Swing buttons, and ImageIcon, which encapsulates a graphics image. Both
are defined by Swing and packaged in javax.swing.
One other point: The Swing components are demonstrated in applets because the
code for an applet is more compact than it is for a desktop application. However,
the same techniques apply to both applets and applications.

JLabel and ImageIcon

JLabel is Swing’s easiest-to-use component. It creates a label and was introduced


in the preceding chapter. Here, we will look at JLabel a bit more
closely. JLabel can be used to display text and/or an icon. It is a passive
component in that it does not respond to user input. JLabel defines several
constructors. Here are three of them:

JLabel(Icon icon) JLabel(String str)


JLabel(String str, Icon icon, int align)
Here, str and icon are the text and icon used for the label. The align argument
specifies the horizontal alignment of the text and/or icon within the dimensions of
the label. It must be one of the following values: LEFT, RIGHT,
CENTER, LEADING, or TRAILING. These constants are defined in
the SwingConstants interface, along with several others used by the Swing
classes.

Notice that icons are specified by objects of type Icon, which is an interface
defined by Swing. The easiest way to obtain an icon is to use
the ImageIcon class. ImageIcon implements Icon and encapsulates an image.
Thus, an object of type ImageIcon can be passed as an argument to
the Icon parameter of JLabel’s constructor. There are several ways to provide the
image, including reading it from a file or downloading it from a URL. Here is
the ImageIcon constructor used by the example in this section:

ImageIcon(String filename)
It obtains the image in the file named filename.

The icon and text associated with the label can be obtained by the following
methods:

Icon getIcon( ) String getText( )

The icon and text associated with a label can be set by these methods:

void setIcon(Icon icon) void setText(String str)

Here, icon and str are the icon and text, respectively. Therefore, using setText( ) it
is possible to change the text inside a label during program execution.
The following applet illustrates how to create and display a label containing both
an icon and a string. It begins by creating an ImageIcon object for the
file hourglass.png, which depicts an hourglass. This is used as the second
argument to the JLabel constructor. The first and last arguments for
the JLabel constructor are the label text and the alignment. Finally, the label is
added to the content pane.

// Demonstrate JLabel and ImageIcon.


import java.awt.*;

import javax.swing.*; /*

<applet code="JLabelDemo" width=250 height=200> </applet>

*/
public class JLabelDemo extends JApplet {

public void init() { try {

SwingUtilities.invokeAndWait( new Runnable() {

public void run() { makeGUI();

);
} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

private void makeGUI() {

// Create an icon.

ImageIcon ii = new ImageIcon("hourglass.png");


// Create a label.

JLabel jl = new JLabel("Hourglass", ii, JLabel.CENTER);

// Add the label to the content pane.


add(jl);

JTextField
JTextField is the simplest Swing text component. It is also probably its most
widely used text component. JTextField allows you to edit one line of text. It is
derived from JTextComponent, which provides the basic functionality common
to Swing text components. JTextField uses the Document interface for its model.
Three of JTextField’s constructors are shown here:
JTextField(int cols) JTextField(String str, int cols) JTextField(String str)

Here, str is the string to be initially presented, and cols is the number of columns in
the text field. If no string is specified, the text field is initially empty. If the number
of columns is not specified, the text field is sized to fit the specified string.
JTextField generates events in response to user interaction. For example,
an ActionEvent is fired when the user presses enter. A CaretEvent is fired each
time the caret (i.e., the cursor) changes position. (CaretEvent is packaged
in javax.swing.event.) Other events are also possible. In many cases, your
program will not need to handle these events. Instead, you will simply obtain the
string currently in the text field when it is needed. To obtain the text currently in
the text field, call getText( ).

The following example illustrates JTextField. It creates a JTextField and adds it


to the content pane. When the user presses enter, an action event is generated. This
is handled by displaying the text in the status window.

// Demonstrate JTextField.
import java.awt.*;

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

<applet code="JTextFieldDemo" width=300 height=50> </applet>

*/

public class JTextFieldDemo extends JApplet { JTextField jtf;

public void init() { try {


SwingUtilities.invokeAndWait( new Runnable() {

public void run() { makeGUI();

);

} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

private void makeGUI() {

//Change to flow layout.


setLayout(new FlowLayout());

//Add text field to content pane.

jtf = new JTextField(15); add(jtf);

jtf.addActionListener(new ActionListener() { public void


actionPerformed(ActionEvent ae) {
//Show text when user presses ENTER.
showStatus(jtf.getText());

});
The Swing Buttons
Swing defines four types of buttons: JButton, JToggleButton, JCheckBox,
and JRadioButton. All are subclasses of the AbstractButton class, which
extends JComponent. Thus, all buttons share a set of common traits.
AbstractButton contains many methods that allow you to control the behavior of
buttons. For example, you can define different icons that are displayed for the
button when it is disabled, pressed, or selected. Another icon can be used as
a rollover icon, which is displayed when the mouse is positioned over a button.
The following methods set these icons:

void setDisabledIcon(Icon di) void setPressedIcon(Icon pi) void


setSelectedIcon(Icon si) void setRolloverIcon(Icon ri)

Here, di, pi, si, and ri are the icons to be used for the indicated purpose.

The text associated with a button can be read and written via the following
methods:

String getText( )

void setText(String str)

Here, str is the text to be associated with the button.


The model used by all buttons is defined by the ButtonModel interface. A button
generates an action event when it is pressed. Other events are possible. Each of the
concrete button classes is examined next.

JButton
The JButton class provides the functionality of a push button. You have already
seen a simple form of it in the preceding chapter. JButton allows an icon, a string,
or both to be associated with the push button. Three of its constructors are shown
here:

JButton(Icon icon) JButton(String str) JButton(String str, Icon icon)

Here, str and icon are the string and icon used for the button.

When the button is pressed, an ActionEvent is generated. Using


the ActionEvent object passed to the actionPerformed( ) method of the
registered ActionListener, you can obtain the action command string associated
with the button. By default, this is the string displayed inside the button. However,
you can set the action command by calling setActionCommand( ) on the button.
You can obtain the action command by calling getActionCommand( ) on the
event object. It is declared like this:

String getActionCommand( )

The action command identifies the button. Thus, when using two or more buttons
within the same application, the action command gives you an easy way to
determine which button was pressed.
In the preceding chapter, you saw an example of a text-based button. The
following demonstrates an icon-based button. It displays four push buttons and a
label. Each button displays an icon that represents a timepiece. When a button is
pressed, the name of that timepiece is displayed in the label.

// Demonstrate an icon-based JButton.


import java.awt.*;

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


<applet code="JButtonDemo" width=250 height=750> </applet>

*/

public class JButtonDemo extends JApplet implements


ActionListener {

JLabel jlab;

public void init() { try {

SwingUtilities.invokeAndWait( new Runnable() {

public void run() { makeGUI();

);

} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

}
}

private void makeGUI() {

Change to flow layout. setLayout(new FlowLayout());

Add buttons to content pane.

ImageIcon hourglass = new ImageIcon("hourglass.png"); JButton jb


= new JButton(hourglass); jb.setActionCommand("Hourglass");
jb.addActionListener(this);

add(jb);

ImageIcon analog = new ImageIcon("analog.png"); jb = new


JButton(analog); jb.setActionCommand("Analog Clock");
jb.addActionListener(this);

add(jb);

ImageIcon digital = new ImageIcon("digital.png"); jb = new


JButton(digital); jb.setActionCommand("Digital Clock");
jb.addActionListener(this);
add(jb);
ImageIcon stopwatch = new ImageIcon("stopwatch.png"); jb = new
JButton(stopwatch); jb.setActionCommand("Stopwatch");
jb.addActionListener(this);

add(jb);
// Create and add the label to content pane.
jlab = new JLabel("Choose a Timepiece"); add(jlab);

// Handle button events.

public void actionPerformed(ActionEvent ae) { jlab.setText("You


selected " + ae.getActionCommand());

JToggleButton
A useful variation on the push button is called a toggle button. A toggle button
looks just like a push button, but it acts differently because it has two states:
pushed and released. That is, when you press a toggle button, it stays pressed rather
than popping back up as a regular push button does. When you press the toggle
button a second time, it releases (pops up). Therefore, each time a toggle button is
pushed, it toggles between its two states.
Toggle buttons are objects of
the JToggleButton class. JToggleButton implements AbstractButton. In
addition to creating standard toggle buttons, JToggleButton is a superclass for two
other Swing components that also represent two-state controls. These
are JCheckBox and JRadioButton, which are described later in this chapter.
Thus, JToggleButton defines the basic functionality of all two-state components.
JToggleButton defines several constructors. The one used by the example in this
section is shown here:

JToggleButton(String str)
This creates a toggle button that contains the text passed in str. By default, the
button is in the off position. Other constructors enable you to create toggle buttons
that contain images, or images and text.

JToggleButton uses a model defined by a nested class


called JToggleButton.Toggle-ButtonModel. Normally, you won’t need to
interact directly with the model to use a standard toggle button.
Like JButton, JToggleButton generates an action event each time it is pressed.
Unlike JButton, however, JToggleButton also generates an item event. This event
is used by those components that support the concept of selection. When
a JToggleButton is pressed in, it is selected. When it is popped out, it is
deselected.
To handle item events, you must implement the ItemListener interface. Recall
from Chapter 24, that each time an item event is generated, it is passed to
the itemStateChanged( ) method defined by ItemListener.
Inside itemStateChanged( ), the getItem( ) method can be called on
the ItemEvent object to obtain a reference to the JToggleButton instance that
generated the event. It is shown here:

Object getItem( )
A reference to the button is returned. You will need to cast this reference
to JToggleButton. The easiest way to determine a toggle button’s state is by
calling the isSelected( ) method
(inherited from AbstractButton) on the button that generated the event. It is
shown here: boolean isSelected( )

It returns true if the button is selected and false otherwise.

Here is an example that uses a toggle button. Notice how the item listener works. It
simply calls isSelected( ) to determine the button’s state.

// Demonstrate JToggleButton.
import java.awt.*;

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

<applet code="JToggleButtonDemo" width=200 height=80> </applet>

*/

public class JToggleButtonDemo extends JApplet {

JLabel jlab;

JToggleButton jtbn;

public void init() { try {


SwingUtilities.invokeAndWait( new Runnable() {

public void run() { makeGUI();

);
} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

private void makeGUI() {

//Change to flow layout.


setLayout(new FlowLayout());

//Create a label.

jlab = new JLabel("Button is off.");

// Make a toggle button.


jtbn = new JToggleButton("On/Off");

// Add an item listener for the toggle button.


jtbn.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent ie)


{ if(jtbn.isSelected())

jlab.setText("Button is on."); else

jlab.setText("Button is off.");

});

// Add the toggle button and label to the content pane.


add(jtbn);

add(jlab);

}
The output from the toggle button example is shown here:
Check Boxes

The JCheckBox class provides the functionality of a check box. Its immediate
superclass is JToggleButton, which provides support for two-state buttons, as just
described. JCheckBox defines several constructors. The one used here is

JCheckBox(String str)

It creates a check box that has the text specified by str as a label. Other
constructors let you specify the initial selection state of the button and specify an
icon.

When the user selects or deselects a check box, an ItemEvent is generated. You
can obtain a reference to the JCheckBox that generated the event by
calling getItem( ) on the
ItemEvent passed to the itemStateChanged( ) method defined by ItemListener.
The easiest way to determine the selected state of a check box is to call isSelected(
) on the JCheckBox instance.

The following example illustrates check boxes. It displays four check boxes and a
label. When the user clicks a check box, an ItemEvent is generated. Inside
the itemStateChanged( ) method, getItem( ) is called to obtain a reference to
the JCheckBox object that generated the event. Next, a call
to isSelected( ) determines if the box was selected or cleared.
The getText( ) method gets the text for that check box and uses it to set the text
inside the label.

// Demonstrate JCheckbox.
import java.awt.*; import java.awt.event.*; import javax.swing.*;

/*

<applet code="JCheckBoxDemo" width=270 height=50> </applet>

*/

public class JCheckBoxDemo extends JApplet implements


ItemListener {

JLabel jlab;

public void init() { try {

SwingUtilities.invokeAndWait( new Runnable() {

public void run() { makeGUI();

}
);

} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

private void makeGUI() {

//Change to flow layout.


setLayout(new FlowLayout());

//Add check boxes to the content pane.

JCheckBox cb = new JCheckBox("C"); cb.addItemListener(this);

add(cb);

cb = new JCheckBox("C++"); cb.addItemListener(this); add(cb);


cb = new JCheckBox("Java"); cb.addItemListener(this); add(cb);

cb = new JCheckBox("Perl"); cb.addItemListener(this); add(cb);


// Create the label and add it to the content pane.
jlab = new JLabel("Select languages");

add(jlab);

// Handle item events for the check boxes.


public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)ie.getItem();

if(cb.isSelected())

jlab.setText(cb.getText() + " is selected"); else

jlab.setText(cb.getText() + " is cleared");

}
}

Output from this example is shown here:

Radio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one button
can be selected at any one time. They are supported by the JRadioButton class,
which extends JToggleButton. JRadioButton provides several constructors. The
one used in the example is shown here:
JRadioButton(String str)
Here, str is the label for the button. Other constructors let you specify the initial
selection state of the button and specify an icon.
In order for their mutually exclusive nature to be activated, radio buttons must be
configured into a group. Only one of the buttons in the group can be selected at any
time. For example, if a user presses a radio button that is in a group, any previously
selected button in that group is automatically deselected. A button group is created
by the ButtonGroup class. Its default constructor is invoked for this purpose.
Elements are
then added to the button group via the following method: void
add(AbstractButton ab)

Here, ab is a reference to the button to be added to the group.

A JRadioButton generates action events, item events, and change events each
time the button selection changes. Most often, it is the action event that is handled,
which means that you will normally implement the ActionListener interface.
Recall that the only method defined by ActionListener is actionPerformed( ).
Inside this method, you can use a number of different ways to determine which
button was selected. First, you can check its action command by
calling getActionCommand( ). By default, the action command is the same as the
button label, but you can set the action command to something else by
calling setActionCommand( ) on the radio button. Second, you can
call getSource( ) on the ActionEvent object and check that reference against the
buttons. Third, you can check each radio button to find out which one is currently
selected by calling isSelected( ) on each button. Finally, each button could use its
own action event handler implemented as either an anonymous inner class or a
lambda expression. Remember, each time an action event occurs, it means that the
button being selected has changed and that one and only one button will be
selected.
The following example illustrates how to use radio buttons. Three radio buttons are
created. The buttons are then added to a button group. As explained, this is
necessary to cause their mutually exclusive behavior. Pressing a radio button
generates an action event, which is handled by actionPerformed( ). Within that
handler, the getActionCommand( ) method gets the text that is associated with the
radio button and uses it to set the text within a label.

// Demonstrate JRadioButton
import java.awt.*;

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

<applet code="JRadioButtonDemo" width=300 height=50> </applet>

*/

public class JRadioButtonDemo extends JApplet implements


ActionListener {

JLabel jlab;

public void init() { try {

SwingUtilities.invokeAndWait( new Runnable() {

public void run() { makeGUI();

}
}

);

} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

private void makeGUI() {

//Change to flow layout.


setLayout(new FlowLayout());
//Create radio buttons and add them to content pane.
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
add(b2);

JRadioButton b3 = new JRadioButton("C");


b3.addActionListener(this);
add(b3);

//Define a button group.


ButtonGroup bg = new ButtonGroup(); bg.add(b1);

bg.add(b2);

bg.add(b3);

//Create a label and add it to the content pane.


jlab = new JLabel("Select One");
add(jlab);

// Handle button selection.

public void actionPerformed(ActionEvent ae) { jlab.setText("You


selected " + ae.getActionCommand());

Output from the radio button example is shown here:

JTabbedPane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by
linking them with tabs. Selecting a tab causes the component associated with that
tab to come to the forefront. Tabbed panes are very common in the modern GUI,
and you have no doubt used them many times. Given the complex nature of a
tabbed pane, they are surprisingly easy to create and use.

JTabbedPane defines three constructors. We will use its default constructor,


which creates an empty control with the tabs positioned across the top of the pane.
The other two constructors let you specify the location of the tabs, which can be
along any of the four sides. JTabbedPane uses the SingleSelectionModel model.
Tabs are added by calling addTab( ). Here is one of its forms: void
addTab(String name, Component comp)
Here, name is the name for the tab, and comp is the component that should be
added to the tab. Often, the component added to a tab is a JPanel that contains a
group of related components. This technique allows a tab to hold a set of
components.
The general procedure to use a tabbed pane is outlined here:

Create an instance of JTabbedPane.

Add each tab by calling addTab( ).

Add the tabbed pane to the content pane.

The following example illustrates a tabbed pane. The first tab is titled "Cities" and
contains four buttons. Each button displays the name of a city. The second tab is
titled "Colors" and contains three check boxes. Each check box displays the name
of a color. The third tab is titled "Flavors" and contains one combo box. This
enables the user to select one of three flavors.

// Demonstrate JTabbedPane.
import javax.swing.*;

/*

<applet code="JTabbedPaneDemo" width=400 height=100> </applet>

*/
public class JTabbedPaneDemo extends JApplet {

public void init() { try {

SwingUtilities.invokeAndWait( new Runnable() {

public void run() { makeGUI();

);

} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

private void makeGUI() {

JTabbedPane jtp = new JTabbedPane();


jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel()); add(jtp);

// Make the panels that will be added to the tabbed pane.


class CitiesPanel extends JPanel {

public CitiesPanel() {

JButton b1 = new JButton("New York"); add(b1);

JButton b2 = new JButton("London"); add(b2);

JButton b3 = new JButton("Hong Kong"); add(b3);

JButton b4 = new JButton("Tokyo"); add(b4);

class ColorsPanel extends JPanel {

public ColorsPanel() {
JCheckBox cb1 = new JCheckBox("Red"); add(cb1);

JCheckBox cb2 = new JCheckBox("Green"); add(cb2);

JCheckBox cb3 = new JCheckBox("Blue"); add(cb3);

class FlavorsPanel extends JPanel {

public FlavorsPanel() {

JComboBox<String> jcb = new JComboBox<String>();


jcb.addItem("Vanilla"); jcb.addItem("Chocolate");
jcb.addItem("Strawberry");

add(jcb);

Output from the tabbed pane example is shown in the following three illustrations:
JScrollPane
JScrollPane is a lightweight container that automatically handles the scrolling of
another component. The component being scrolled can be either an individual
component, such as a table, or a group of components contained within another
lightweight container, such as a JPanel. In either case, if the object being scrolled
is larger than the viewable area, horizontal and/or vertical scroll bars are
automatically provided, and the component can be scrolled through the pane.
Because JScrollPane automates scrolling, it usually eliminates the need to manage
individual scroll bars.

The viewable area of a scroll pane is called the viewport. It is a window in which
the component being scrolled is displayed. Thus, the viewport displays the visible
portion of the component being scrolled. The scroll bars scroll the component
through the viewport. In its default behavior, a JScrollPane will dynamically add
or remove a scroll bar as needed. For example, if the component is taller than the
viewport, a vertical scroll bar is added. If the component will completely fit within
the viewport, the scroll bars are removed.

JScrollPane defines several constructors. The one used in this chapter is shown
here: JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are automatically
displayed when the content of the pane exceeds the dimensions of the viewport.
Here are the steps to follow to use a scroll pane:

Create the component to be scrolled.

Create an instance of JScrollPane, passing to it the object to scroll.

Add the scroll pane to the content pane.

The following example illustrates a scroll pane. First, a JPanel object is created,
and 400 buttons are added to it, arranged into 20 columns. This panel is then added
to a scroll pane, and the scroll pane is added to the content pane. Because the panel
is larger than the viewport, vertical and horizontal scroll bars appear automatically.
You can use the scroll bars to scroll the buttons into view.

// Demonstrate JScrollPane.
import java.awt.*;

import javax.swing.*; /*

<applet code="JScrollPaneDemo" width=300 height=250> </applet>

*/

public class JScrollPaneDemo extends JApplet {

public void init() { try {


SwingUtilities.invokeAndWait( new Runnable() {

public void run() {


makeGUI();

);

} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

private void makeGUI() {


// Add 400 buttons to a panel.
JPanel jp = new JPanel(); jp.setLayout(new GridLayout(20, 20));
int b = 0;

for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) {

jp.add(new JButton("Button " + b)); ++b;


}

//Create the scroll pane.

JScrollPane jsp = new JScrollPane(jp);

//Add the scroll pane to the content pane.

//Because the default border layout is used,

//the scroll pane will be added to the center.

add(jsp, BorderLayout.CENTER);

Output from the scroll pane example is shown here:


JList
In Swing, the basic list class is called JList. It supports the selection of one or
more items from a list. Although the list often consists of strings, it is possible to
create a list of just about any object that can be displayed. JList is so widely used
in Java that it is highly unlikely that you have not seen one before.
In the past, the items in a JList were represented as Object references. However,
beginning with JDK 7, JList was made generic and is now declared like this:

class JList<E>

Here, E represents the type of the items in the list.

JList provides several constructors. The one used here is JList(E[ ] items)

This creates a JList that contains the items in the array specified by items.

JList is based on two models. The first is ListModel. This interface defines how
access to the list data is achieved. The second model is
the ListSelectionModel interface, which defines methods that determine what list
item or items are selected.
Although a JList will work properly by itself, most of the time you will wrap
a JList inside a JScrollPane. This way, long lists will automatically be scrollable,
which simplifies GUI design. It also makes it easy to change the number of entries
in a list without having to change the size of the JList component.
A JList generates a ListSelectionEvent when the user makes or changes a
selection. This event is also generated when the user deselects an item. It is
handled by implementing ListSelectionListener. This listener specifies only one
method, called valueChanged( ), which is shown here:

void valueChanged(ListSelectionEvent le)

Here, le is a reference to the event. Although ListSelectionEvent does provide


some methods of its own, normally you will interrogate the JList object itself to
determine what has occurred.
Both ListSelectionEvent and ListSelectionListener are packaged
in javax.swing.event.

By default, a JList allows the user to select multiple ranges of items within the list,
but you can change this behavior by calling setSelectionMode( ), which is defined
by JList. It is shown here:

void setSelectionMode(int mode)

Here, mode specifies the selection mode. It must be one of these values defined by

ListSelectionModel:

SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION

MULTIPLE_INTERVAL_SELECTION

The default, multiple-interval selection, lets the user select multiple ranges of items
within a list. With single-interval selection, the user can select one range of items.
With single selection, the user can select only a single item. Of course, a single
item can be selected in the other two modes, too. It’s just that they also allow a
range to be selected.
You can obtain the index of the first item selected, which will also be the index of
the only selected item when using single-selection mode, by
calling getSelectedIndex( ), shown here:

int getSelectedIndex( )

Indexing begins at zero. So, if the first item is selected, this method will return 0. If
no item is selected, –1 is returned.
Instead of obtaining the index of a selection, you can obtain the value associated
with the selection by calling getSelectedValue( ):

E getSelectedValue( )

It returns a reference to the first selected value. If no value has been selected, it
returns null. The following applet demonstrates a simple JList, which holds a list
of cities. Each time
a city is selected in the list, a ListSelectionEvent is generated, which is handled by
the valueChanged( ) method defined by ListSelectionListener. It responds by
obtaining the index of the selected item and displaying the name of the selected
city in a label.
// Demonstrate JList.
import javax.swing.*; import javax.swing.event.*; import
java.awt.*;

import java.awt.event.*;

/*

<applet code="JListDemo" width=200 height=120> </applet>

*/

public class JListDemo extends JApplet { JList<String> jlst;

JLabel jlab; JScrollPane jscrlp;

// Create an array of cities.

String Cities[] = { "New York", "Chicago", "Houston", "Denver",


"Los Angeles", "Seattle", "London", "Paris", "New Delhi", "Hong
Kong", "Tokyo", "Sydney" };

public void init() { try {

SwingUtilities.invokeAndWait( new Runnable() {

public void run() { makeGUI();


}

);

} catch (Exception exc) {

System.out.println("Can't create because of " + exc);


}

private void makeGUI() {

///Change to flow layout.


setLayout(new FlowLayout());

//Create a JList.

jlst = new JList<String>(Cities);

//Set the list selection mode to single selection.


jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

//Add the list to a scroll pane.

jscrlp = new JScrollPane(jlst);


//Set the preferred size of the scroll pane.
jscrlp.setPreferredSize(new Dimension(120, 90));

//Make a label that displays the selection.

jlab = new JLabel("Choose a City");

//Add selection listener for the list.

jlst.addListSelectionListener(new ListSelectionListener() {

public void valueChanged(ListSelectionEvent le) {

//Get the index of the changed item.

int idx = jlst.getSelectedIndex();

// Display selection, if item was selected.


if(idx != -1)

jlab.setText("Current selection: " + Cities[idx]); else


// Otherwise, reprompt.

jlab.setText("Choose a City");

});
// Add the list and label to the content pane.
add(jscrlp);

add(jlab);

Output from the list example is shown here:

JComboBox
Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class. A combo box normally displays one entry, but it
will also display a drop-down list that allows a user to select a different entry. You
can also create a combo box that lets the user enter a selection into the text field.

In the past, the items in a JComboBox were represented as Object references.


However, beginning with JDK 7, JComboBox was made generic and is now
declared like this:

class JComboBox<E>
Here, E represents the type of the items in the combo box.

The JComboBox constructor used by the example is shown here:


JComboBox(E[ ] items)
Here, items is an array that initializes the combo box. Other constructors are
available. JComboBox uses the ComboBoxModel. Mutable combo boxes (those
whose entries can

be changed) use the MutableComboBoxModel.

In addition to passing an array of items to be displayed in the drop-down list, items


can be dynamically added to the list of choices via the addItem( ) method, shown
here:

void addItem(E obj)

Here, obj is the object to be added to the combo box. This method must be used
only with mutable combo boxes.

JComboBox generates an action event when the user selects an item from the
list. JComboBox also generates an item event when the state of selection changes,
which occurs when an item is selected or deselected. Thus, changing a selection
means that two item events will occur: one for the deselected item and another for
the selected item. Often, it is sufficient to simply listen for action events, but both
event types are available for your use.
One way to obtain the item selected in the list is to call getSelectedItem( ) on the
combo box. It is shown here:

Object getSelectedItem( )
You will need to cast the returned value into the type of object stored in the list.
The following example demonstrates the combo box. The combo box contains
entries for "Hourglass", "Analog", "Digital", and "Stopwatch". When a timepiece
is selected, an icon-based label is updated to display it. You can see how little code
is required to use this powerful component.

// Demonstrate JComboBox.
import java.awt.*; import java.awt.event.*; import javax.swing.*;

/*

<applet code="JComboBoxDemo" width=300 height=200> </applet>

*/

public class JComboBoxDemo extends JApplet { JLabel jlab;

ImageIcon hourglass, analog, digital, stopwatch;


JComboBox<String> jcb;
String timepieces[] = { "Hourglass", "Analog", "Digital",
"Stopwatch" };

public void init() { try {

SwingUtilities.invokeAndWait( new Runnable() {

public void run() { makeGUI();

}
}

);

} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

private void makeGUI() {

//Change to flow layout.


setLayout(new FlowLayout());

//Instantiate a combo box and add it to the content pane.

jcb = new JComboBox<String>(timepieces);

add(jcb);

//Handle selections.

jcb.addActionListener(new ActionListener() { public void


actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem(); jlab.setIcon(new
ImageIcon(s + ".png"));
}

});

// Create a label and add it to the content pane.


jlab = new JLabel(new ImageIcon("hourglass.png")); add(jlab);

}
Output from the combo box example is shown here:
FILL IN THE BLANKS
1. Swing is a Java Foundation Classes(JFC) library.
2. AWT full form is Abstract Window Toolkit.
3. AWT supports limited number of GUI components.
4. Model – View-Controller(MVC) is a well-known design pattern in the web development.
5. MVC has the feature of scalability that in turn helps the growth of application.
6. Layout Managers are used to arrange components in a particular manner.
7. Delegation Event Model is defined to handle events in GUI programming languages.
8. Events are the objects that define state change in a source.
9. Source is an object that causes and generates an event.
10. Inner class is a class that is declared inside the class or interface.
11. Anonymous Inner class is an inner class without a name and for which only a single object is
created.
12. Applet is a special type of program that is embedded in the webpage to generate the dynamic
content.
13. Swing-based applets are similar to AWT-based applets.
14. AbstractButton contains many methods that allow you to control the behavior of buttons.
15. JButton class provides the functionality of a push button.

You might also like