0% found this document useful (0 votes)
2 views396 pages

OOP With Java Complete Notes

The document provides an introduction to Java, detailing its history, features, and various applications. It covers Java's version release history, programming structure, data types, type casting, comments, operators, and control statements. Additionally, it includes steps for setting up the Java environment and examples of basic Java programs.

Uploaded by

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

OOP With Java Complete Notes

The document provides an introduction to Java, detailing its history, features, and various applications. It covers Java's version release history, programming structure, data types, type casting, comments, operators, and control statements. Additionally, it includes steps for setting up the Java environment and examples of basic Java programs.

Uploaded by

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

Introduction To JAVA

Technology

Neeraj Kr. Gupta


Asstt. Prof.
IIMT, Meerut
Unit -1
What is JAVA?
• Java is a high level, robust, secured and object-oriented
programming language developed by Sun
Microsystems(now merged into Oracle
Corporation) and released in 1995.
• Java is a platform independent language which means
java programs can be run on any operating system with
any type of processor as long as the Java interpreter is
available on that system.
• Java code that runs on one platform does not need to be
recompiled to run on another platform, it's called write
once, run anywhere(WORA).

Note :
• Simula is considered as the first Object Oriented Programing Language.
• Smalltalk is considered as the first Truly Object Oriented Programing Language.
History of JAVA
• James Gosling, Mike Sheridan, and Patrick
Naughton initiated the Java language project in June
1991. This small team of sun engineers called Green
Team.
• Originally designed for small, embedded systems in
electronic appliances like set-top boxes.
• Firstly, it was called "Greentalk" by James Gosling
and file extension was .gt.
• After that, it was called Oak and was developed as a
part of the Green project.
• In 1995, Oak was renamed as "Java" because it was
already a trademark by Oak Technologies.
Java Version Release History
Version Released on
JDK1.0 23 Jan 1996
JDK1.1 19 Feb 1997

J2SE 1.2 8 Dec 1998


J2SE 1.3 8 May 2000

J2SE 1.4 6 Feb 2002


J2SE 5.0 30 Sep. 2004
Java SE 6 11 Dec 2006
Java SE 7.0 28 July 2011
Java SE 8.0 18 March 2014

Java SE 9.0 21 Sep. 2017


Java SE 10 20 Mar 2018
Java SE 11 25 Sep. 2018
Java SE 12 19 Mar 2019
Java SE 13 10 Sep. 2019
Java SE 14 17 Mar 2020
Java SE 15 16 Sep. 2020
Java Version Release History (to be continued…)
Version Released on
Java SE 16 16th March 2021

Java SE 17 14th September 2021


Java SE 18 22nd March 2022
Java SE 19 20th September 2022
Java SE 20 21st March 2023
Java SE 21 19th September 2023
Java SE 22 19th March 2024
Java SE 23 17th September 2024
Java SE 24 March 2025
Java SE 25 September 2025
Applications of JAVA

• Console Applications
• Windows Applications
• Web Applications
• Enterprise Applications (large-scale,
multi-tiered, scalable, reliable, and secure
network applications)
• Mobile Applications
JAVA Editions

• J2SE (Java 2 Standard Edition)

• J2EE (Java 2 Enterprise Edition)

• J2ME (Java 2 Micro Edition)


Features of JAVA
Steps for Setting up Java Environment for Windows
1. Download Java8 JDK from the following URL :
https://www.oracle.com/technetwork/java/javase/downl
oads/jdk8-downloads-2133151.html
2. Click second last link for Windows(32 bit) and last link
for Windows(64 bit) as highlighted below.
3. After download, run the .exe file and follow the instructions to install Java on
your machine. Once you installed Java on your machine, you have to setup
environment variable(Path).
4. Go to Control Panel -> System and Security -> System.
Under Advanced System Setting option click on Environment Variables as
highlighted below.
5. Now, you have to alter the “Path” variable under System variables so that it
also contains the path to the Java environment. Select the “Path” variable and
click on Edit button as highlighted below.
6. You will see list of different paths, click on New button and then add path
where java is installed. By default, java is installed in “C:\Program
Files\Java\jdk\bin” folder OR “C:\Program Files(x86)\Java\jdk\bin”. In case, you
have installed java at any other location, then add that path.
7. Click on OK, Save the settings and you are
done !! Now to check whether installation is
done correctly, open command prompt and
type javac -version. You will see that java is
running on your machine.
8. In order to make sure whether compiler is
setup, type javac in command prompt. You
will see a list related to javac.
JAVA Program Structure
import packagename1.*;
import packagename2.*;

class classname
{
public static void main(String [] objname)
{
Variables declaration;
Executable statements;
}
}

Save => classname.java


Compile => javac programname.java
Run => java classname
Example : Write a java program to display
“Welcome To JAVA”.

class Simple
{
public static void main(String [] t)
{
System.out.print(“Welcome To JAVA”);
}
}

Save => Simple.java


Compile => javac Simple.java
Run => java Simple
What happens at compile time?
• At compile time, java file is compiled by Java Compiler (It
does not interact with OS) and converts the java code into
byte code.
What happens at run time?
• Following steps are performed at run time:
JVM
• JVM stands for Java Virtual Machine.
• JVM acts as a run-time engine to run Java
applications.
• It is a specification that provides runtime
environment in which java bytecode can be
executed.
• JVMs are available for many hardware and
software platforms (i.e. JVM is platform
dependent).
JRE
• Java Run-time Environment (JRE) is the part of
the Java Development Kit (JDK).
• It is a freely available software distribution
which has Java Class Library, specific tools, and a
stand-alone JVM.
• It is the most common environment available on
devices to run java programs. The source Java
code gets compiled and converted to Java
bytecode. If you wish to run this bytecode on
any platform, you require JRE.
• The JRE loads classes, verify access to memory,
and retrieves the system resources. JRE acts as a
layer on the top of the operating system.
Java Naming Conventions
• Java uses CamelCase as a practice for writing names of
classes, methods, variables, packages and constants.
• Camel case in Java Programming : It consists of
compound words or phrases such that each word begins
with a capital letter or first word with a lowercase letter,
rest all words begins with capital.
1. Classes and Interfaces :
• Class names should be nouns, in mixed case with
the first letter of each internal word capitalised.
Interfaces name should also be capitalised just like class
names.
• Use whole words and must avoid acronyms and
abbreviations.
Examples:
System, DataInputStream, String, IOException etc.
2. Methods :
• Methods should be verbs, in mixed case with the first letter
lowercase and with the first letter of each internal word
capitalised.
Examples:
void getData( );
void readLine( );
void speedUp(int increment);
void applyBrakes(int decrement);
3. Variables : Variable names should be short yet meaningful.
• Should not start with underscore(‘_’) or dollar sign ‘$’
characters.
• Should be mnemonic i.e, designed to indicate to the casual
observer the intent of its use.
• One-character variable names should be avoided except for
temporary variables.
• Common names for temporary variables are i, j, k, m, and n for
integers; c, d, and e for characters.
Examples:
int speed = 0;
int age = 18;
char c;
4. Constants :
• Should be all uppercase with words separated by underscores
(“_”).
Examples:
final int MIN_WIDTH = 4;
final int ROI=5;
5. Packages :
• A unique package name is always written in all-lowercase ASCII
letters.
Examples:
java.io
java.awt
Data Types in JAVA
• Data types are used to specify what type of value will be
stored in a variable.
• Java supports following two types of data types :
• Primitive Data Types(Built-in data types
provided by java are known as primitive data
types)
• Non Primitive Data Types(They are also known
as derived or user defined data types. They are
defined by using primitive data types. For
example – array, class & interface)
Primitive Data Types in Java
Data Type Size Range
boolean 1 Byte true/false
char 2 Bytes ‘\u0000’ to ‘\uffff’ (0 to 65535)
byte 1 Byte -128 to 127
short 2 Bytes -32768 to 32767
int 4 Bytes -2147483648 to 2147483647
long 8 Bytes -263 to 263 - 1
float 4 Bytes 3.4e-38 to 3.4e+38
double 8 Bytes 1.7e-308 to 1.7e+308
Brainstorming on Data Types
Question 1 : What will be the output of following program?
class Sample
{
public static void main(String[] S) {
int i;
System.out.println(i);
}
}

Options :
A. 0 B. garbage value C. compile error D. runtime error
Question 2 : What will be the output of following program?
class Sample {
public static void main(String[] S) {
for(int j = 0; 1; j++)
{
System.out.println(“DVSGI");
break;
}
}
}

Options :
A. Empty output B. DVSGI C. runtime error D. compile error
Type Casting
• This is the process of converting one type of value into
another type.
• There are following two types of type casting
supported by java:
• Implicit Type Casting
• Explicit Type Casting
Implicit Type Casting
• This is the process of converting one type of value into
another type implicitly (automatically).
• Since java is a type safe language, therefore, it
supports implicit type casting only for lower to higher
data type conversion.
Example :
int i;
short s=4500;
i=s; // implicit type casting
s=i; //Error
Explicit Type Casting
• This is the process of converting one type of value into
another type forcefully.
Syntax :
(Data Type) Expression ;
Example :
int i=5000;
short s;
s= (short) i; //Explicit Type Casting
Brainstorming on Type Casting
Question 1 : What will be the output of following program?
class Sample
{
public static void main(String[] S) {
float age=4.5;
System.out.println(age);
}
}

Options :
A. 4.5 B. 4.5000000 C. compile error D. runtime error
Question 2 : What will be the output of following program?
class Sample {
public static void main(String[] S) {
int a=5, b=2;
int c;
c=a/b;
System.out.println(c);
}
}

Options :
A. 2.5 B. 2 C. runtime error D. compile error
Comments in JAVA
• Non executable statements of a program are known as
comments.
• Comments are used to explain Java code, and to make
it more readable.
• There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
Single Line Comment
• The single line comment is used to comment only one line.
Syntax:
// This is single line comment

Multi Line Comment


• The multi line comment is used to comment multiple lines of
code.
Syntax:
/*
This
is
multi line
comment
*/
Documentation Comment
• This type of comments are used generally when
writing code for a project/software package, since it
helps to generate a documentation page for reference,
which can be used for getting information about
methods present, its parameters, etc.
• The documentation comment is used to create
documentation API. To create documentation API, you
need to use javadoc tool.
Syntax:
/**Comment start
*
*tags are used in order to specify a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*
*comment ends
*/
Example:
//Java program to illustrate frequently used
// Comment tags

/**
* <h1>Find average of three numbers!</h1>
* The FindAvg program implements an application that
* simply calculates average of three integers and Prints
* the output on the screen.
*
* @author Neeraj Kumar Gupta
* @version 1.0
* @since 2019-12-18
*/
public class FindAvg
{
/**
* This method is used to find average of three integers.
* @param numA This is the first parameter to findAvg method
* @param numB This is the second parameter to findAvg method
* @param numC This is the second parameter to findAvg method
* @return int This returns average of numA, numB and numC.
*/
public int findAvg(int numA, int numB, int numC)
{
return (numA + numB + numC)/3;
}
}
Operators in JAVA
• Operators are the symbols which are used to operate
operands.
• Java supports following operators :
• Unary Operators (++ , -- )
• Binary Operators
• Arithmetic Operators(+, -, *, /, %)
• Relational Operators (==, >, <, <=, >=, !=)
• Logical Operators (&&, ||, !)
• Assignment Operators ( =, +=, -=, *=, /=, %=)
• Ternary Operator ( ? : )
• Bitwise Operators ( <<, >>, &, | )
Control Statements in JAVA
• Control statements are the statements which are used to
control the flow of a program.
• Java supports following three types of control statements
:
• Conditional Statements
• Repetition Statements
• Jump Statements
 Conditional Statements : The statements
which are used to execute the statements on
the basis of a condition are known as
conditional statements.

Java supports following conditional statements :

1. if statement
2. If … else statement
3. If … else if statement
4. switch … case statement
 Repetition/Looping Statements : The statements which are
used to execute the statements repeatedly till some specific given
condition is satisfied, are known as repetition statements.
Java supports following repetition statements :
1. while loop
2. for loop
3. do … while loop
4. for each loop/Enhanced for loop
4. for each loop/enhanced for loop : The Java for-each loop or
enhanced for loop is introduced since J2SE 5.0. This loop is used to
process all the elements of an array or a collection.
Syntax :
for (data_type variable_name : array_name/collection_name)
{
statement or block to execute
}
Example 1:
class Sample
{
public static void main(String s[])
{
int n[]={10,20,30,40,50};
for(int i : n)
{
System.out.println(i);
}
}
}
Example 2:
class Sample
{
public static void main(String s[])
{
String [] names = {“Amit“, “Sumit", “Mohit",
“Aman”, “Pankaj"};
for( String n : names )
{
System.out.println( n );
}
}
}
 Jump Statements : Jump statements are the
statements which are used to jump from a
statement to another statement.
Java supports following jump statements :
1. break
2. Continue

1. break statement : This jump statement is


used to terminate a loop or exit from the
switch case.
Syntax :
break;
Example: Java Break Statement with Loop
public class BreakExample
{
public static void main(String[] s)
{
for(int i=1;i<=100;i++)
{
if(i==5)
{
break;
}
System.out.print(i);
}
}
}
Output:
1234
Java Break Statement with Nested For Loop
Example:
public class BreakExample
{
public static void main(String[] s)
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(i==2 && j==2)
{
break;
}
System.out.println(i+" "+j);
}
}
} }
Java Break Statement with Labelled For Loop
We can use break statement with a label. This feature is introduced since JDK 1.5. So,
we can break any loop in Java now whether it is outer loop or inner.
Example:
public class BreakExample
{
public static void main(String[] s)
{
aa:
for(int i=1;i<=3;i++)
{
bb:
for(int j=1;j<=3;j++)
{
if(i==2 && j==2)
{
break aa;
}
System.out.println(i+" "+j);
}
}
Brainstorming on Looping Statements
Question 1 : How many times will “DVSGI” be printed in the
below program?
class Sample_Loop1 {
public static void main(String[ ] s)
{
int i=1024;
for( ; i>0 ; i>>=1)
{
System.out.println("DVSGI");
}}}
Options :
A. 10 B. 11 C. compile error D. infinite
Question 2 : How many times will “DVSGI” be printed in the
below program?
class Sample_Loop2 {
public static void main(String[ ] s) {
int i=0;
do
{
if(i++ < 3)
{
System.out.println("DVSGI"); Options :
continue;
A. 1
}
} while(false); B. 2
}} C. 3
D. Infinite
Question 3 : What will be the output of following program?
class Sample_Loop3 {
public static void main(String[ ] s) {
int i=0;
switch(i)
{
case '0' : System.out.println("BCA");
break;
case '1' : System.out.println("MCA");
break; Options :
default : System.out.println("DVSGI");
} A. BCA
} B. MCA
}
C. DVSGI
D. Compile error
Question 4 : What will be the output of following program?
class Sample_Loop4
{
public static void main(String[ ] s)
{
boolean t=false;
if(t) ;
else
System.out.println("DVSGI");
} Options :
}
A. If block is executed.
B. else block is executed.
C. Error: misplaced else
D. None
Question 5 : What will be the output of following program?
class Sample_Loop5
{
public static void main(String[ ] s)
{
int t;
for(t=9; t!=0; t--)
System.out.print(t--);
}
} Options :
A. 9 7 5 3 1
B. 9 8 7 6 5 4 3 2 1
C. Infinite loop
D. Error
Question 6 : What will be the output of following program?
class Sample_Loop6
{
public static void main(String[ ] s)
{
int m=5, n=10;
do
{
n/=m;
} while(m-- > 0); Options :
System.out.println(n);
} A. 0
} B. 1
C. Compile time error
D. Run time error
Command Line Arguments
• The arguments which are passed from the command
line when we run the program, are known as
command line arguments.
• These arguments can be accessed using the array
name which has been passed to the main() as follows :
First Argument : array_name[0]
Second Argument : array_name[1]
and so on…
Getting Interactive Input in JAVA
• There are three ways to get interactive input from the
user in java.

1. Using BufferedReader class

2. Using Scanner class

3. Using Console class


1. BufferedReader Class

• This is the Java classical method to take


input, Introduced in JDK1.0.
• BufferedReader is a built-in class available
in java.io package.
• Java.io.BufferedReader class reads text
from a character-input stream, buffering
characters so as to provide for the
efficient reading of sequence of
characters.
• Following steps are to be performed to get input using
BufferedReader class :
• Step 1 : Create an object of BufferedReader class as follows :
BufferedReader obj_name=new BufferedReader (new
InputStreamReader(System.in));

• Step 2 : Now, data can be get input by using readLine() as


follows :
String obj_name=BR_obj_name.readLine();

Note : The method readLine() generates an


IOException.
2. Scanner Class
• Scanner is a built-in class available in java.util package.
Java.util.Scanner class is a simple text scanner which
can parse primitive types and strings.

Scanner t=new Scanner(System.in);


Commonly Used Methods of Scanner Class

Method Description

public String next() To get a string from the user

public String nextLine() To get a string having multiple words from


the user

public short nextShort() To get a short value from the user

public int nextInt() To get an integer value from the user

public long nextLong() To get along value from the user

public int nextFloat() To get a float value from the user

public int nextDouble() To get a double value from the user


Exercise
 Write a Program to input a number and check whether it is an even no
or odd no.
 Write a Program to input two numbers. Display larger one.
 Write a Program to input three numbers. Display smallest no.
Write a Program to input salary. Calculate tax as follows :
Upto 5000, tax is 0
For next 10000, tax is 10%
For next 15000, tax is 20%
And above tax is 30%
Write a Program to display even nos. b/w 1 and 100.
Write a Program to input a number. Display factorial of the no.
Write a Program to input a number. Check either it is a perfect no. or
not.
Write a Program to input a number. Check either it is an armstrong no.
or not.
Write a Program to input a number. Check either it is a palindrome no.
or not.
Write a Program to input a number. Check either it is a prime no. or not.
3. Console Class
• Console is a built-in class available in java.io package.
• The Console class was added to java.io by JDK 6.
• The Java.io.Console class provides methods to access
the character-based console device.
• Console class can be used for reading password-like
input without echoing the characters entered by the
user.
• It does not work in an IDE.
Console obj_name = System.console();
Commonly Used Methods of Console Class

Method Description

public String readLine() To read a single line of text

public char[] readPassword() To read a password without


echoing
Example : Write a java program to get two nos. from the
user. Display their sum.

import java.util.*;
class Sum
{
public static void main(String [] S)
{
int a,b,c;
Scanner t=new Scanner(System.in);
System.out.print(“Enter two nos. : ”);
a=t.nextInt();
b=t.nextInt();
c=a+b;
System.out.print(“\n Sum is : “ + c);
}
}
Exercise
 Write a Program to input a number and check whether it is a Pronic
Number.
Hint : A pronic number, oblong number, rectangular number or heteromecic number,
is a number which is the product of two consecutive integers, that is, n (n + 1).
Example : 56 = 7 * 8 i.e. 56 is a product of two consecutive integers 7 and 8.
Write a Program in Java to input a number and check whether it is
a Harshad Number or Niven Number or not.
Hint : A Harshad number (or Niven number), is a number that is divisible by the sum
of its digits.
Write a Program to input a number and check whether it is
a Disarium Number.
Hint : A number will be called DISARIUM if sum of its digits powered with their
respective position is equal to the original number.
For example 89 is a DISARIUM
(Workings 81+92 = 89, some other DISARIUM are 135, 175 etc)
Write a Program in Java to input a number and check whether it is
an Automorphic Number or not.
Hint : An automorphic number is a number which is present in the last digit(s) of its
square.
Example: 25 is an automorphic number as its square is 625 and 25 is present as the
last digits
Object Oriented Programming
• Object-Oriented Programming is a methodology to
develop a program using classes and objects. It simplifies
the software development and maintenance by providing
following concepts:
• Class
• Object
• Encapsulation
• Data Hiding
• Polymorphism
• Inheritance
• Message Passing
Class in JAVA
• In laymen term, a class is a category which can consist of
its own features & behavior. In technical term, a class is
used to define your own data type (non-primitive) which
consists of its own features & behavior.
• In general, a class consists of following two types of
members :
1. Data Members (variables which are used to store the data).
2. Methods (functions which are used to manipulate the data).
Access Specifiers/Modifiers
• These are used to specify the accessibility of the members
of a class.
Java supports following access specifiers :
1. Private : The private members of a class can only be accessed
inside the class. The keyword private is used for this access
specifier.
2. Default : If no access specifier is given, by default it is default.
They can be accessed inside the class as well as outside the
class but within the same package only.
3. Protected : The protected members of a class are same as
default members of a class except that they can also be
accessed in derived class outside the package. The keyword
protected is used for this access specifier.
4. Public : They can be accessed anywhere that is inside the class
as well as outside the class. The keyword public is used for this
access specifier.
Non-Access Modifiers
• There are following non-access modifiers which can be
combined with access specifiers :
1. Static : The keyword static is used for this non-access modifier. The
static members of a class have following two properties:
A. Static members of a class occupy the memory only once for the whole
class, they do not occupy the memory separately for every object of a
class.
B. Static members of a class are accessed directly by using class name,
creation of an object is not required to access static members of a
class.
2. Final : The final keyword performs different-different tasks while
being used with different members of a class as follows :
A. Using final with the data members of a class : if a data member of a
class has been declared using final keyword, it will become a constant.
B. Using final with the method of a class : if a method has been defined
using final keyword, the method can not be overridden in derived
class.
C. Using final with a class : if a class has been defined with final
keyword, the class can not be used as a parent class.
Defining Class in JAVA
• The keyword “class” is used to define a class in java as
follows :

class classname
{
Data members declaration;
Methods definition
}
Object in JAVA
• An object is an instance of a class that is used to access
the members of a class.
• A object of a class in java can be created in following two
ways :
1. class_name
obj_name; // Declaration
obj_name = new class_name(); // Instantiation

2.
class_name obj_name=new class_name();
//Declaration & Instantiation
Accessing Members of a Class
• The members of a class can be accessed in following two
ways :

1. Static Memebrs : They can be accessed directly by using the


class name as follows :
class_name.member_name

2. Instance Members : They are accessed with the help of an


object(instance) of a class as follows :
object_name.member_name
Example1 : Write a menu driven program to
maintain the details of an item in a
departmental store. The output of the
program should be as follows :

1. Purchase
2. Modify
3. Bill
4. Exit
Enter Your Choice :
Example2 : Write a menu driven java program
to maintain the details of an account in a
bank. The output of the program should be as
follows :

1. Open An Account
2. Deposit Amount
3. Withdraw Amount
4. Balance Enquiry
5. Exit
Enter Your Choice :
Array Object in JAVA
• As we can work with any type of array, we can also create
an array of a class which is known as array object of a
class.
• To work with an array object of a class, we are required to
perform following two steps :
Step 1 : Declaring an array object
class_name [] obj_name = new class_name[size];
Account[] t = new Account[50];
Step 2 : Instanciating Elements of an array object
obj_name[index] = new class_name();
t[0] = new Account();
t[1] = new Account();
And so on .......
Example1 : Write a menu driven program to
maintain the details of as many items as
customer wants(up to 20 items) in a
departmental store. The output of the program
should be as follows :
1. Purchase
2. Modify
3. Cancel
4. Display Details of a particular Item
5. Bill
6. Exit
Enter Your Choice :
Example2 : Write a menu driven java program to
maintain the details of multiple accounts in a bank. The
output of the program should be as follows :
1. Open An Account
2. Deposit Amount
3. Withdraw Amount
4. Balance Enquiry
5. Close an account
6. Display Details of all Accounts
5. Exit
Enter Your Choice :
Passing Object as method arguments
• As any type of arguments can be passed to a method, an
object of the same class can also be passed to a method.
Such mechanism is known as passing object as method
arguments.
• The concept of passing objects as method arguments can
easily be understood with the help of following example :
Example : Write a program to maintain the details of three
rectangles. For first & second rectangles get details from
the user. The details of third rectangle should be sum of
first & second rectangle.
Exercise 1 : Define a class Complex to maintain the details
of a complex number. Define a method sum() to add two
complex numbers.
Returning Object From a method
• As any type of value can be get returned from a method,
an object of the same class can also be get returned from
a method. Such mechanism is known as returning object
from a method.
• The concept of returning objects from a method can
easily be understood with the help of following example :
Example : Define a class Complex to maintain the details of
a complex number. Define a method sum() to add two
complex numbers.
Exercise 1 : Define a class Time to maintain the time
details. Define a method sum() to add two objects of
Time class.
Constructors
• A constructor is a method having the
same name as class name which is
executed automatically whenever an
object of a class is instantiated.
• A constructor can not have any return
type not even void because the implicit
return type of a constructor is a class
itself.
• A constructor is used to initialize the
data members of a class.
Type of Constructors
• There are following types of
constructors supported by java :
1. Default Constructor

2. Parameterized Constructor

3. Overloaded Constructor

4. Copy Constructor
1. Default Constructor
• A constructor having no arguments is
known as default constructor.
Syntax :
classname()
{
_________________;
_________________;
}
Example :
class Item
{
int itno,qty;
String name;
float price;
Item()
{
itno=price=qty=0;
name=“”;
}
}
Note : Now, an object of above defined item class will be created as
follows :
classname objname=new classname();
Item t = new Item();
2. Parameterized Constructor
• A constructor having one or more
arguments is known as parameterized
constructor.
Syntax :
classname(argtype1 argname1,argtype2 argname2,…)
{
_________________;
_________________;
}
Example :
class Item
{
int itno,qty;
String name;
float price;
Item(int no, String nm, floar pr, int qt)
{
itno=no;
name=nm;
price=pr;
qty=qt;
}
}
Note : Now, an object of above defined item class will be created as follows :
classname objname=new classname(argname1, argname1, argname1, argname1,);
Item t = new Item(101,”Lux”,35,5);
3. Overloaded Constructor
• This is the process of defining more than one constructors
in a class.
Syntax :
classname( )
{
_________________;
_________________;
}

classname(argtype1 argname1,argtype2 argname2)


{
_________________;
_________________;
}
Example :
class Item
{
int itno, qty;
String name;
float price;
Item()
{
Itno=price=qty=0;
name=nm;
}
Item(int no, String nm, floar pr, int qt)
{
itno=no;
name=nm;
price=pr;
qty=qt;
}
}
Note : Now, an object of above defined item class can be created in following 2 ways :
Item t1= new Item();
Item t 2= new Item(101,”Lux”,35,5);
4. Copy Constructor
• This constructor is defined to initialize
the data members of an object by the
data members of another object.
Syntax :
classname(classname objname )
{
_________________;
_________________;
}
Example :
class Item
{
int itno, qty;
String name;
float price;
Item()
{
Itno=price=qty=0;
name=nm;
}
Item(Item x)
{
itno=x.itno;
name=x.name;
price=x.price;
qty=x.qty;
}
void Getdata()
{
------------------;
}
}
Note : Now, an object of above defined item class can be created in following 2 ways :

Item t1= new Item();

t1.Getdata();

Item t 2= new Item(t1);


Destructor
• A destructor is a method which is executed
automatically whenever an object of a class is
destroyed(deleted).
• A destructor is defined to free up the resource which
are no longer required. But java provides the
concept of garbage collection, which automatically
free up the resource which are no longer required,
therefore, defining destructor is not required in java.
Even though, if you want to define a destructor, you
can define as follows :
protected void finalize()
{
//statements like closure of database connection
}
Inheritance
• Inheritance is the process of inheriting the features of
one class into another class.
• The idea behind inheritance is that you can create
new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you
can add new methods and fields in your current class
also.
• Inheritance represents the IS-A relationship which is
also known as a parent-child relationship.
• The class from which the features are being inherited
is known as Parent class, Base class or Super class.
• The class into which the features are being inherited is
known as Child class, Derived class or Sub class.
Type of Inheritance
•There are following five types of
inheritance :
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
Single Inheritance
•This is the process of inheriting a
class from single base class.
Multilevel Inheritance
• This is the process of inheriting a class
from such base class which already
inherits any other base class.
Hierarchical Inheritance
• This is the process of inheriting multiple
classes from single base class.
Multiple Inheritance
•This is the process of inheriting a
class from two or more base classes.
Hybrid Inheritance
•This is the combination of single and
multiple inheritance both.

Note : Java supports only single inheritance and its


family(multilevel & hierarchical).
Implementing Inheritance in Java
• The keyword “extends” is used to implement inheritance
in java as follows :

class DerivedClassName extends BaseClassName


{
Define Additional Features
______________________
______________________
}
Example1 : Write a program to maintain the
details of a Rectangle and a Cuboid.
Example2 : Define a class Student to maintain
personal details (rollno, name) of a student.
Define another class Marks to maintain
personal details of a student & marks of two
subjects. Define another class Total to maintain
personal details of a student, marks of two
subjects and total marks.
Write Main() to maintain all details of a
student.
Making Inheritance More Efficient
import java.util.*; class Cuboid extends Rect class Demo
class Rect { {
{ private int h; public static void main(String[] s)
private int l,b; public void Input() {
public void GetData() { Rect r=new Rect();
{ GetData(); Cuboid c=new Cuboid();
Scanner t=new Scanner(System.in); Scanner t=new Scanner(System.in); System.out.print(“\Rectangle Details :”);
System.out.print(“\nEnter Length : “); System.out.print(“\nEnter Height : “); r.GetData();
l=t.nextInt(); h=t.nextInt(); r.Display();
System.out.print(“\nEnter Breadth : “); } System.out.print(“\Cuboid Details :”);
b=t.nextInt(); public void Show() c.Input()
} { c.Show();
public void Display() Display(); }
{ System.out.print(“\nHeight : “ + h); }
System.out.print(“\nLength : “ + l); }
System.out.print(“\nBreadth : “ + b); }
}
}
Method Overriding

• This is the process of defining a method


by the same name and signature in
derived class which is already being
inherited from the base class.
Method Overriding - Example
import java.util.*; class Cuboid extends Rect class Demo
class Rect { {
{ private int h; public static void main(String[] s)
private int l,b; public void GetData() {
public void GetData() { Rect r=new Rect();
{ super.GetData(); Cuboid c=new Cuboid();
Scanner t=new Scanner(System.in); Scanner t=new Scanner(System.in); System.out.print(“\Rectangle Details :”);
System.out.print(“\nEnter Length : “); System.out.print(“\nEnter Height : “); r.GetData();
l=t.nextInt(); h=t.nextInt(); r.Display();
System.out.print(“\nEnter Breadth : “); } System.out.print(“\Cuboid Details :”);
b=t.nextInt(); public void Display() c.GetData();
} { c.Display();
public void Display() super.Display(); }
{ System.out.print(“\nHeight : “ + h); }
System.out.print(“\nLength : “ + l); }
System.out.print(“\nBreadth : “ + b); }
}
}
Constructor in Derived Class

• To define a constructor in derived class,


we must be knowing following two
mechanisms :
1. Execution Sequence of Constructors
2. Defining Constructor is optional or
mandatory
Execution Sequence of Constructors

• Whenever an object of base class is


instantiated, base class constructor is
executed.
• Whenever an object of derived class is
instantiated, both base class and derived
class constructors are executed.
Defining Constructor is Optional/Mandatory
• It is optional to define a constructor in base
class.
• Define constructor in derived class depends
on base class constructor as follows :
• In case of no base class constructor or base
class default constructor, It is optional to
define a constructor in derived class.
• In case of base class parameterized
constructor, It is mandatory to define a
constructor in derived and it is also
compulsory to call base class constructor from
this derived class constructor as a first
statement.
Abstract Class & Interface
• Data abstraction is the process of hiding certain details
and showing only essential information to the user.
• Abstraction can be achieved with either abstract
classes or interfaces.
• An abstract class is a class that is declared abstract—it
may or may not have all abstract methods (an abstract
method is a method that is declared without an
implementation).
• Abstract classes can not be instantiated, they can only
be subclassed.
• When an abstract class is subclassed, the subclass
usually provides implementations for all of the abstract
methods in its parent class. However, if it does not, then
the subclass must also be declared abstract.
Defining Abstract Class in JAVA
• The keyword “abstract” is used to define an abstract class
in java as follows :

abstract class classname


{
Data members declaration;
Methods definition
Abstract methods declaration;
}
Example1 : Define an abstract class Shape to
maintain the details of a shape. Now define
following concrete classes :
1. Rect – To maintain the details of a rectangle
2. Square – To maintain the details of a square
3. Triangle – To maintain the details of a triangle
Brainstorming on abstract class
• Can an abstract class contain constructors?
• Can we have an abstract class without any
abstract method?
• An instance of an abstract class cannot be
created, but can we have the reference of an
abstract class?
• Can an abstract class also have final
methods?
 An abstract class can contain constructors in Java. And a constructor of abstract class is
called when an instance of a inherited class is created.
Example :
abstract class Base
{
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
}
class Derived extends Base
{
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
}
class Main
{
public static void main(String args[])
{
Derived d = new Derived();
}
}
Output:
Base Constructor Called
Derived Constructor Called
 We can have an abstract class without any abstract method. This allows us
to create classes that cannot be instantiated, but can only be inherited.
Example :
abstract class Base
{
void fun() { System.out.println("Base fun() called"); }
}

class Derived extends Base { }

class Main
{
public static void main(String args[])
{
Derived d = new Derived();
d.fun();
}
}
Output:
Base fun() called
 An instance of an abstract class cannot be created, but we can have
references of abstract class.
Example :
abstract class Base
{
abstract void fun();
}
class Derived extends Base
{
void fun() { System.out.println("Derived fun() called"); }
}
class Main
{
public static void main(String args[])
{
Base b = new Derived();
b.fun();
}
}
Output:
Derived fun() called
 Abstract classes can also have final methods
Example :
abstract class Base
{
final void fun() { System.out.println(“Base fun() called"); }
}

class Derived extends Base {}

class Main
{
public static void main(String args[]) {
Derived d = new Derived();
d.fun();
}
}
Output:
Base fun() called
Interfaces
• Interfaces are same as abstract classes that
are used to define fully abstract data
type. That means all the methods in an
interface are declared with an empty body
and are public and all fields(data members)
are public, static and final by default.
• A class that implements interface must
implement all the methods declared in the
interface.
• A class can implement one or more
interfaces. Therefore, we can say that
interfaces provides the concept of multiple
inheritance in java.
Type of Interfaces

•There are following two types of


interfaces supported by java :
1. Built-in Interfaces
2. User Defined Interfaces
1. Built-in Interfaces
•Predefined interfaces provided by
java are known as built-in interfaces.
•To work with built-in interfaces, we
are required to perform following
steps :
Step 1 : Implements all the required
interfaces as follows :
class classname implements
interfacename1,interfacename2,…
Step 2 : Define all the methods of all the
implemented interfaces
2. User Defined Interfaces
• If you want to define your own interface,
you can define, such interfaces are
known as user defined interfaces.
• The keyword “interface” is used to
define an interface as follows :
interface interface_name
{
Data members declaration & initialization;
Methods declaration;
}
Java program to demonstrate working of Interface
interface In1
{
final int x = 100;
void Show();
}
// A class that implements the interface.
class SampleClass implements In1
{
public void Show()
{
System.out.println(“DVSGI");
}
public static void main (String[] s)
{
SampleClass M = new SampleClass();
M.Show();
System.out.println(M.x);
}
}
Output:
DVSGI
100
New features added in interfaces in JDK 8
1. Prior to JDK 8, interface could not define
implementation. We can now add default
implementation for interface methods. This
default implementation has special use and
does not affect the intention behind
interfaces. Suppose we need to add a new
function in an existing interface. Obviously
the old code will not work as the classes
have not implemented those new
functions. So with the help of default
implementation, we will give a default body
for the newly added functions. Then the old
codes will still work.
Example :
interface In1
{
final int x = 100;
default void Show()
{
System.out.println(“DVSGI");
}
}
// A class that implements the interface.
class Sample implements In1
{
public static void main (String[] S)
{
Sample t = new Sample();
t.Show();
}
}
Output :
DVSGI
New features added in interfaces in JDK 8

2. Another feature that was added in


JDK 8 is that we can now define static
methods in interfaces which can be
called independently without an
object. Note: these methods are not
inherited.
Example :
interface In1
{
final int x = 100;
static void Show()
{
System.out.println(“DVSGI");
}
}
// A class that implements the interface.
class Sample implements In1
{
public static void main (String[] S)
{
In1.Show();
}
}
Output :
DVSGI
Packages
•A package is a collection of similar
type of classes and interface.
•Packages are used to prevent naming
conflicts. For example there can be
two classes with same name in two
packages.
•The main advantage of a package is
that, by placing classes in a package,
they can be used in any of the
program just by importing the
package.
Types of Packages

•There are following two types of


packages supported by java :
1. Built-in Packages
2. User Defined Packages
1. Built-in Packages

•Predefined packages provides by


java are known as built-in
packages.
•Mainly, java provides two built-in
packages – java(core java) and
javax(advance java). All other
built-in packages are available
inside these two main packages.
Most Commonly Used Built-in Packages
Java
lang io util awt net applet sql
1) java.lang: Contains language support classes(e.g classed which
defines primitive data types, math operations). This package is
automatically imported.
2) java.io: Contains classed for supporting input / output
operations.
3) java.util: Contains utility classes which implement data structures
like Linked List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for
graphical user interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
7) java.sql: Contain classes for database connectivity.
Working with built-in Packages
•To work with built-in package, just we
are required to import a package.
•A package can be imported in
following two ways :
1. Importing a whole package
Syntax : import packagename.*;
Example : import java.io.*;
2. Importing a particular class
Syntax : import packagename.classname;
Example : import java.io.DataInputStream;
2. User Defined Packages

•If you wan to define your own


package, you can define, such
packages are known as user
defined packages.
Working with User Defined Packages

•To work with user defined


packages, we are required to
perform following two steps :
 Step 1 : Defining a package
 Step 2 : Importing a package
Step 1 : Defining a Package
• To define a package, we are required to perform following
steps :
a) Specify a package name as follows:
package package_name;
b) Define a public class which is to be placed inside the
package.
c) Save your package program by the same name as class
name with .java extension.
d) Compile the package program by issuing following
command :
javac -d . programname
e) The above statement will compile the package program, if
there is no error, the package will be created successfully.
f) After successful creation of a package, the package program
is not required, therefore either delete or rename the
package program.
Step 2 : Importing a Package

•A user defined package will also


be imported in the same manner
in a built-in package is imported as
follows :
import packagename.*;
OR
import
packagename.classname;
Java Static Import

•Static import is a feature


introduced in Java programming
language version 5.
•This feature facilitate the java
programmer to access any static
member(public) of a class directly.
There is no need to qualify it by the
class name.
Example of Static Import
import static java.lang.System.*;
class Example
{
public static void main(String s[])
{
out.println("Hello");
//Now no need of System.out
out.println("Java");
}
}
Unit -2
Exception Handling
• An exception is an abnormal condition that
is caused by run time error in a program.
• Whenever an exception is generated in a
program and the exception handler of such
exception is found inside the program, the
generated exception will be handled and
the program will keep running successfully.
• But, if no such exception handler is found
inside the program, every language has its
own exception handler. Therefore,
execution control will be transferred to that
exception handler and the program will be
terminated.
Exception Class Hierarchy
Throwable

Exception

IOException

SQLException

ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException

Types of Exceptions

•There are following two types of


exceptions :
1. Built-in Exceptions
2. User Defined Exceptions
1. Built-in Exceptions
• Predefined exception provided by java which
are generated implicitly are known as built-in
exceptions.
• To work with built-in exceptions, just we are
required to handle the exception.
• Java provides following four keywords to
handle the exceptions :
a) try
b) catch
c) finally
d) throws
Exception Handling using try & catch
• try & catch blocks are used in combination.
• try block consists of the statements which
may generate exceptions.
• Just follow the try block there must be a
catch block consists of the statements to
handle corresponding exception generated in
try block.
• More than one catch blocks can also be given
with one try block.
Syntax :
try
{
Statements that may generate exceptions;
__________________________________;
}
catch(Exception_class_name1 obj_name1)
{
Statements to handle exception;
__________________________;
}
catch(Exception_class_name2 obj_name2)
{
Statements to handle exception;
__________________________;
}
...
Exception Handling using try, catch & finally
• finally block can only be used in the
combination of try block or try & catch block.
• Statements of finally block must be executed
either exception is handled or not.
• finally block is a block that is used to execute
important code such as closing connection,
stream etc.
Syntax :
try
{
Statements that may generate exceptions;
__________________________________;
}
catch(Exception_class_name1 obj_name1)
{
Statements to handle exception;
__________________________;
}
catch(Exception_class_name2 obj_name2)
{
Statements to handle exception;
__________________________;
}
finally
{
Statements must be executed;
________________________;
}
Usage of finally block
• Let's see the different cases where java finally block
can be used.
Case 1 : where exception doesn't occur
class TestFinallyBlock{
public static void main(String s[]){
try{
int data=125/5;
System.out.println(data);
}
catch(NullPointerException e)
{System.out.println(“Inside catch block”);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output : 25
finally block is always executed
rest of the code...
Case 2 : where exception occurs and not handled
class TestFinallyBlock{
public static void main(String s[]){
try{
int data=125/0;
System.out.println(data);
}
catch(NullPointerException e)
{System.out.println(“Inside catch block”);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output : finally block is always executed
Exception in thread main
java.lang.ArithmeticException:divide by zero
Case 3 : where exception occurs and handled
class TestFinallyBlock{
public static void main(String s[]){
try{
int data=125/0;
System.out.println(data);
}
catch(ArithmeticException e)
{System.out.println(“Inside catch block”);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output : Inside catch block
finally block is always executed
rest of the code…
Exception Handling using throws
• Whenever an exception is generated in a program,
there are two ways to deal with the exception – either
handle the exception using try/catch, try/catch/finally
block or further throwing an exception.
• throws keyword is used to further throwing an
exception.
• To further throw an exception, throws keyword must
be given with the method name from which exception
is to be further thrown.
• While further throwing an exception using throws
keyword, the exception must be thrown up to
command prompt.
Syntax :

public return_type methodName() throws ExpClsName1,…


{
Statements ;
__________;
__________;
}
2. User Defined Exception
• Exceptions may be useful also. Therefore, If
you want to define your own exception, you
can define. Such exception are known as user
defined exceptions.
• To work with user defined exceptions, we are
required to perform following three steps :
Step 1 : Defining an Exception
Step 2 : Generating(throwing) an Exception
Step 3 : Handling an Exception
Step 1 : Defining an Exception
• To define your own exception, you are just required to
define a class by inheriting Exception class or any of its
child class.
• It is customary to give both a default constructor and a
constructor that contains a detailed message.
• Therefore, An exception can be defined as follows :
class ExpCLS_Name extends Exception
{
ExpCLS_Name() { }
ExpCLS_Name(String msg)
{ super(msg); }
}
Step 2 : Generating(throwing) an Exception

• The keyword throw is used to generate an exception


as follows :
throw Exception_OBJ_Name;

Step 3 : Handling an Exception


• A user defined exception will also be handled in the
same manner in built-in exceptions are handled that is
by using try & catch block, try, catch & finally block or
by using throws keyword.
Streams
• Java programs performs I/O through streams.
• A stream can be defined as a sequence of data.
• There are two kinds of Streams −
1. Input Stream − The Input Stream is used to read data from a source.
2. Output Stream − The Output Stream is used for writing data to a
destination.

Note : All the stream classes are available in java.io


package.
Byte Streams and Character Streams
• Byte streams provide a convenient means for
handling input and output of bytes. Byte
streams are used for reading or writing
binary data.
• Character streams provide a convenient
means for handling input and output of
characters.
Byte Stream Classes
Character Stream Classes
Byte Streams

•Java byte streams are used to


perform input and output of bytes.
Though there are many classes
related to byte streams but the most
frequently used classes are,
FileInputStream and FileOutputStre
am.
•FileInputStream : This class is used
to read data from a file.

Syntax :

FileInputStream obj_name = new


FileInputStream(“file path”);
Methods of FileInputStream class
Method Description
int available() It is used to return the estimated
number of bytes that can be read
from the input stream.
int read() It is used to read the byte of data
from the input stream. Returns -1
when it reaches at the end of file.
int read(byte[] b) It is used to read up
to b.length bytes of data from the
input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of
data from the input stream.
long skip(long x) It is used to skip over and discards x
bytes of data from the input stream.
void close() It is used to closes the stream.
•FileOutputStream : This class is used
to write data to a file.

Syntax :

FileOutputStream obj_name = new


FileOutputStream(“file path”);
Methods of FileOutputStream class
Method Description
void write(int b) It is used to write the specified byte
to the file output stream.

void write(byte[] ary) It is used to write ary.length bytes


from the byte array to the file output
stream.

void write(byte[] ary, int off, int len) It is used to write len bytes from
the byte array starting at
offset off to the file output stream.

void close() It is used to closes the file output


stream.
Example : Write a program to copy the contents of one file onto another file.
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Streams

•Java character streams are used to


perform input and output of
characters. Though there are many
classes related to character streams
but the most frequently used classes
are, FileReader and FileWriter.
•FileReader : This class is used to read
data from a file.

Syntax :

FileReader obj_name = new


FileReader(“file path”);
Methods of FileReader class

Method Description

int read() It is used to return a character


in ASCII form. It returns -1 at
the end of file.

void close() It is used to close the


FileReader class.
•FileWriter : This class is used to write
data to a file.

Syntax :

FileWriter obj_name = new


FileWriter(“file path”);
Methods of FileWriter class
Method Description
void write(char c) It is used to write the char into
FileWriter.

void write(char[] c) It is used to write char array into


FileWriter.

void write(String text) It is used to write the string into


FileWriter.

void close() It is used to closes the file writer.


Example : Write a program to copy the contents of one file onto another file.
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Multithreading
• To learn Multithreading, firstly we must be
knowing Multitasking.
Multitasking : Multitasking is the process of
performing more than one tasks at the
same time. Multitasking can be achieved in
following two ways :
1. Process Based Multitasking
2. Thread Based Multitasking
1. Process Based Multitasking : Whenever
two or more processes are being
executed at the same time, such
mechanism is known as Process Based
Multitasking.
2. Thread Based Multitasking : Whenever
two or more parts(tasks) of the same
process are being executed at the same
time, every task is known as the thread
& if there are more than one threads,
such mechanism is known as
Multithreading.
Thread States
• In the life cycle of the thread, a thread
may be in following several states :
Born

start()
Sleep Interval Expires I/O Completion
Ready

Assigns the
yield()
processor

Running

sleep()

Waiting Sleeping Dead Blocked


Implementing Multithreading in Java

• Java provides following two mechanisms


to implement multithreading :
1. By Implementing Runnable Interface
2. By Extending Thread Class
Implementing Multithreading using Runnable Interface

• Runnable is a built-in interface available in java.lang


package.
• This interface provides the mechanism to implement
multithreading in java.
• Runnable interface provides a method public void run()
that is executed automatically whenever a thread is
started.
Steps to Implement Multithreading using
Runnable Interface
Step 1 : Define a class by implementing Runnable
interface as follows :
class Class_Name implements Runnable
Step 2 : Now, declare as many objects of Thread class
as much multithreading you want to achieve as
follows :
Thread ObjName1,ObjName2,…
Step 3 : Now, instantiate all of the above created
Thread objects as follows :
Objname1=new Thread(this);
or
Objname1=new Thread(Runnable target);
Step 4 : Now, start the execution of all of the above
created Threads by calling start() of Thread class as
follows :
ObjName1.start();
ObjName2.start();
………
Step 5 : Now, define run() of Runnable interface as
per your requirement as follows :
public void run()
{
……….
}
Example1 : Write a program by using the concept of
multithreading to produce following outptut :
2
1
4
3
6
5
8
7
10
9
Thread Class
• Thread is a built-in interface available in java.lang package.
• This class implements Runnable interface therefore this class also
provides the mechanism to implement multithreading in java.
• This class provides a method public void run() that is executed
automatically whenever a thread is started.
• A Thread class object can be created in following ways :
Thread objname=new Thread();
Thread objname=new Thread(“name”);
Thread objname=new Thread(Runnable Target);
Thread objname=new Thread(Runnable Target,”name”);
Methods of Thread Class
1. start() : This method is used to start the execution of a thread.
Syntax : Thread_objname.start();
2. sleep() : This method is used to suspend the execution of a
thread up to given number of milliseconds. This method
generates an Exception.
Syntax : Thread_objname.sleep(milliseconds);
3. isAlive() : This method returns true if thread is alive otherwise
returns false.
Syntax : boolean varname=Thread_objname.isAlive();
4. setName() : This method is used to specify the name of a thread.
Syntax : Thread_objname.setName(“name”);
5. getName() : This method is used to retrieve the name of a
thread.
Syntax : String objname=Thread_objname.getName();
6. currentThread() : This is a static method of Thread class that
returns the reference of currently running thread.
Syntax : Thread objname=Thread.currentThread();
7. setPriority() : Higher priority threads are executed earlier than
lower priority threads irrespective of their starting sequence. The
priority of a thread can be set between 1 (Thread.MIN_PRIORITY)
and 10 (THREAD.MAX_PRIORITY). If no priority has been given to
a thread, by default it is 5 (Thread.NORM_PRIORITY). This
method is used to specify the priority of a thread.
Syntax : Thread_objname.setPriority(priority);
8. getPriority() : This method is used to retrieve the priority of a thread.
Syntax : int varname=Thread_objname.getPriority();
9. suspend() : This method is used to suspend the execution of a thread
until it has not been resumed explicitly.
Syntax : Thread_objname.suspend();
10. resume() : This method is used to resume the execution of a thread
that has been suspended using suspend().
Syntax : Thread_objname.resume();
11. yield() : This method is used to pause a thread temporary and allow
other threads to be executed.
Syntax : Thread_objname.yield();
12. join() : Some times sub threads are alive and main
thread is dead. In such case program will not work
properly. Therefore, main thread must not be dead if
any sub thread is alive. To do so, sub threads must be
joined with main thread. This method is used to join sub
thread with main thread.
Syntax : SubThread_objname.join();
Steps to Implement Multithreading using
Thread class
Step 1 : Define a class by inheriting Thread class as
follows :
class Class_Name extends Thread
Step 2 : Override the method public void run() as per
your requirement in the above defined class as
follows :
public void run()
{
____________________;
____________________;
}
Step 3 : Now, define another class having main() and
create as many objects of above defined class as
much multithreading you want to implement.
Step 4 : Now, start the execution of all the threads
created in step 3 by calling start().
Example1 : Write a program by using the concept of
multithreading to produce following outptut :
2
1
4
3
6
5
8
7
10
9
class MyThread extends Thread
{
MyThread(String name)
{
setName(name);
}
public void run()
{
String nm=getName();
if(nm.equals("even"))
{
for(int i=2;i<=10;i+=2)
{
System.out.print("\n" + i);
try
{
sleep(10);
}
catch(Exception e) { }
}
}
else if(nm.equals("odd"))
{
for(int j=1;j<=9;j+=2)
{
System.out.print("\n" + j);
try
{
sleep(10);
}
catch(Exception e) { }
}
}
}
}
class MyThreadDemo
{
public static void main(String[] s)
{
MyThread t1=new MyThread("even");
MyThread t2=new MyThread("odd");
t1.start();
t2.start();
}
}
Synchronization
• Multi-threaded programs may often come to a situation where
multiple threads try to access the same resources and finally
produce erroneous and unforeseen results.
• So it needs to be made sure by some synchronization method
that only one thread can access the resource at a given point of
time.
• Java provides a way of creating threads and synchronizing their
task by using synchronized blocks. Synchronized blocks in Java
are marked with the synchronized keyword. A synchronized block
in Java is synchronized on some object. All synchronized blocks
synchronized on the same object can only have one thread
executing inside them at a time. All other threads attempting to
enter the synchronized block are blocked until the thread inside
the synchronized block exits the block.
• This synchronization is implemented in Java with a concept called
monitors. Only one thread can own a monitor at a given time. When a
thread acquires a lock, it is said to have entered the monitor. All other
threads attempting to enter the locked monitor will be suspended
until the first thread exits the monitor.
• A synchronized block can be created as follows :
synchronized
{
__________________;
__________________;
}
• A complete method can be synchronized as follows :
synchronized access_specifier return type methodname()
{
__________________;
__________________;
}
Inter Thread Communication
• Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each other.
• Cooperation (Inter-thread communication) is a mechanism in
which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical
section to be executed. It is implemented by following methods
of Object class:
• wait()
• notify()
• notifyAll()
1. wait() method : This method causes current thread to release
the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a
specified amount of time has elapsed.
2. notify() method : This method wakes up a single thread
that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
3. notifyAll() method : This method wakes up all threads
that are waiting on this object's monitor.
Example of inter thread communication in java

class Customer{

int amount=10000;

synchronized void withdraw(int amount){

System.out.println("going to withdraw...");

if(this.amount<amount){

System.out.println("Less balance; waiting for deposit...");

try{wait();}catch(Exception e){}

this.amount-=amount;

System.out.println("withdraw completed...");

synchronized void deposit(int amount){

System.out.println("going to deposit...");

this.amount+=amount;

System.out.println("deposit completed... ");

notify(); } }

class Test{

public static void main(String args[]){

final Customer c=new Customer();

new Thread(){

public void run(){c.withdraw(15000);}

}.start();

new Thread(){

public void run(){c.deposit(10000);}

}.start();

}}
class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();

new Thread(){
public void run(){c.deposit(10000);}
}.start();
Output: going to withdraw...
Less balance; waiting for deposit...
} going to deposit...
deposit completed...
} withdraw completed
Unit -3
Java New Features
Functional Interfaces
• An Interface that contains exactly one abstract
method is known as functional interface.
• It can have any number of default, static methods but
can contain only one abstract method.
• It can also declare methods of object class.
• Functional Interface is also known as Single Abstract
Method Interfaces or SAM Interfaces.
• It is a new feature in Java, which helps to achieve
functional programming approach.
Functional Interface - Example
Let‘s understand Functional Interface with the following code:
@FunctionalInterface
interface sayable{
void say(String msg);
}
public class FIExample implements sayable{
public void say(String msg){
System.out.println(msg); Output :
}
public static void main(String[] args) { Welcome to IIIMT
FIExample fie = new FIExample();
fie.say(“Welcome to IIMT");
}
}
Lambda Expression
• Lambda expression is a new and important feature of Java
which was included in Java SE 8.
• It provides a clear and concise way to represent one method
interface using an expression.
• It is very useful in collection library. It helps to iterate, filter
and extract data from collection.
• The Lambda expression is used to provide the implementation
of an interface which has functional interface. It saves a lot of
code.
• In case of lambda expression, we don't need to define the
method again for providing the implementation. Here, we just
write the implementation code.
• Java lambda expression is treated as a function, so compiler
does not create .class file.
Why use Lambda Expression :
1.To provide the implementation of Functional interface.
2.Less coding.
Syntax :
(argument-list) -> {body}

Java lambda expression is consisted of three components:


1) Argument-list: It can be empty or non-empty as well.
2) Arrow-token: It is used to link arguments-list and body
of expression.
3) Body: It contains expressions and statements for
lambda expression.
Lambda Expression - Example
Let‘s understand Lambda Expression with the following code:
@FunctionalInterface //It is optional
interface Drawable{
public void draw();
}

public class LambdaExpressionExample2 {


public static void main(String[] args) {
int width=10; Output :
//with lambda Drawing 10
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}
Method References
• Java provides a new feature called method reference in Java
8.
• Method reference is used to refer method of functional
interface.
• It is compact and easy form of lambda expression.
• Each time when you are using lambda expression to just
referring a method, you can replace your lambda expression
with method reference.

There are three types of method references in java:


1. Reference to a static method.
2. Reference to an instance method.
3. Reference to a constructor.
1. Reference to a static method
You can refer to static method defined in the class. Following is the syntax and
example which describe the process of referring static method in Java.
Syntax : ContainingClass::staticMethodName
Example:
interface Sayable{
void say();
}
public class MethodReference {
public static void saySomething(){ Output :
System.out.println("Hello, this is static method.");
} Hello, this is static
public static void main(String[] args) { method.
// Referring static method
Sayable sayable = MethodReference::saySomethi
ng;
// Calling interface method
sayable.say();
}
}
2. Reference to an Instance Method
Like static methods, you can refer instance methods also. In the
following example, we are describing the process of referring the
instance method. Syntax : containingObject::instanceMethodName
Example:
interface Sayable{
void say();
}
public class InstanceMethodReference {
public void saySomething(){
System.out.println("Hello, this is non-static method.");
} Output :
public static void main(String[] args) {
// Creating object
InstanceMethodReference methodReference = new InstanceMethodRefer
Hello, this is non-
ence(); static method.
// Referring non-static method using reference
Sayable sayable = methodReference::saySomething;
Hello, this is non-
// Calling interface method static method.
sayable.say();
// Referring non-static method using anonymous object
Sayable sayable2 = new InstanceMethodReference()::saySomething; //
You can use anonymous object also
// Calling interface method
sayable2.say();
}
3. Reference to a Constructor
You can refer a constructor by using the new keyword. Here, we are
referring constructor with the help of functional interface.
Syntax : ClassName::new
Example:
interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
Output :
System.out.print(msg);
IIMT University
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage(“IIMT University");
}
}
Java Default Methods
Java provides a facility to create default methods inside the interface. Methods
which are defined inside the interface and tagged with default are known as
default methods. These methods are non-abstract methods.
Java Default Method Example:
In the following example, Sayable is a functional interface that contains a default and an abstract
method. The concept of default method is used to define a method with default implementation. You
can override default method also to provide more specific implementation for the method.
interface Sayable{
// Default method
default void say(){
System.out.println("Hello, this is default method"); Output :
}
// Abstract method
void sayMore(String msg);
} Hello, this is default
public class DefaultMethods implements Sayable{ method
public void sayMore(String msg){ // implementing abstract m
ethod Work is worship
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
}
}
Java Static Method
• Java 8 interface can also consists of static methods.
Example :
interface Sayable{
// default method
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
// static method
static void sayLouder(String msg){
System.out.println(msg); Output :
}
}
public class StaticExample implements Sayable{
Hello, this is default method
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg); Work is worship
}
Welcome To IIMT
public static void main(String[] args) {
StaticExample t = new StaticExample();
t.say(); // calling default method
t.sayMore("Work is worship"); // calling abstract method
Sayable.sayLouder(“Welcome To IIMT”); // calling static method
}
}
Java Base64 Encode and Decode
• Java provides a class Base64 to deal with encryption. You can
encrypt and decrypt your data by using provided methods. You
need to import java.util.Base64 in your source file to use its
methods.
• This class provides three different encoders and decoders to
encrypt information at each level. You can use these methods at
the following levels.
Nested Classes of Base64 :

Class Description
Base64.Decoder This class implements a decoder for
decoding byte data using the Base64
encoding scheme as specified in RFC
4648 and RFC 2045.
Base64.Encoder This class implements an encoder for
encoding byte data using the Base64
encoding scheme as specified in RFC
4648 and RFC 2045.
Base64 Methods:
Methods Description
public static Base64.Decoder getDecoder() It returns a Base64.Decoder that decodes
using the Basic type base64 encoding scheme.

public static Base64.Encoder getEncoder() It returns a Base64.Encoder that encodes


using the Basic type base64 encoding scheme.

public static Base64.Decoder getUrlDecoder() It returns a Base64.Decoder that decodes


using the URL and Filename safe type base64
encoding scheme.
public static Base64.Decoder It returns a Base64.Decoder that decodes
getMimeDecoder() using the MIME type base64 decoding scheme.

public static Base64.Encoder It Returns a Base64.Encoder that encodes


getMimeEncoder() using the MIME type base64 encoding scheme.

public static Base64.Encoder It returns a Base64.Encoder that encodes


getMimeEncoder(int lineLength, byte[] using the MIME type base64 encoding scheme
lineSeparator) with specified line length and line separators.

public static Base64.Encoder getUrlEncoder() It returns a Base64.Encoder that encodes


using the URL and Filename safe type base64
encoding scheme.
Base64.Decoder Methods:
Methods Description
public byte[] decode(byte[] src) It decodes all bytes from the input byte array using
the Base64 encoding scheme, writing the results into
a newly-allocated output byte array. The returned
byte array is of the length of the resulting bytes.

public byte[] decode(String src) It decodes a Base64 encoded String into a newly-
allocated byte array using the Base64 encoding
scheme.

public int decode(byte[] src, byte[] dst) It decodes all bytes from the input byte array using
the Base64 encoding scheme, writing the results into
the given output byte array, starting at offset 0.

public ByteBuffer decode(ByteBuffer buffer) It decodes all bytes from the input byte buffer using
the Base64 encoding scheme, writing the results into
a newly-allocated ByteBuffer.

public InputStream wrap(InputStream is) It returns an input stream for decoding Base64
encoded byte stream.
Base64.Encoder Methods:
Methods Description
public byte[] encode(byte[] src) It encodes all bytes from the specified byte array into a
newly-allocated byte array using the Base64 encoding
scheme. The returned byte array is of the length of the
resulting bytes.
public int encode(byte[] src, byte[] dst) It encodes all bytes from the specified byte array using the
Base64 encoding scheme, writing the resulting bytes to
the given output byte array, starting at offset 0.

public String encodeToString(byte[] src) It encodes the specified byte array into a String using the
Base64 encoding scheme.
public ByteBuffer encode(ByteBuffer buffer) It encodes all remaining bytes from the specified byte
buffer into a newly-allocated ByteBuffer using the Base64
encoding scheme. Upon return, the source buffer's
position will be updated to its limit; its limit will not have
been changed. The returned output buffer's position will
be zero and its limit will be the number of resulting
encoded bytes.

public OutputStream wrap(OutputStream It wraps an output stream for encoding byte data using the
os) Base64 encoding scheme.
public Base64.Encoder withoutPadding() It returns an encoder instance that encodes equivalently
to this one, but without adding any padding character at
the end of the encoded byte data.
Basic Encoding and Decoding
It uses the Base64 alphabet specified by Java in RFC 4648 and RFC 2045 for
encoding and decoding operations. The encoder does not add any line separator
character. The decoder rejects data that contains characters outside the base64
alphabet.
Example:
import java.util.Base64;
public class EncryptionExample { Output :
public static void main(String[] args) {
// Getting encoder
Base64.Encoder encoder = Base64.getEncoder();
// Creating byte array
byte byteArr[] = {1,2};
// encoding byte array
byte byteArr2[] = encoder.encode(byteArr);
System.out.println("Encoded byte array: "+byteArr2);
byte byteArr3[] = new byte[5]; // Make sure it has enough size to store copied bytes
int x = encoder.encode(byteArr,byteArr3); // Returns number of bytes written
System.out.println("Encoded byte array written to another array: "+byteArr3);
System.out.println("Number of bytes written: "+x);

// Encoding string
String str = encoder.encodeToString("Welcome To IIMT".getBytes());
System.out.println("Encoded string: "+str);
// Getting decoder
Base64.Decoder decoder = Base64.getDecoder();
// Decoding string
String dStr = new String(decoder.decode(str));
System.out.println("Decoded string: "+dStr);
}
}
URL and Filename Encoding and Decoding
It uses the Base64 alphabet specified by Java in RFC 4648 for encoding and
decoding operations. The encoder does not add any line separator character. The
decoder rejects data that contains characters outside the base64 alphabet.
Example:
import java.util.Base64;
public class URLEncryptionExample {
public static void main(String[] args) {
// Getting encoder
Base64.Encoder encoder = Base64.getUrlEncoder();
// Encoding URL
String eStr = encoder.encodeToString("http://www.google.com".getBytes());
System.out.println("Encoded URL: "+eStr);
// Getting decoder
Base64.Decoder decoder = Base64.getUrlDecoder();
// Decoding URl
String dStr = new String(decoder.decode(eStr));
System.out.println("Decoded URL: "+dStr);
}
}
Output :
Java forEach Method
• Java provides a new method forEach() to iterate the
elements. It is defined in Iterable and Stream interface. It
is a default method defined in the Iterable interface.
Collection classes which extends Iterable interface can
use forEach loop to iterate elements.

• This method takes a single parameter which is a


functional interface. So, you can pass lambda
expression as an argument.

Syntax:
default void forEach(Consumer<super T>action)
forEach() Example :
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing lambda expression--------------");
gamesList.forEach(games -> System.out.println(games));
}
}

------------Iterating by passing lambda expression--------------


Output : Football
Cricket
Chess
Hocky
Java Annotations
• Java Annotation is a tag that represents the metadata i.e. attached with class,
interface, methods or fields to indicate some additional information which can be
used by java compiler and JVM.
• Annotations in Java are used to provide additional information, so it is an alternative
option for XML and Java marker interfaces.
• There are two types of Annotations :
1. Built-in annotations
2. Custom annotations
1. Built-in Annotations
• There are several built-in annotations in Java. Some annotations are applied to
Java code and some to other annotations.
• Built-In Java Annotations used in Java code
 @Override
 @SuppressWarnings
 @Deprecated
• Built-In Java Annotations used in other annotations
 @Target
 @Retention
 @Inherited
 @Documented
@Override
• @Override annotation assures that the subclass method is overriding the parent class
method. If it is not so, compile time error occurs.
• Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.
Import java.util.*; Import java.util.*;
class Rect class Cuboid extends Rect
{ {
int l,b; int h;
public void GetData() @Override
{ public void GetData()
Scanner t=new Scanner(System.in); {
System.out.print(“\nEnter Length : “); super.GetData();
l=t.nextInt(); System.out.print(“\nEnter Height : “);
System.out.print(“\nEnter Breadth : “); h=t.nextInt();
b=t.nextInt(); }
} @Override
public void Display() public void Display()
{ {
System.out.print(“\nLength : “ + l); Super.Display();
System.out.print(“\nBreadth : “ + b); System.out.print(“\nHeight : “ + h);
} }
} }
@SuppressWarnings
• @SuppressWarnings annotation: is used to suppress warnings issued
by the compiler.

@Deprecated
• @Deprecated annoation marks that this method is deprecated so
compiler prints warning. It informs user that it may be removed in
the future versions. So, it is better not to use such methods.
Java Type Annotations
• Java 8 has included two new features repeating and type annotations in
its prior annotations topic.
• In early Java versions, you can apply annotations only to declarations.
• After releasing of Java SE 8 , annotations can be applied to any type use.
It means that annotations can be used anywhere you use a type.
• For example, if you want to avoid NullPointerException in your code, you
can declare a string variable like this:
@NonNull String str;

Following are the examples of type annotations:


• @NonNull List<String>
• List<@NonNull String> str
• Arrays<@NonNegative Integer> sort
• @Encrypted File file
• @Open Connection connection
• void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticExcept
ion
Note - Java created type annotations to support improved analysis of Java
programs. It supports way of ensuring stronger type checking.
Java Repeating Annotations
• In Java 8 release, Java allows you to use repeating annotations in
your source code.
• It is helpful when you want to reuse annotation for the same class.
• You can repeat an annotation anywhere that you would use a
standard annotation.
• For compatibility reasons, repeating annotations are stored in a
container annotation that is automatically generated by the Java
compiler.

In order for the compiler to do this, two declarations are


required in your code :
1.Declare a repeatable annotation type
2.Declare the containing annotation type
1) Declare a repeatable annotation type
• Declaring of repeatable annotation type must be marked with the
@Repeatable meta-annotation.
• In the following example, we have defined a custom @Game
repeatable annotation type.
@Repeatable(Games.class)
@interfaceGame{
String name();
String day();
}

• The value of the @Repeatable meta-annotation, in parentheses, is


the type of the container annotation that the Java compiler
generates to store repeating annotations. In the following example,
the containing annotation type is Games. So, repeating @Game
annotations is stored in an @Games annotation.
2) Declare the containing annotation type
• Containing annotation type must have a value element with an
array type.
• The component type of the array type must be the repeatable
annotation type.
• In the following example, we are declaring Games containing
annotation type:

@interfaceGames{
Game[] value();
}
Java Switch Expression
• The Java switch statement executes one statement from multiple
conditions. It is like if-else-if ladder statement.
• The switch statement works with byte, short, int, long, enum types, String
and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you
can use strings in the switch statement.
• In other words, the switch statement tests the equality of a variable
against multiple values.
Important Points :
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only. The case value must
be literal or constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders
compile-time error.
• The Java switch expression must be of byte, short, int, long (with its Wrapper
type), enums and string.
• Each case statement can have a break statement which is optional. When
control reaches to the break statement, it jumps the control after the switch
expression. If a break statement is not found, it executes the next case.
• The case value can have a default label which is optional.
Java Switch Statement Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
......
default:
code to be executed if all
cases are not matched;
}
Switch Expression - Example
Let‘s understand Switch Expression with the following code:
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
Output :
case 20: System.out.println("20");
20
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Try-with-resources statement
• try-with-resources statement is a try statement that declares one or more resources.
• The resource is as an object that must be closed after finishing the program.
• The try-with-resources statement ensures that each resource is closed at the end of
the statement execution.
• You can pass any object that implements java.lang.AutoCloseable, which includes all
objects which implement java.io.Closeable.
Note - In a try-with-resources statement, catch or finally block executes after closing of
the declared resources.
Example :
import java.io.FileOutputStream;
public class TryWithResourcesDemo {
public static void main(String args[]){
// Using try-with-resources
try(FileOutputStream fileOutputStream =newFileOutputStream("abc.txt")){
String msg = "Welcome to IIMT!";
byte byteArray[] = msg.getBytes(); //converting string into byte array
fileOutputStream.write(byteArray);
System.out.println("Message written to file successfuly!");
}catch(Exception exception){
System.out.println(exception);}
}
Java 9 Module System
• Java Module System is a major change in Java 9 version. Java
added this feature to collect Java packages and code into a single
unit called module.
• In earlier versions of Java, there was no concept of module to
create modular Java applications, that’s why size of application
increased and difficult to move around. Even JDK itself was too
heavy in size.
• To deal with situation, Java 9 restructured JDK into set of
modules so that we can use only required module for our project.
• Apart from JDK, Java also allows us to create our own modules so
that we can develop module based application.
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
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
Internal working of given code

Person p=new Person(){


void eat(){System.out.println("nice fruits");}
};

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 class generated by the compiler

import java.io.PrintStream;
static class TestAnonymousInner$1 extends Person
{
TestAnonymousInner$1(){}
void eat()
{
System.out.println("nice fruits");
}
}
Diamond operator
• Diamond operator was introduced in Java 7 as a new feature. The main
purpose of the diamond operator is to simplify the use of generics when
creating an object. It avoids unchecked warnings in a program and makes the
program more readable. The diamond operator could not be used with
Anonymous inner classes in JDK 7. In JDK 9, it can be used with
the anonymous class as well to simplify code and improves readability.
Before JDK 7, we have to create an object with Generic type on both side of
the expression like:

// Here we mentioned the generic type


// on both side of expression while creating object
List<String> geeks = new ArrayList<String>();

When Diamond operator was introduced in Java 7, we can create the object
without mentioning generic type on right side of expression like:

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


Diamond operator for Anonymous Inner Class
• With the help of Diamond operator, we can create an object without mentioning the
generic type on the right hand side of the expression. But the problem is it will only
work with normal classes. Suppose you want to use the diamond operator for
anonymous inner class in jdk 7 then compiler will throw error message like this :

abstract class Sample<T> {


abstract T add(T num1, T num2);
}

public class DiamondDemo {


public static void main(String[] args)
{
Sample<Integer> obj = new Sample<>() {
Integer add(Integer n1, Integer n2)
{
return (n1 + n2);
}
};
Integer result = obj.add(10, 20);
System.out.println("Addition of two numbers: " + result);
}
}
Output in JDK 7 :
prog.java:9: error: cannot infer type arguments for Sample
Sample obj = new Sample() {
^
reason: cannot use '' with anonymous inner classes
where T is a type-variable:
T extends Object declared in class Sample
1 error

Java developer extended the feature of the diamond operator in JDK 9 by allowing the
diamond operator to be used with anonymous inner classes too. If we run the above
code with JDK 9, then code will run fine and we will generate the below output.

Output in jdk
Addition 9: numbers: 30
of two
Yield Keyword
• The yield keyword is used to exit from
a switch expression by returning a value that becomes
the value of the switch expression.
• This means we can assign the value of
a switch expression to a variable.
• Lastly, by using yield in a switch expression, we get an
implicit check that we’re covering our cases, which
makes our code more robust.
• The yield keyword can be used in two ways :
1. yield with Arrow Operator
2. yield with Colon Delimiter
yield with Arrow Operator - Example

String message = switch (n%2) {


case 0 -> {
yield “Even Number";
}
case 1 -> {
yield “Odd Number";
}
default -> {
yield “hi";
}
};
yield with Colon Operator - Example

String message = switch (n%2) {


case 0 :
yield “Even Number";
case 1 :
yield “Odd Number";
default :
yield “hi";
};
Unit -4
Java Collections Framework
Java Collection Framework
• Collections in Java
• Java Collection means a single unit of objects.
• The Collection in Java is a framework that provides an
architecture to store and manipulate the group of objects.
• Java Collections can achieve all the operations that you perform
on a data such as searching, sorting, insertion, manipulation,
and deletion.
• Java Collection framework provides many interfaces (Set, List,
Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet).
• What is Collection in Java
• A Collection represents a single unit of objects, i.e., a group.

• What is a framework in Java


• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.

• What is Collection framework


• The Collection framework represents a unified architecture for
storing and manipulating a group of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Hierarchy of Collection Framework
Iterable Interface
• This is the root interface for the entire collection framework. The
collection interface extends the iterable interface. Therefore,
inherently, all the interfaces and classes implement this interface. The
main functionality of this interface is to provide an iterator for the
collections.

• Definition of Iterable
public interface Iterable<T>
{
Iterator<T> iterator();

Spliterator<T> spliterator();

void forEach(Consumer<? super T> action);


}
Note : Here, T is the type of element returned by the Iterator.
Iterating an Iterable(any collection object) using Iterator
• Create an Iterator object by calling iterator() as follows :
Iterator<T> obj_name=collection_objname.iterator();

• Now, By using following methods of Iterator interface, we


can perform the operations :
• hasNext(): It returns false if we have reached the end of the
collection, otherwise returns true.
• next(): Returns the next element in a collection.
• remove(): Removes the last element returned by the iterator
from the collection.
• forEachRemaining(): Performs the given action for each
remaining element in a collection, in sequential order.
Example :
// Java Program to demonstrate iterate
// an Iterable using an Iterator
import java.io.*;
import java.util.*;
class Sample {
public static void main(String[] s)
{
List<String> books = new ArrayList<>();

books.add(“Java");
books.add(“Python");
books.add(“C#.net");

Iterator<String> t = books.iterator();

while (t.hasNext()) {
String element = t.next();
System.out.println(element); }
}
Collection Interface
• The Collection interface is the interface which is
implemented by all the classes in the collection
framework. It declares the methods that every
collection will have. In other words, we can say that the
Collection interface builds the foundation on which the
collection framework depends.
• This interface contains all the basic methods which
every collection has like adding the data into the
collection, removing the data, clearing the data, etc.
Methods of Collection Interface
METHOD DESCRIPTION
add​(E e) Ensures that this collection contains the specified element (optional operation).

Adds all the elements in the specified collection to this collection (optional
addAll​(Collection<? extends E> c)
operation).

clear() Removes all the elements from this collection (optional operation).
contains​(Object o) Returns true if this collection contains the specified element.
containsAll​(Collection<?> c) Returns true if this collection contains all the elements in the specified collection.
equals​(Object o) Compares the specified object with this collection for equality.
isEmpty() Returns true if this collection contains no elements.
iterator() Returns an iterator over the elements in this collection.

Removes a single instance of the specified element from this collection, if it is


remove​(Object o)
present (optional operation).

Removes all of this collection’s elements that are also contained in the specified
removeAll​(Collection<?> c)
collection (optional operation).

removeIf​(Predicate<? super E> filter) Removes all the elements of this collection that satisfy the given predicate.
size() Returns the number of elements in this collection.
toArray() Returns an array containing all the elements in this collection.

Returns an array containing all the elements in this collection; the runtime type of
toArray​(T[] a)
the returned array is that of the specified array.
List Interface
• It is a child interface of the Collection interface.
• This interface is dedicated to the data of the list type in which
we can store all the ordered collections of the objects.
• This deals with the index or position-specific functions like
getting an element or setting an element.
• It deals with the arrays and lists types of operations.
• List interface is implemented by the classes ArrayList,
LinkedList, Vector, and Stack.
• A List interface can be instantiated as follows :
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
Methods of List Interface
Method Description
This method is used with Java List Interface to add an element at a particular index in the list. When a
add(int index, element)
single parameter is passed, it simply adds the element at the end of the list.

This method is used with List Interface in Java to add all the elements in the given collection to the list.
addAll(int index, Collection collection)
When a single parameter is passed, it adds all the elements of the given collection at the end of the list.

size() This method is used with Java List Interface to return the size of the list.
This method is used to remove all the elements in the list. However, the reference of the list created is
clear()
still stored.
This method removes an element from the specified index. It shifts subsequent elements(if any) to left
remove(int index)
and decreases their indexes by 1.
This method is used with Java List Interface to remove the first occurrence of the given element in the
remove(element)
list.
get(int index) This method returns elements at the specified index.
This method replaces elements at a given index with the new element. This function returns the element
set(int index, element)
which was just replaced by a new element.
This method returns the first occurrence of the given element or -1 if the element is not present in the
indexOf(element)
list.
This method returns the last occurrence of the given element or -1 if the element is not present in the
lastIndexOf(element)
list.
This method is used with Java List Interface to compare the equality of the given element with the
equals(element)
elements of the list.
This method is used with Java List Interface to check if the list is empty or not. It returns true if the list is
isEmpty()
empty, else false.
This method is used with List Interface in Java to check if the list contains the given element or not. It
contains(element)
returns true if the list contains the element.
ArrayList Class
• ArrayList class implements the List interface.
• This class is available in java.util package.
• This class provides dynamic arrays in Java.
• The elements stored in the ArrayList class can be randomly
accessed.
• We can not create an array list of the primitive types, such as int,
float, char, etc. It is required to use the required wrapper class in
such cases. For example:
• ArrayList<int> al = ArrayList<int>(); // does not work
• ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
• An object of an ArrayList can be instantiated as follows :
1. ArrayList objname=new ArrayList();
2. ArrayList objname=new ArrayList(size);
3. ArrayList objname=new ArrayList(Collection objname);
Example of ArrayList Class :
// Java program to Demonstrate ArrayList class
import java.util.*;

class ArrayListDemo {
// Removes element from index 1
public static void main(String[] args)
l1.remove(1);
{

ArrayList<Integer> l1 = new ArrayList<Integer>();


// Printing the updated List 1
// Adding elements to object of ArrayList System.out.println(l1);
l1.add(0, 1);

l1.add(1, 2); // Prints element at index 3 in list 1


// using get() method
// Print the elements inside the object
System.out.println(l1.get(3));
System.out.println(l1);

// Replace 0th element with 5


// Now creating another object of the ArrayList
// in List 1
ArrayList<Integer> l2 = new ArrayList<Integer>();
l1.set(0, 5);
// Adding elements to second object of ArrayList

l2.add(1);
// Again printing the updated List 1
l2.add(2); System.out.println(l1);
l2.add(3); }
}
// Will add all elements of list l2 in the list l1 from 1 index

l1.addAll(1, l2);

System.out.println(l1);
Output :

[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]
LinkedList Class
• LinkedList class implements the List interface.
• This class is available in java.util package.
• This class uses a doubly linked list internally to store the
elements.
• In LinkedList, the manipulation is fast because no shifting is
required.
• An object of a LinkedList can be instantiated as follows :
1. LinkedList objname=new LinkedList();
2. LinkedList objname=new LinkedList(Collection objname);
Example of LinkedList Class :
// Java program to Demonstrate LinkedList class
import java.util.*;

public class LinkedListDemo {


public static void main(String args[])
{
// Creating object of the class linked list
LinkedList<String> l1 = new LinkedList<String>();

// Adding elements to the linked list


l1.add("A");
l1.add("B");
l1.addLast("C");
l1.addFirst("D");
l1.add(2, "E");

System.out.println(l1);

l1.remove("B");
l1.remove(3);
l1.removeFirst();
l1.removeLast();

System.out.println(l1);
}
}
Output :

[D, A, E, B, C]
[A]
Vector Class
• Vector class implements the List interface.
• This class is available in java.util package.
• Vector class uses a dynamic array to store the data
elements.
• It is similar to ArrayList. However, It is synchronized and has
some legacy methods that the collection framework does
not contain.
• An object of a Vector can be instantiated as follows :
1. Vector<T> objname=new Vector<T>();
2. Vector<T> objname=new Vector<T>(size);
3. Vector<T> objname=new Vector<T>(size,incr);
4. Vector<T> objname=new Vector<T>(Collection objname);
Example of Vector Class :
// Java program to Demonstrate Vector class
import java.io.*; // Displaying the vector after deletion
import java.util.*; System.out.println(v);

class VectorDemo { // iterating over vector elements


public static void main(String[] args) // using for loop
{ for (int i = 0; i < v.size(); i++)
// Size of the Vector
int n = 5;
// Printing elements one by one
System.out.print(v.get(i) + " ");
// Declaring the Vector with initial size n
}
Vector<Integer> v = new Vector<Integer>(n);
}

// Appending new elements at the end of the vector


for (int i = 1; i <= n; i++)
v.add(i);

// Printing elements
System.out.println(v);

// Remove element at index 3


v.remove(3);
Output :

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Stack Class
• Stack class extends the Vector class.
• This class is available in java.util package.
• Stack class models and implements a Stack data structure.
The class is based on the basic principle of LIFO(last-in-first-
out).
• In addition to the basic push and pop operations, the class
provides three more functions of empty, search, and peek.
• An object of a Stack can be instantiated as follows :
Stack objname=new Stack();
Or
Stack<T> objname=new Stack<T>();
Methods of Stack Class
Method Method Description
empty() The method checks the stack is empty or not.

push(E item) The method pushes (insert) an element onto


the top of the stack.

pop() The method removes an element from the top


of the stack and returns the same element as
the value of that function.

peek() The method returns the top element of the


stack without removing it.
search(Object o) The method searches the specified object and
returns the position of the object.
Example of Stack Class :
// Java program to Demonstrate Stack class
import java.util.*; //performing pop operation
public class StackDemo Integer n= (Integer) stk.pop();
{ System.out.println(n);
public static void main (String[] args) //prints modified stack
{ System.out.println("stack: " + stk);
Stack stk = new Stack(); // Access element from the top of the stack
boolean b=stk.empty(); Integer r = (Integer) stk.peek();
System.out.println("Is the stack empty or not? " + b); System.out.println("Element at top: " + r);
stk.push(22); // prints stack
stk.push(33); System.out.println(“Stack: " + stk);
stk.push(44); // Search an element
stk.push(55); int location = stk.search(44);
stk.push(66); System.out.println("Location of 44: " + location);
//prints stack }
System.out.println("stack: " + stk); }
// Checks the Stack is empty or not
b=stk.empty();
System.out.println("Is the stack empty or not? " +b);
// Find the size of the Stack
int x=stk.size();
System.out.println("The stack size is: "+x);
Output :

Is the stack empty or not? true


stack: 22 33 44 55 66
Is the stack empty or not? false
The stack size is: 5
66
stack: 22 33 44 55
Element at top: 55
stack: 22 33 44 55
Location of 44: 2
Queue Interface
• The interface Queue is available in the java.util package and
does extend the Collection interface.
• It is used to keep the elements that are processed in the First
In First Out (FIFO) manner.
• It is an ordered list of objects, where insertion of elements
occurs at the end(known as rear) of the list, and removal of
elements occur at the beginning(known as front) of the list.
• Being an interface, the Queue requires, for the declaration, a
concrete class, and the most common classes are the
LinkedList, ArrayDeque and PriorityQueue in Java.
• A Queue interface can be instantiated as follows :
Queue<String> q1 = new PriorityQueue<String>();
Queue<String> q2 = new LinkedList<String>();
Methods of Queue Interface
Method Description
Adds an element to the rear of the queue. If the queue
add(element)
is full, it throws an exception.

Adds an element to the rear of the queue. If the queue


offer(element)
is full, it returns false.

Removes and returns the element at the front of the


remove()
queue. If the queue is empty, it throws an exception.

Removes and returns the element at the front of the


poll()
queue. If the queue is empty, it returns null.
Returns the element at the front of the queue without
element() removing it. If the queue is empty, it throws an
exception.
Returns the element at the front of the queue without
peek()
removing it. If the queue is empty, it returns null.
Example1 of Queue Interface :
// Java program to Demonstrate Queue Interface using LinkedList
import java.util.*;
// add another element to the queue
public class QueueExample {
queue.add("date");
public static void main(String[] args)
{
// peek at the element at the front of the queue
Queue<String> queue = new LinkedList<>();
String peeked = queue.peek();
// add elements to the queue System.out.println("Peeked element: " + peeked);
queue.add("apple");
queue.add("banana"); // print the updated queue
queue.add("cherry"); System.out.println("Queue after peek: " + queue);

// print the queue // Rest all methods of collection


System.out.println("Queue: " + queue); // interface like size and contains
// can be used with this implementation.
// remove the element at the front of the queue
int size = queue.size();
String front = queue.remove();
System.out.println("Size of queue-"
System.out.println("Removed element: " + front);
+ size);
}
// print the updated queue
}
System.out.println("Queue after removal: " +
queue);
Output :
Queue: [apple, banana, cherry]
Removed element: apple
Queue after removal: [banana, cherry]
Peeked element: banana
Queue after peek: [banana, cherry, date]
Size of queue: 3
Example2 of Queue Interface :
// Java program to Demonstrate Queue Interface using PriorityQueue
// Note: The insertion order is not retained in the PriorityQueue. The elements are
// stored based on the priority order which is ascending by default.
import java.util.*;
public class QueueExample {
public static void main(String[] args)
{
Queue<String> queue = new PriorityQueue<>();

// add elements to the queue


queue.add("banana");
queue.add("apple");
queue.add("cherry");

// print the queue


System.out.println(“Initial Queue: " + queue);

// remove the element at the front of the queue


queue.remove(“cherry”);
System.out.println(“Queue After Remove: " + queue);
System.out.println("Poll Method " + queue.poll());
System.out.println("Final Queue " + queue);
}
}
Output :

Initial Queue [apple, banana, cherry]


Queue After Remove [apple, banana]
Poll Method apple
Final Queue [banana]
Set Interface
• The interface Set is available in the java.util package and does
extend the Collection interface.
• It represents the unordered set of elements which doesn't
allow us to store the duplicate items.
• We can store at most one null value in Set.
• Set interface is implemented by HashSet, LinkedHashSet,
and TreeSet classes.
• A Set interface can be instantiated as follows :
Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();
HashSet Class
• This class is available in java.util package and implements Set interface.
• Java HashSet class is used to create a collection that uses a hash table for
storage.
• HashSet stores the elements by using a mechanism called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion order. Here, elements are
inserted on the basis of their hashcode.
• HashSet is the best approach for search operations.
• The initial default capacity of HashSet is 16.
• An object of a HashSet can be instantiated as follows :
HashSet objname=new HashSet();
Or
HashSet <T> objname=new HashSet <T>();
Methods of HashSet Class
Method Description
It is used to add the specified element to this set
add(element)
if it is not already present.
It is used to remove the specified element
remove(Object o)
from this set if it is present.
It is used to remove all of the elements from
clear()
the set.
It is used to return true if this set contains no
isEmpty()
elements.
It is used to return the number of elements in
size()
the set.
It is used to return an iterator over the
iterator()
elements in this set.
Example of HashSet Class:
import java.util.*; //Removing elements on the basis of specified condition
class HashSetDemo{ set.removeIf(str->str.contains("Vijay"));
public static void main(String args[]){ System.out.println("After removing : "+set);
HashSet<String> set=new HashSet<String>(); //Removing all the elements available in the set
set.add("Ravi"); set.clear();
set.add("Vijay"); System.out.println("After removing all elements:
set.add("Arun"); "+set);
set.add(“Vijay"); }
set.add("Sumit"); }
System.out.println(“Initial list : "+set);
//Removing specific element from HashSet
set.remove("Ravi");
System.out.println(“List After remove: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
System.out.println("Updated List: "+set);
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After removing: "+set);
Output :

An initial list of elements: [Vijay, Ravi, Arun, Sumit]


After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []
LinkedHashSet Class
• This class is available in java.util package.
• It inherits the HashSet class and implements the Set interface.
• LinkedHashSet class is a Hashtable and Linked list implementation
of the Set interface.
• Java LinkedHashSet class contains unique elements only like
HashSet.
• Java LinkedHashSet class provides all optional set operations and
permits null elements.
• Java LinkedHashSet class is non-synchronized.
• Java LinkedHashSet class maintains insertion order.
• An object of a LinkedHashSet can be instantiated as follows :
LinkedHashSet objname=new LinkedHashSet();
Or
LinkedHashSet <T> objname=new LinkedHashSet <T>();
Example of LinkedHashSet Class:
import java.util.*; // Removing an element from the above linked Set
public class LinkedHashSetDemo
// since the element “C#.net" is present, therefore, the meth
{ od remove() will return true
public static void main(String argvs[]) System.out.println(lhs.remove(“C#.net"));
{
// After removing the element
// Creating an empty LinekdhashSet of string type
System.out.println("After removing the element, the hash set
LinkedHashSet<String> lhs = new LinkedHashSet<St is: " + lhs);
ring>();
// since the element “Oracle" is not present, therefore, the m
// Adding elements to the above Set ethod remove() will return false
System.out.println(lhs.remove(“Oracle"));
lhs.add(“C");
lhs.add(“C++"); }
lhs.add(“Java"); }
lhs.add(“C#.net");
lhs.add(“Python");

// displaying all the elements


System.out.println("The hash set is: " + lhs);
Output :

The hash set is: [C, C++, Java, C#.net, Python ]


true
After removing the element, the hash set is: [C, C++, Java, Python ]
false
SortedSet Interface
• The interface SortedSet is available in the java.util package
and does extend the Set interface.
• SortedSet is the alternate of Set interface that provides a
total ordering on its elements. The elements of the
SortedSet are arranged in the increasing (ascending) order.
• SortedSet interface is implemented by TreeSet class.
• A SortedSet interface can be instantiated as follows :
SortedSet<data-type> obj_name = new TreeSet();
Methods of SortedSet Interface
Method Description
first() Returns the first element from the current set.

This method returns the elements which are


headSet(E toElement) less than the given element that are present in
the sorted set.
Returns the reverse order view of the mapping
last()
which present in the map.
This method returns the elements which are
tailSet(E fromElement) greater than or equal to the element that are
present in the sorted set.
Returns a key-value mapping which is
subSet(E fromElement, E associated with the greatest key which is less
toElement) than or equal to the given key. Also, returns null
if the map is empty.
TreeSet Class

• This class is available in java.util package and implements Set interface.


• Java TreeSet class is used tree for storage.
• Java TreeSet class contains unique elements only like HashSet.
• Java TreeSet class access and retrieval times are quiet fast.
• Java TreeSet class doesn't allow null element.
• Java TreeSet class is non synchronized.
• Java TreeSet class maintains ascending order.
• An object of a TreeSet can be instantiated as follows :
TreeSet objname=new TreeSet();
Or
TreeSet <T> objname=new TreeSet <T>();
Example of SortedSet interface & TreeSet Class:
import java.util.*; /*Returns a view of the portion of the given set
public class SortedSetExample { whose elements are strictly less than the given Element.
*/
public static void main(String[] args) { System.out.println("The respective element is given as: " +
SortedSet set = new TreeSet(); set.headSet("Baleno"));
// Add the elements in the given set.
/*Returns a view of the portion of the given set
set.add("Audi");
whose elements are strictly greater than or equal
set.add("BMW"); to the given Element.
set.add("Mercedes"); */
System.out.println("The respective element is given as: " +
set.add("Baleno"); set.tailSet(“BMW"));
System.out.println("The list of elements:"); }
System.out.println(set); }

//Returns the last element


System.out.println(“First element: " + set.first());

//Returns the last element


System.out.println(“Last element: " + set.last());
Output :

The list of elements: [Audi, BMW, Baleno, Mercedes]


First Element: Audi
Lastst Element: Mercedes
The respective element is given as: [Audi, BMW]
The respective element is given as: [BMW, Baleno, Mercedes]
Map Interface
• A map contains values on the basis of key, i.e. key and value
pair.
• Each key and value pair is known as an entry. A Map
contains unique keys.
• A Map is useful if you have to search, update or delete
elements on the basis of a key.
• A Map doesn't allow duplicate keys, but you can have
duplicate values.
• There are two interfaces for implementing Map in java: Map
and SortedMap, and three classes: HashMap,
LinkedHashMap, and TreeMap.
Java Map Hierarchy
Methods of Map Interface
Method Description
V put(Object key, Object value) It is used to insert an entry in the map.
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only
if it is not already specified.
V remove(Object key) It is used to delete an entry for the specified key.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys
from the map.
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys and values.
void clear() It is used to reset the map.
boolean containsValue(Object value) This method returns true if some value equal to the value exists
within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key exists within
the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
V get(Object key) This method returns the object that contains the value associated
with the key.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or
defaultValue if the map contains no mapping for the key.
boolean isEmpty() This method returns true if the map is empty; returns false if it
contains at least one key.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> It replaces each entry's value with the result of invoking the given
function) function on that entry until all entries have been processed or the
function throws an exception.
Collection values() It returns a collection view of the values contained in the map.
int size() This method returns the number of entries in the map.
HashMap Class

• This class is available in java.util package and implements Map


interface which allows us to store key and value pair, where keys
should be unique. If you try to insert the duplicate key, it will
replace the element of the corresponding key.
• Java HashMap may have one null key and multiple null values.
• Java HashMap is non synchronized.
• Java HashMap maintains no order.
• The initial default capacity of Java HashMap class is 16.
• An object of a HashMap can be instantiated as follows :
HashMap<K,V> objname=new HashMap<K,V>();
Or
HashMap<K,V> objname=new HashMap<K,V>(capacity);
Methods of HashMap Class
Method Description
V put(Object key, Object value) It is used to insert an entry in the map.
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only
if it is not already specified.
V remove(Object key) It is used to delete an entry for the specified key.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys
from the map.
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys and values.
void clear() It is used to reset the map.
boolean containsValue(Object value) This method returns true if some value equal to the value exists
within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key exists within
the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
V get(Object key) This method returns the object that contains the value associated
with the key.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or
defaultValue if the map contains no mapping for the key.
boolean isEmpty() This method returns true if the map is empty; returns false if it
contains at least one key.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> It replaces each entry's value with the result of invoking the given
function) function on that entry until all entries have been processed or the
function throws an exception.
Collection values() It returns a collection view of the values contained in the map.
int size() This method returns the number of entries in the map.
Example of Map interface & HashMap Class:
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> m1=new HashMap<Integer,String>(); //Creating HashMap
m1.put(1,"Mango"); //Put elements in Map
m1.put(2,"Apple");
m1.put(3,"Banana");
m1.put(1,"Grapes"); //trying duplicate key

System.out.println("Initial list of elements: "+m1);

System.out.println("Iterating Hashmap...");
for(Map.Entry m : m1.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output :

Initial list of elements: {1=Grapes, 2=Apple, 3=Banana}


Iterating Hashmap...
1 Grapes
2 Apple
3 Banana
Example of Map interface & HashMap Class:
import java.util.*; HashMap<Integer,String> hm2=new HashMap<Integer,String
class HashMapExaple2{ >();
hm2.put(104,"Ravi");
public static void main(String args[]){
hm2.putAll(hm1);
HashMap<Integer,String> hm1=new HashMap<Int System.out.println("Iterating Hashmap...");
eger,String>(); for(Map.Entry m:hm2.entrySet()){
System.out.println("Initial list of elements: "+hm1); System.out.println(m.getKey()+" "+m.getValue());
hm1.put(100,"Amit"); }

hm1.put(101,"Vijay");
System.out.println("Initial list of elements: "+hm1);
hm1.put(102,"Rahul"); //key-based removal
hm1.remove(100);
System.out.println("Iterating Hashmap..."); System.out.println("Updated list of elements: "+hm1);
//value-based removal
for(Map.Entry m:hm1.entrySet()){
hm1.remove(“Rahul”);
System.out.println(m.getKey()+" "+m.getValue()); }
System.out.println("Updated list of elements: "+hm1);
hm1.putIfAbsent(103, "Gaurav"); //key-value pair based removal
hm1.remove(101, “Vijay");
System.out.println("Iterating Hashmap..."); System.out.println("Updated list of elements: "+hm1);

for(Map.Entry m:hm1.entrySet()){
}
System.out.println(m.getKey()+" "+m.getValue()); } }
Output : Initial list of elements: {}
Iterating Hashmap...
100 Amit
101 Vijay
102 Rahul
Iterating Hashmap...
100 Amit
101 Vijay
102 Rahul
103 Gaurav
Iterating Hashmap...
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
103 Gaurav
Updated list of elements:
101 Vijay
102 Rahul
103 Gaurav
Updated list of elements:
101 Vijay
103 Gaurav
Updated list of elements:
103 Gaurav
LinkedHashMap Class
• This class is available in java.util package.
• It inherits HashMap class and implements the Map interface.
• LinkedHashMap class is Hashtable and Linked list implementation of the
Map interface.
• LinkedHashMap contains values based on the key.
• LinkedHashMap contains unique elements.
• LinkedHashMap may have one null key and multiple null values.
• LinkedHashMap is non synchronized.
• LinkedHashMap maintains insertion order.
• The initial default capacity of LinkedHashMap class is 16.
• An object of a LinkedHashMap can be instantiated as follows :
LinkedHashMap <K,V> objname=new LinkedHashMap<K,V>();
Or
LinkedHashMap <K,V> objname=new LinkedHashMap<K,V>(capacity);
Example of LinkedHashMap Class:
import java.util.*;
class LinkedHashMap1{
public static void main(String args[]){

LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();

hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output :

100 Amit
101 Vijay
102 Rahul
Example of LinkedHashMap Class:
import java.util.*;
class LinkedHashMap2{
public static void main(String args[]){
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Fetching key
System.out.println("Keys: "+map.keySet());
//Fetching value
System.out.println("Values: "+map.values());
//Fetching key-value pair
System.out.println("Key-Value pairs: "+map.entrySet());
}
}
Output :

Keys: [100, 101, 102]


Values: [Amit, Vijay, Rahul]
Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul]
TreeMap Class

• This class is available in java.util package.


• Java TreeMap class is a red-black tree based implementation. It
provides an efficient means of storing key-value pairs in sorted
order.
• Java TreeMap contains only unique elements.
• Java TreeMap cannot have a null key but can have multiple null
values.
• Java TreeMap is non synchronized.
• Java TreeMap maintains ascending order.
• An object of a TreeMap can be instantiated as follows :
TreeMap <K,V> objname=new TreeMap<K,V>();
Methods of TreeMap Class
Method Description
Map.Entry<K,V> ceilingEntry(K key) It returns the key-value pair having the least key, greater than or equal to the specified
key, or null if there is no such key.
K ceilingKey(K key) It returns the least key, greater than the specified key or null if there is no such key.
void clear() It removes all the key-value pairs from a map.
Map.Entry firstEntry() It returns the key-value pair having the least key.
Map.Entry<K,V> floorEntry(K key) It returns the greatest key, less than or equal to the specified key, or null if there is no such
key.
Map.Entry<K,V> higherEntry(K key) It returns the least key strictly greater than the given key, or null if there is no such key.
K higherKey(K key) It is used to return true if this map contains a mapping for the specified key.
Set keySet() It returns the collection of keys exist in the map.
Map.Entry<K,V> lastEntry() It returns the key-value pair having the greatest key, or null if there is no such key.
Map.Entry<K,V> lowerEntry(K key) It returns a key-value mapping associated with the greatest key strictly less than the given
key, or null if there is no such key.
K lowerKey(K key) It returns the greatest key strictly less than the given key, or null if there is no such key.
Map.Entry<K,V> pollFirstEntry() It removes and returns a key-value mapping associated with the least key in this map, or
null if the map is empty.
Map.Entry<K,V> pollLastEntry() It removes and returns a key-value mapping associated with the greatest key in this map,
or null if the map is empty.
V put(K key, V value) It inserts the specified value with the specified key in the map.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean containsKey(Object key) It returns true if the map contains a mapping for the specified key.
boolean containsValue(Object value) It returns true if the map maps one or more keys to the specified value.
K firstKey() It is used to return the first (lowest) key currently in this sorted map.
V get(Object key) It is used to return the value to which the map maps the specified key.
K lastKey() It is used to return the last (highest) key currently in the sorted map.
V remove(Object key) It removes the key-value pair of the specified key from the map.
Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the map.
int size() It returns the number of key-value pairs exists in the hashtable.
Collection values() It returns a collection view of the values contained in the map.
Example1 of TreeMap Class:
import java.util.*;
public class TreeMapDemo1 {
public static void main(String args[]) {
TreeMap<Integer,String> tm1=new TreeMap<Integer,String>();
tm1.put(100,"Amit");
tm1.put(102,"Ravi");
tm1.put(101,"Vijay");
tm1.put(103,"Rahul");
System.out.println("Iterating Treemap...");
for(Map.Entry m:tm1.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
tm1.remove(102);
System.out.println("After invoking remove() method");
for(Map.Entry m:tm1.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output :

Iterating Treemap...
100 Amit
101 Vijay
102 Ravi
103 Rahul
After invoking remove() method
100 Amit
101 Vijay
103 Rahul
Example2 of TreeMap Class:
import java.util.*;
class TreeMapDemo2{
public static void main(String args[]){
TreeMap<Integer,String> tm1=new TreeMap<Integer,String>();
tm1.put(100,"Amit");
tm1.put(102,"Ravi");
tm1.put(101,"Vijay");
tm1.put(103,"Rahul");
//Maintains descending order
System.out.println(“DescendingMap: "+tm1.descendingMap());
//Returns key-value pairs whose keys are less than or equal to the specified key.
System.out.println("headMap: "+tm1.headMap(102,true));
//Returns key-value pairs whose keys are greater than or equal to the specified key.
System.out.println("tailMap: "+tm1.tailMap(102,true));
//Returns key-value pairs exists in between the specified key.
System.out.println("subMap: "+tm1.subMap(100, false, 102, true));
}
}
Output :

DescendingMap: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}


headMap: {100=Amit, 101=Vijay, 102=Ravi}
tailMap: {102=Ravi, 103=Rahul}
subMap: {101=Vijay, 102=Ravi}
HashTable Class
• This class is available in java.util package.
• Java Hashtable class implements a hashtable, which maps keys to
values.
• It inherits Dictionary class and implements the Map interface.
• A Hashtable is an array of a list. Each list is known as a bucket.
• Java Hashtable class contains unique elements.
• Java Hashtable class doesn't allow null key or value.
• Java Hashtable class is synchronized.
• The initial default capacity of Hashtable class is 11.
• An object of a Hashtable can be instantiated as follows :
Hashtable<K,V> objname=new Hashtable<K,V>();
Or
HashTable<K,V> objname=new HashTable <K,V>(capacity);
Example1 of HashTable Class:
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output :

103 Rahul
102 Ravi
101 Vijay
100 Amit
Example2 of HashTable Class:
import java.util.*;
public class Hashtable2 {
public static void main(String args[]) {
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
System.out.println("Before remove: "+ hm);
// Remove value for key 102
hm.remove(102);
System.out.println("After remove: "+ hm);
}
}
Output :

Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}


After remove: {103=Rahul, 101=Vijay, 100=Amit}
Example3 of HashTable Class:
import java.util.*;
class Hashtable3{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
//Here, we specify the if and else statement as arguments of the
method
System.out.println(hm.getOrDefault(101, "Not Found"));
System.out.println(hm.getOrDefault(105, "Not Found"));
}
}
Output :

Vijay
Not Found
Difference Between HashMap & HashTable Class
HashMap and Hashtable both are used to store data in key and value form.
Both are using hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that
are given below.
HashMap Hashtable
1) HashMap is non synchronized. It Hashtable is synchronized. It is
is not-thread safe and can't be thread-safe and can be shared with
shared between many threads many threads.
without proper synchronization code.
2) HashMap allows one null key and Hashtable doesn't allow any null key
multiple null values. or value.
3) HashMap is fast. Hashtable is slow.
4) HashMap is traversed by Iterator. Hashtable is traversed by
Enumerator and Iterator.
5)HashMap inherits Hashtable inherits Dictionary class.
AbstractMap class.
Sorting in Collection
• We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
• Collections class provides static method public void
sort(List L) for sorting the elements of a collection. If
collection elements are of Set or Map, we can use
TreeSet or TreeMap. However, we cannot sort the
elements of List. Collections class provides methods
for sorting the elements of List type elements also.
Note : To sort a List, List elements must be of the
Comparable type.
Example1 of Sorting(Ascending Order):
import java.util.*;
class TestSort1{
public static void main(String args[]){

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


al.add(“Manoj");
al.add("Shivam");
al.add(“Ankur");
al.add(“Kartik");

Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :
Ankur
Kartik
Manoj
Shivam
Example2 of Sorting(Descending Order):
import java.util.*;
class TestSort1{
public static void main(String args[]){

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


al.add(“Manoj");
al.add("Shivam");
al.add(“Ankur");
al.add(“Kartik");

Collections.sort(al,Collections.reverseOrder());
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :
Shivam
Manoj
Kartik
Ankur
Comparable Interface
• Comparable interface is used to order(sort) the objects of the
user-defined class. This interface is found in java.lang package
and contains only one method named compareTo(Object).
• It provides a single sorting sequence only, i.e., you can sort the
elements on the basis of single data member only. For example,
it may be rollno, name, age or anything else.
compareTo(Object obj) method
public int compareTo(Object obj): It is used to compare the
current object with the specified object. It returns
• positive integer, if the current object is greater than the
specified object.
• negative integer, if the current object is less than the
specified object.
• zero, if the current object is equal to the specified object.
Example1 of Comparable Interface to sort in ascending order:
import java.util.*; public class ComparableExample
{
class Student implements Comparable<Student>{ public static void main(String args[])
int rollno; {
String name; ArrayList<Student> al=new ArrayList<Student>();
int age;
al.add(new Student(101,"Vijay",23));
Student(int rn,String nm,int ag){
al.add(new Student(106,"Ajay",27));
this.rollno=rn;
al.add(new Student(105,"Jai",21));
this.name=nm;
this.age=ag;
Collections.sort(al);
}
for(Student st:al){
System.out.println(st.rollno+" "+st.name+"
public int compareTo(Student st){ "+st.age);
if(age==st.age) }
return 0;
}
else if(age>st.age)
}
return 1;
else
return -1;
}
}
Output :

105 Jai 21
101 Vijay 23
106 Ajay 27
Example2 of Comparable Interface to sort in descending order:
import java.util.*; public class ComparableExample
{
class Student implements Comparable<Student>{ public static void main(String args[])
int rollno; {
String name; ArrayList<Student> al=new ArrayList<Student>();
int age;
al.add(new Student(101,"Vijay",23));
Student(int rn,String nm,int ag){
al.add(new Student(106,"Ajay",27));
this.rollno=rn;
al.add(new Student(105,"Jai",21));
this.name=nm;
this.age=ag;
Collections.sort(al);
}
for(Student st:al){
System.out.println(st.rollno+" "+st.name+"
public int compareTo(Student st){ "+st.age);
if(age==st.age) }
return 0;
}
else if(age<st.age)
}
return 1;
else
return -1;
}
}
Output :

106 Ajay 27
101 Vijay 23
105 Jai 21
Comparator Interface

• Comparator interface is used to order(sort) the


objects of a user-defined class.
• This interface is found in java.util package and
contains two methods compare(Object
obj1,Object obj2) and equals(Object element).
• It provides multiple sorting sequences, i.e., you
can sort the elements on the basis of any data
member, for example, rollno, name, age or
anything else.
Methods of Comparator Interface

Method Description

public int compare(Object It compares the first


obj1, Object obj2) object with the
second object.
public boolean It is used to
equals(Object obj) compare the
current object with
the specified object.
Comparator Example

• Let's see the example of sorting the elements


of List on the basis of age and name. In this
example, we are creating 4 java classes:
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java
class Student
{
int rollno;
String name;
int age;
Student(int rn,String nm,int ag){
this.rollno=rn;
this.name=nm;
this.age=ag;
}
}
AgeComparator.java
import java.util.*;
class AgeComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2){
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
NameComparator.java

import java.util.*;
class NameComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
return s1.name.compareTo(s2.name);
}
}
Simple.java
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

System.out.println("Sorting by Name");

Collections.sort(al,new NameComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}

System.out.println("Sorting by age");

Collections.sort(al,new AgeComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output :

Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23

Sorting by age
105 Jai 21
101 Vijay 23
106 Ajay 27
Properties Class
• This is a built-in class available in java.util package.
• This class extends HashTable class.
• The properties object contains key and value pair both as
a string.
• The Properties class provides methods to get data from
the properties file and store data into the properties file.
• It can be used to get property value based on the
property key.
• It can also be used to get the properties of a system.
• An object of a Properties can be instantiated as follows :
Properties objname=new Properties();
Methods of Properties Class
Method Description
public void load(Reader r) It loads data from the Reader object.

public void load(InputStream is) It loads data from the InputStream object

public String getProperty(String key) It returns value based on the key.

public String getProperty(String key, String It searches for the property with the specified key.
defaultValue)
public void setProperty(String key, String value) It calls the put method of Hashtable.

public void list(PrintStream out) It is used to print the property list out to the
specified output stream.

public void list(PrintWriter out)) It is used to print the property list out to the
specified output stream.

public Enumeration<?> propertyNames()) It returns an enumeration of all the keys from the
property list.
public Set<String> stringPropertyNames() It returns a set of keys in from property list where
the key and its corresponding value are strings.

public void store(Writer w, String comment) It writes the properties in the writer object.

public void store(OutputStream os, String It writes the properties in the OutputStream object.
comment)
Example1 of Properties class to get all the system properties
import java.util.*;
import java.io.*;
public class PropertyDemo1
{
public static void main(String[] args)throws Exception
{

Properties p=System.getProperties();
Set set=p.entrySet();

Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = "+entry.getValue());
}
}
}
Output :

java.runtime.name = Java(TM) SE Runtime Environment


sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........
Example2 of Properties class to get information from the properties file-
Suppose, There is a property file by the name db.properties having
following two properties :
user=IIMT
password=India123
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output :

IIMT
India123
•Example3 of Properties class to create the properties file
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception
{
Properties p=new Properties();
p.setProperty("name",“IIMT Eng. College");
p.setProperty("email",“[email protected]");

p.store(new FileWriter("info.properties"),"Properties Example");

}
}
Unit -5
Java Spring Framework & Spring Boot
Java Spring Framework
• Spring is a lightweight framework.
• It can be thought of as a framework of
frameworks because it provides support to various
frameworks such as Struts, Hibernate,
Tapestry, EJB, JSF, etc.
• It was developed by Rod Johnson in 2003.
• Spring is a Dependency Injection Framework to make
java application loosely coupled.
• Spring framework makes the easy development of
JavaEE applications.
• The Spring framework comprises of several modules
such as Core, Beans, IOC, AOP, DAO, Context, ORM,
WEB MVC etc.
Advantages of Spring Framework
1. Predefined Templates
• Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So
there is no need to write too much code. It hides the basic steps of these technologies.
2. Loose Coupling
• The Spring applications are loosely coupled because of dependency injection.
3. Easy to test
• The Dependency Injection makes easier to test the application. The EJB or Struts
application require server to run the application but Spring framework doesn't require
server.
4. Lightweight
• Spring framework is lightweight because of its POJO(Plain Old Java Object)
implementation. The Spring Framework doesn't force the programmer to inherit any
class or implement any interface. That is why it is said non-invasive.
5. Fast Development
• The Dependency Injection feature of Spring Framework and it support to various
frameworks makes the easy development of JavaEE application.
6. Powerful abstraction
• It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.
7. Declarative support
• It provides declarative support for caching, validation, transactions and formatting.
Dependancy Injection
It is a design pattern.
Inversion Of Control (IOC) and Dependency Injection
These are the design patterns that are used to remove dependency from
the programming code. They make the code easier to test and maintain.
Let's understand this with the following code:
class Employee{
Address address;
Employee(){
address=new Address();
}
}
In such case, there is dependency between the Employee and Address
(tight coupling).
IOC makes the code loosely coupled. In such case, there is no need to
modify the code if our logic is moved to new environment.
In Spring framework, IOC container is responsible to inject the dependency.
We provide metadata to the IOC container either by XML file or
annotation.
Spring Modules
• The Spring framework comprises of many modules such as core, beans, context,
expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS,
Transaction, Web, Servlet, Struts etc. These modules are grouped into Test, Core
Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web (MVC /
Remoting) as displayed in the following diagram.
• Spring Core Container
• The Spring Core container contains core, beans,
context and expression language (EL) modules.
1. Core and Beans
• These modules provide IOC and Dependency
Injection features.
2. Context
• This module supports internationalization (I18N), EJB,
JMS, Basic Remoting.
3. Expression Language
• It is an extension to the EL defined in JSP. It provides
support to setting and getting property values,
method invocation, accessing collections and
indexers, named variables, logical and arithmetic
operators, retrieval of objects by name etc.
• AOP, Aspects and Instrumentation
• These modules support aspect oriented
programming implementation where you
can use Advices, Pointcuts etc. to decouple
the code.
• The aspects module provides support to
integration with AspectJ.
• The instrumentation module provides
support to class instrumentation and
classloader implementations.
• Data Access / Integration
• This group comprises of JDBC, ORM, OXM,
JMS and Transaction modules. These
modules basically provide support to
interact with the database.
• Web
• This group comprises of Web, Web-Servlet,
Web-Struts and Web-Portlet. These modules
provide support to create web application.
• Test
• This layer provides support of testing with
JUnit and TestNG.
Dependency Injection
• Dependency Injection (DI) is a design pattern that removes the dependency
from the programming code so that it can be easy to manage and test the
application.
• Dependency Injection makes our programming code loosely coupled and
easier for testing.
• In such case we provide the information from the external source such as
XML file.
Let‘s understand dependency injection with the following code:

class Employee{
Address address;
Employee(){
address=new Address();
}
}

In such case, there is dependency between the Employee and Address (tight
coupling).
In the Inversion of Control scenario(Dependency Injection),
we do this something like this:
class Employee{
Address address;
Employee(Address address){
this.address=address;
}
public void setAddress(Address address){
this.address=address;
}
}

In such case, instance of Address class is provided by external


souce such as XML file either by constructor or setter
method.
Two ways to perform Dependency Injection in Spring
framework

• Spring framework provides two ways to inject


dependency
• By Setter method
• By Constructor
1. Dependency Injection using Setter Method
class Student class Address
{ {
int id; String street;
String name; String city;
Address address; String state;
String country;
public void setId(int id) public void setStreet(String street)
{ {
this.street=street;
this.id=id
}
}
public void setCity(String city)
{
public void setName(String name)
this.city=city;
{
}
this.name=name public void setState(String state)
} {
this.state=state;
public void setAddress(Address address)
}
{ public void setCountry(String country)
this.address=address; {
} this.country=country;
} }
}
2. Dependency Injection using Constructor Method
class Student
{
int id;
String name;
Address address;
public Student(int id, String name, Address address)
{
this.id=id;
this.name=name;
this.address=address;
}
}

class Address
{
String street;
String city;
String state;
String country;
public Address(String street, String city, String State, String country)
{
this.street=street;
this.city=city;
this.state=state;
this.country=country;
}
}
IoC Container
• The IoC container is responsible to instantiate, configure
and assemble the objects. The IoC container gets
information from the XML file and works accordingly.
The main tasks performed by IoC container are:
• to instantiate the application class
• to configure the object
• to assemble the dependencies between the objects
• There are two types of IoC containers. They are:
• BeanFactory
• ApplicationContext
Difference between BeanFactory and the ApplicationContext

• The org.springframework.beans.factory.BeanFactory and the


org.springframework.context.ApplicationContext interfaces
acts as the IoC container. The ApplicationContext interface is
built on top of the BeanFactory interface. It adds some extra
functionality than BeanFactory such as simple integration with
Spring's AOP, message resource handling (for I18N), event
propagation, application layer specific context (e.g.
WebApplicationContext) for web application. So it is better to
use ApplicationContext than BeanFactory.
Using BeanFactory
• The XmlBeanFactory is the implementation class for the
BeanFactory interface. To use the BeanFactory, we need to
create the instance of XmlBeanFactory class as given below:

Resource resource=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(resource);
The constructor of XmlBeanFactory class receives the
Resource object so we need to pass the resource object to
create the object of BeanFactory.
Using ApplicationContext
• The ClassPathXmlApplicationContext class is the
implementation class of ApplicationContext interface. We
need to instantiate the ClassPathXmlApplicationContext
class to use the ApplicationContext as given below:

ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");

The constructor of ClassPathXmlApplicationContext class


receives string, so we can pass the name of the xml file to
create the instance of ApplicationContext.
Developing Spring Application

• To create Spring application, we are required


to perform following steps :
1. create the class
2. create the xml file to provide the values
3. create the test class
4. Load the spring jar files
5. Run the test class
1. Creating Java Class
public class Student {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public void displayInfo(){


System.out.println("Hello: "+name);
}
}

This is simple bean class, containing only one property name with its
getters and setters method. This class contains one extra method
named displayInfo() that prints the student name by the hello
message.
2. Creating xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="studentbean" class="Student">


<property name="name" value=“Amit Kumar"></property>
</bean>

</beans>

The bean element is used to define the bean for the given class.
The property subelement of bean specifies the property of the
Student class named name. The value specified in the property
element will be set in the Student class object by the IOC container.
3. Creating Test Class
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Test {


public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);

Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}

The Resource object represents the information of applicationContext.xml file. The


Resource is the interface and the ClassPathResource is the implementation class of
the Reource interface. The BeanFactory is responsible to return the bean.
The XmlBeanFactory is the implementation class of the BeanFactory. There are
many methods in the BeanFactory interface. One method is getBean(), which
returns the object of the associated class.
4. Load the jar files required for spring framework

• There are mainly three jar files required to run this


application.
• org.springframework.core-3.0.1.RELEASE-A
• com.springsource.org.apache.commons.logging-1.1.1
• org.springframework.beans-3.0.1.RELEASE-A

5. Run the test class


• Now run the Test class. You will get the output Hello: Amit
Kumar
AOP (Aspect Oriented Programming)
• One of the key components of Spring Framework is the Aspect oriented
programming (AOP) framework. Aspect-Oriented Programming entails
breaking down program logic into distinct parts called so-called
concerns. The functions that span multiple points of an application are
called cross-cutting concerns and these cross-cutting concerns are
conceptually separate from the application's business logic. There are
various common good examples of aspects like logging, auditing,
declarative transactions, security, caching, etc.
• The key unit of modularity in OOP is the class, whereas in AOP the unit
of modularity is the aspect. Dependency Injection helps you decouple
your application objects from each other and AOP helps you decouple
cross-cutting concerns from the objects that they affect. AOP is like
triggers in programming languages such as Perl, .NET, and others.
• Spring AOP module provides interceptors to intercept an application.
For example, when a method is executed, you can add extra
functionality before or after the method execution.
Spring - Bean
• The objects that form the backbone of your application and that are managed by the Spring
IoC container are called beans.
• A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC
container.
• These beans are created with the configuration metadata that you supply to the container.
For example, in the form of XML <bean/> definitions which we have already seen.
Example :
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-

<!-- A simple bean definition -->


<bean id="studentbean" class="Student">
<property name="name" value=“Amit Kumar"></property>
</bean>
</beans>
Bean Scopes
• When defining a <bean> we have the option of
declaring a scope for that bean. The Spring Framework
supports the following five scopes :
1. singleton
2. prototype
3. request
4. session
5. global-session
1. Singleton Scope
• If a scope is set to singleton, the Spring IoC container
creates exactly one instance of the object defined by
that bean definition. This single instance is stored in a
cache of such singleton beans, and all subsequent
requests and references for that named bean return
the cached object.
• The default scope is always singleton.
• The scope property can be set to singleton in the bean
configuration file, as follows :
<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = "singleton">
<!-- collaborators and configuration for this bean go here -->
</bean>
2. Prototype Scope
• If the scope is set to prototype, the Spring IoC container
creates a new bean instance of the object every time a
request for that specific bean is made.
• As a rule, use the prototype scope for all state-full beans
and the singleton scope for stateless beans.
• The scope property can be set to prototype in the bean
configuration file, as follows :
<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = “prototype">
<!-- collaborators and configuration for this bean go here -->
</bean>
3. Request Scope
• This creates a single bean instance per HTTP request.
• It is valid only in the context of a web
application.

4. Session Scope
• This creates a single bean instance per HTTP session.
• It is valid only in the context of a web
application.
5. GlobalSession Scope
• This creates a single bean instance per global HTTP session.
• It is valid only in the context of a web
application.
Bean Life Cycle
• Bean life cycle is managed by the spring container.
• When we run the program then, first of all, the spring
container gets started.
• After that, the container creates the instance of a bean as
per the request, and then dependencies are injected.
• And finally, the bean is destroyed when the spring container
is closed.
• Therefore, if you want to execute some code on the bean
instantiation and just after closing the spring container, then
you can write that code inside the custom init() method and
the destroy() method.
Note: We can choose a custom method name instead
of init() and destroy()
The following figure shows the process flow of the bean
life cycle :
Implementing Life Cycle of a Bean
• To implement life cycle of a bean , we are
required to perform following steps :
1. Firstly, we need to create a bean and
define the init() and destroy() methods in
the class.
2. Now, we need to configure the XML
file and need to register the init() and
destroy() methods in it.
3. Finally, we need to create a test class to
run this bean.
1. Creating a bean
public class Student {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public void displayInfo(){


System.out.println("Hello: "+name);
}
public void init(){
System.out.println("Bean is going through init.");
}
public void destroy() {
System.out.println("Bean will destroy now.");
}
}
2. Creating xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="studentbean" class="Student“ init-method = "init"


destroy-method = "destroy">

<property name="name" value=“Amit Kumar"></property>


</bean>

</beans>
3. Creating Test Class
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Test {


public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);

Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}

Output :
Bean is going through init.
Hello : Amit Kumar
Bean will destroy now.
Spring - Autowiring
• Autowiring in the Spring framework can inject
dependencies automatically.
• The Spring container detects those dependencies specified
in the configuration file and the relationship between the
beans. This is referred to as Autowiring in Spring.
• To enable Autowiring in the Spring application we should
use @Autowired annotation.
• Autowiring in Spring internally uses constructor injection.
• An autowired application requires fewer lines of code
comparatively but at the same time, it provides very little
flexibility to the programmer.
Autowiring Modes
1. No
• This mode tells the framework that autowiring is not supposed to
be done. It is the default mode used by Spring.
Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City"></bean>
2. byName
• It uses the name of the bean for injecting dependencies. However,
it requires that the name of the property and bean must be the
same. It invokes the setter method internally for autowiring.
Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byName"></bean>
3. byType
• It injects the dependency according to the type of the bean. It
looks up in the configuration file for the class type of the property.
If it finds a bean that matches, it injects the property. If not, the
program throws an error. The names of the property and bean can
be different in this case. It invokes the setter method internally for
autowiring.
• Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byType"></bean>
4. constructor
• It injects the required dependencies by invoking the constructor. It
works similar to the “byType” mode but it looks for the class type
of the constructor arguments. If none or more than one bean are
detected, then it throws an error, otherwise, it autowires the
“byType” on all constructor arguments.
• Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="constructor"></bean>
5. autodetect
• The autodetect mode uses two other modes for autowiring –
constructor and byType. It first tries to autowire via the
constructor mode and if it fails, it uses the byType mode for
autowiring. It works in Spring 2.0 and 2.5 but is deprecated from
Spring 3.0 onwards.
• Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire=“autodetect"></bean>
Spring Framework Annotations
• Spring Annotations are a form of metadata that provides data about a
program.
• Annotations are used to provide supplemental information about a
program. It does not have a direct effect on the operation of the code
they annotate. It does not change the action of the compiled program
Types of Spring Framework Annotations
Basically, there are 6 types of annotation available in the whole spring
framework.
1. Spring Core Annotations
2. Spring Web Annotations
3. Spring Boot Annotations
4. Spring Scheduling Annotations
5. Spring Data Annotations
6. Spring Bean Annotations
What is Web Socket?
• A Web Socket is a continuous two-way communication channel between
clients and servers. The client could be any web browser, and the server could
be any backend system. Using the HTTP request/response connections, the
WebSocket can transmit any number of protocols and can provide server-to-
client information without polling. It allows two-way data transfer in which we
can simultaneously transfer data from client to server and vice versa.
• The advanced technology opens an interactive two-way communication
between the client and server. By using the WebSocket API, we can send
information to the server and receive the runtime response without polling
the server for a response.
• The below image explains how WebSocket transfers the data:
What is Spring Boot?
• Spring Boot is an open-source Java framework used to
create a Micro Service.
• Spring boot is developed by Pivotal Team, and it
provides a faster way to set up and an easier, configure,
and run both simple and web-based applications.
• It is a combination of Spring Framework and Embedded
Servers.
• The main goal of Spring Boot is to reduce development,
unit test, and integration test time and in Spring Boot,
there is no requirement for XML configuration.
Advantages
• Easy to understand and develop spring applications
• Increases productivity
• Reduces the development time
Goals
• To avoid complex XML configuration in Spring
• To develop a production ready Spring applications in
an easier way
• To reduce the development time and run the
application independently
• Offer an easier way of getting started with the
application
How does it work?
• Spring Boot automatically configures your application
based on the dependencies you have added to the
project by
using @EnableAutoConfiguration annotation. For
example, if MySQL database is on your classpath, but
you have not configured any database connection, then
Spring Boot auto-configures an in-memory database.
• The entry point of the spring boot application is the
class contains @SpringBootApplication annotation and
the main method.
• Spring Boot automatically scans all the components
included in the project by
using @ComponentScan annotation.
Spring Boot Starters
• Handling dependency management is a difficult task for big
projects. Spring Boot resolves this problem by providing a set of
dependencies for developers convenience.
• For example, if you want to use Spring and JPA for database
access, it is sufficient if you include spring-boot-starter-data-
jpa dependency in your project.
Examples :
following are Spring Boot starters explained below for a better
understanding :
1. Spring Boot Starter Actuator dependency is used to monitor
and manage your application. Its code is shown below −

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2. Spring Boot Starter Security dependency is used for Spring Security.
Its code is shown below −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3. Spring Boot Starter Thyme Leaf dependency is used to create a web
application. Its code is shown below −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
4. Spring Boot Starter Test dependency is used for writing Test cases. Its
code is shown below −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
Spring Boot - Build Systems
In Spring Boot, choosing a build system is an important task. Maven
or Gradle is recommend as they provide a good support for
dependency management. Spring does not support well other build
systems.
• Dependency Management
Spring Boot team provides a list of dependencies to support the Spring Boot
version for its every release. You do not need to provide a version for
dependencies in the build configuration file. Spring Boot automatically
configures the dependencies version based on the release. Remember that
when you upgrade the Spring Boot version, dependencies also will upgrade
automatically.
Note − If you want to specify the version for dependency, you can
specify it in your configuration file. However, the Spring Boot team
highly recommends that it is not needed to specify the version for
dependency.
Maven Dependency
For Maven configuration, we should inherit the Spring
Boot Starter parent project to manage the Spring Boot
Starters dependencies. For this, simply we can inherit the
starter parent in our pom.xml file as shown below.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
Gradle Dependency
We can import the Spring Boot Starters dependencies
directly into build.gradle file. We do not need Spring Boot
start Parent dependency like Maven for Gradle. Observe
the code given below −
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
Spring Boot - Code Structure
Spring Boot does not have any code layout to work with.
However, there are some best practices as follows :
Default package
A class that does not have any package declaration is
considered as a default package. Note that generally a default
package declaration is not recommended. Spring Boot will
cause issues such as malfunctioning of Auto Configuration or
Component Scan, when you use default package.
Note − Java's recommended naming convention for
package declaration is reversed domain name. For
example − com.iimt.myproject
Typical Layout
The typical layout of Spring Boot application will be as
follows:
Spring Boot - Runners
Application Runner and Command Line Runner interfaces lets you to execute the
code after the Spring Boot application is started. You can use these interfaces to
perform any actions immediately after the application has started. This chapter talks
about them in detail.
• Application Runner
Application Runner is an interface used to execute the code after the Spring
Boot application started. The example given below shows how to implement
the Application Runner interface on the main class file.
package com.iimt.demo;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("Hello World from Application Runner");
}
}
Command Line Runner
• Command Line Runner is an interface. It is used to execute the code
after the Spring Boot application started. The example given below
shows how to implement the Command Line Runner interface on the
main class file.
package com.iimt.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... arg0) throws Exception {
System.out.println("Hello world from Command Line Runner");
}
}
Spring Boot - Logging
• Spring Boot uses Apache Commons logging for all internal logging. Spring Boot’s
default configurations provides a support for the use of Java Util Logging, Log4j2,
and Logback. Using these, we can configure the console logging as well as file
logging.
• If you are using Spring Boot Starters, Logback will provide a good support for
logging. Besides, Logback also provides a use of good support for Common Logging,
Util Logging, Log4J, and SLF4J.
Log Format
• The default Spring Boot Log format is shown in the screenshot given below.

which gives you the following information −


• Date and Time that gives the date and time of the log
• Log level shows INFO, ERROR or WARN
• Process ID
• The --- which is a separator
• Thread name is enclosed within the square brackets []
• Logger Name that shows the Source class name
• The Log message
Building RESTful Web Services
• Spring Boot provides a very good support to build RESTful Web
Services for enterprise applications.
• For building a RESTful Web Services, we need to add the Spring Boot
Starter Web dependency into the build configuration file.
If you are a Maven user, use the following code to add the below
dependency in your pom.xml file −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

If you are a Gradle user, use the following code to add the below
dependency in your build.gradle file −
compile('org.springframework.boot:spring-boot-starter-web')
Rest Controller
• The @RestController annotation is used to define the RESTful web
services. It serves JSON, XML and custom response. Its syntax is as
follows −

@RestController
public class ProductServiceController {
}

Request Mapping
• The @RequestMapping annotation is used to define the Request URI
to access the REST Endpoints. We can define Request method to
consume and produce object. The default request method is GET.

@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() { }
Request Body
• The @RequestBody annotation is used to define the request body
content type.

public ResponseEntity<Object> createProduct(@RequestBody Product


product) {
}

Path Variable
• The @PathVariable annotation is used to define the custom or
dynamic request URI. The Path variable in request URI is defined as
curly braces {} as shown below −

public ResponseEntity<Object> updateProduct(@PathVariable("id")


String id) {
}
Request Parameter
• The @RequestParam annotation is used to read the request parameters
from the Request URL. By default, it is a required parameter. We can also set
default value for request parameters as shown here −

public ResponseEntity<Object> getProduct(


@RequestParam(value = "name", required = false, defaultValue =
"honey") String name) {
}

GET API
The default HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path
variables to define the custom or dynamic URL.
• The sample code to define the HTTP GET request method is shown below. In this example, we used HashMap to store the Product. Note that
we used a POJO class as the product to be stored.
• Here, the request URI is /products and it will return the list of products from HashMap repository. The controller class file is given below that
contains GET method REST Endpoint.
package com.iimt.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.iimt.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}}
POST API
• The HTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path
variables to define the custom or dynamic URL.
• The following example shows the sample code to define the HTTP POST request method. In this example, we used HashMap to store the
Product, where the product is a POJO class.
• Here, the request URI is /products, and it will return the String after storing the product into HashMap repository.

package com.iimt.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.iimt.demo.model.Product;

@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();

@RequestMapping(value = "/products", method = RequestMethod.POST)


public ResponseEntity<Object> createProduct(@RequestBody Product product) {
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
}
}

PUT API
The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We can send request parameters and
path variables to define the custom or dynamic URL.
• The example given below shows how to define the HTTP PUT request method. In this example, we used HashMap to update the existing
Product, where the product is a POJO class.
• Here the request URI is /products/{id} which will return the String after a the product into a HashMap repository. Note that we used the Path
variable {id} which defines the products ID that needs to be updated.
package com.iimt.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.iimt.demo.model.Product;

@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();

@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)


public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
}
}

DELETE API
The HTTP Delete request is used to delete the existing resource. This method does not contain any Request Body. We can send request
parameters and path variables to define the custom or dynamic URL.
• The example given below shows how to define the HTTP DELETE request method. In this example, we used HashMap to remove the existing
product, which is a POJO class.
• The request URI is /products/{id} and it will return the String after deleting the product from HashMap repository. We used the Path variable
{id} which defines the products ID that needs to be deleted.

package com.tutorialspoint.demo.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.demo.model.Product;

@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();

@RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)


public ResponseEntity<Object> delete(@PathVariable("id") String id) {
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
}
}

You might also like