OOP With Java Complete Notes
OOP With Java Complete Notes
Technology
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
• Console Applications
• Windows Applications
• Web Applications
• Enterprise Applications (large-scale,
multi-tiered, scalable, reliable, and secure
network applications)
• Mobile Applications
JAVA Editions
class classname
{
public static void main(String [] objname)
{
Variables declaration;
Executable statements;
}
}
class Simple
{
public static void main(String [] t)
{
System.out.print(“Welcome To JAVA”);
}
}
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
/**
* <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.
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
Method Description
Method Description
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. 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( )
{
_________________;
_________________;
}
t1.Getdata();
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 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
Exception
IOException
SQLException
ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
…
Types of Exceptions
Syntax :
Syntax :
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.
Syntax :
Method Description
Syntax :
start()
Sleep Interval Expires I/O Completion
Ready
Assigns the
yield()
processor
Running
sleep()
class Customer{
int amount=10000;
System.out.println("going to withdraw...");
if(this.amount<amount){
try{wait();}catch(Exception e){}
this.amount-=amount;
System.out.println("withdraw completed...");
System.out.println("going to deposit...");
this.amount+=amount;
notify(); } }
class Test{
new Thread(){
}.start();
new Thread(){
}.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}
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 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.
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));
}
}
@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;
@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
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:
When Diamond operator was introduced in Java 7, we can create the object
without mentioning generic type on right side of expression like:
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
• Definition of Iterable
public interface Iterable<T>
{
Iterator<T> iterator();
Spliterator<T> spliterator();
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 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);
{
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.*;
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);
// Printing elements
System.out.println(v);
[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.
System.out.println("Iterating Hashmap...");
for(Map.Entry m : m1.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output :
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[]){
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 :
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 :
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 :
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[]){
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[]){
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
Method Description
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, 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 :
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]");
}
}
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;
}
}
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
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
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">
</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;
Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}
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;
</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;
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 :
<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.
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.
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 −
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<>();
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<>();
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<>();