Module 1
COLLECTION AND GENERICS
Unit Structure
1.0 Objectives
1.1 Introduction to Generics
1.1.1 Advantages of Generics
1.1.2 Generic Classes
1.1.3 Generic Methods
1.1.4 Bounded Type Parameters
1.2 Wildcards
1.2.1 Types of Wildcards
1.3 Introduction to Java Collections
1.3.1 Java Collection Framework
1.3.2 Java Collection Hierarchy
1.3.3 Advantages of Collection
1.3.4 Framework Basic and Bulk Operations on Java Collection
1.4 List
1.4.1 Methods of List Interface
1.4.2 How to create List - ArrayList and LinkedList
1.4.3 Iterating through the List
1.5 Set
1.5.1 Methods of Set Interface
1.5.2 HashSet Class
1.5.3 TreeSet Cl
1.6 Map
1.6.1 Methods of Map Interface
1.6.2 HashMap Class
1.6.2 LinkedHashMap Class
1.6.3 TreeMap Class
1.7 Let Us Sum Up
18 List of References
1.9 Chapter End E3
ercises:[ADVANCE JAVA
1.0 Objectives
After going through this chapter, you will be able to:
. Understand the Collections API
* Leam what is generics and how to write Generic Classes and Methods
* Perform basic operations on Collection
* Learn what are wildeard characters and types of wildcards
* Understand List, Set and Maps
1.1 Introduction to Generics
The Java Generics was added to JDK 1.5 which allowed programming
generically. It allows creating classes and methods that work in the same way on
different types of objects while providing type-safety right at the compile-time It
makes the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-generic.
Now generics force the java programmer to store a specific type of objects.
1.1.1 ADVANTAGE OF GENERICS
There are mainly 3 advantages of generics, They are as follows:
1) Type-safety
We can hold only a single type of objects in generics. It doesn’t allow to
store other objects. Without Generies, we can store any type of objects.
cample:
List list = new ArrayList();
listadd(10); _//Storing an int value in list
listadd("10");_ //Storing a String value in list
With Generics, it is required to specify the type of object we need to store.
List
list = new ArrayList();
list.add(10);
list.add("10")y/ compile-time error
2) Type casting is not required
There is no need to typecast the object. Before Generics, we need to type cast.
Example:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0); //typecasting
After Generics, we don't need to typecast the object.Chapter 1: Collection and Generics
Exampl
List list = new ArrayList();
list.add("hello");
String s = list-get(0);
3) Compile-Time Checking: Type checking is done at compile time so errors
will not occur at runtime.
list.add("hello");
list.add(32);//Compile Time Error
1.1.2 GENERIC CLASSES
Generics
s not only limited to collection. Iti
classes. A generic class declaration looks like a non-generic class declaration,
except that the class name is followed by a type parameter section,
Iso possible to use Generics with
The type parameter section of a generis
These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.
ss can have one or more type parameters
separated by comma:
Example: Program that demonstrates Generic Classes
public class Shape {
private T t;
public void add(T 1) {
this.t=t;
}
public T get() {
retum t;
}
publie static void main(String[] args) {
Shape intShape = new Shape();
Shape strShape = new Box();
intShape.add(new Integer(25));
strShape.add(new String("Generie Classes"));
System out printf("Integer Value :%din\n", intShape.get());
System out print{("String Value :%s\n", strShape.get());[ADVANCE JAVA
Output
Integer Value :25
String Value : Generic Classes
In this program, Box is coded as a Generic Class. Technically, Box is a parametric
class and T is the type parameter. T serves as a placeholder for holding any type of
Object. We can use the above class by substituting any kind of object for the
placeholder T.
1.1.3 GENERIC METHODS
A generic method declaration can have arguments of different types. Based on the
types of the arguments passed to the generic method, the compiler handles each
method call appropriately. Unlike a Generic Class, a generic method containing
different parameters affects only that method, alone. Hence, a class which is not
generic can contain generic and non-generic methods.
Rules for defining Generic Methods
+ All generic method declarations have a type parameter section delimited by
angle brackets (< and >) that precedes the method's return type
+ Each type parameter section contains one or more type parameters
separated by commas. A type parameter is an identifier that specifies a
generic type name.
+ The type parameters can be used to declare the return type and act as
placeholders for the types of the arguments passed to the generic method,
which are known as actual type arguments,
+ A generic method's body is declared like that of any other method,
+ Note that type parameters can represent only reference types, not primitive
types (like int, double and char),
Example I: Program that prints the type of data passed using a single Generic
method
public class GenericMethodsEx!
{ff generic method print
public static void print(T t)
{ System.out printin(t-getClass().getName());
}
public static void main(String args[]) {
GenericMethodsEx 1 print(“Hello World”);
GenericMethodsEx1 print(100);
}
}Chapter 1: Collection and Generics
Output;
java.lang.String
java.lang.Integer
In this program, the static method print has a retum type void and it takes a single
parameter called T. T stands for parametric type which can be substituted with any
of the Java types by a client application.
Example 2: Program that prints an array of different type using a single
Generic method
public class GenerieMethodEx2 {
i! generic method printArray
public static void printArray( E{] i)
{
// Display array elements
for(T element : i) {
System.out.printf("%s ", element);
}
System.out printin();
t
public static void main(String args{]) {
1/ Create arrays of Integer, Double and Character
Integer{] intArray ~ { 1, 2, 3,4, 5};
Double{] doubleAmay = { 1.1, 2.2, 3.3, 4.4};
Character[] charArray = { 'H’,'E', 'L','L', 'O! };
System out printin("Array integerArray contains:
printArray(intArray); // pass an Integer array
System.out.printin("nArray doubleArray contains:");
printArray(doubleArray); // pass a Double array
System out.printin("\nArray characterArray contains:");
printArray(charArray); // pass a Character array[ADVANCE JAVA
Output
Array integerArray contains:
12345
Array doubleArray contains:
1.12.23,34.4
‘Array characterArray contains:
HELLO
In this program, the static method printArray has a return type void and it takes a
single parameter called T. T stands for parametric type which can be substituted
with any of the Java types by a client application, The main method passes arrays
with different types and the single generic method is used to print all of the array
elements.
1.1.4 BOUNDED TYPE PARAMETERS,
Sometimes it is required to restrict the kinds of types that are allowed to be passed
to a type parameter. Example, a method that operates on numbers might only want
bounded type
to accept instances of Number or its subclasses. In such case
parameters can be used.
To declare a bounded type parameter, list the type parameter's name, followed by
the extends keyword, followed by its upper bound like below:
class Example
xxample: Program that calculates the average of numbers either integer or
double
package pl;
public class Test {
TU] numaArr;
Test(T[] numArr) {
this.numArr = numArr;
}
public double getAvg() {
double sum = 0.0;
for (int i= 0; i el = new Test(il);
Test e2 = new Test(d);
double ai = el.getAvg0;
Double ad = e2.getAvg();
System.out printin("Average of Integers =" + ai);
System.out printIn("Average of Double =" + ad);
Output
Average of Integers = 14.0
Average of Double =2.5
1.2 WILDCARD CHARACTER
The question mark (2) is known as the wildcard in generic programming . It
represents an unknown type.
The wildcard can be used in a variety of situations such as the type of a
parameter, field, or local variable; sometimes as a return type.
Unlike arrays, different instantiations of a generic type are not compatible
with each other, not even explicitly. This incompatibility may be softened by
the wildcard if? is used as an actual type parameter.
1.2.1 TYPES OF WILDCARDS
There are three types of wildcards: They are:
1, UPPER BOUNDED WILDCARDS
>
v
‘These wildcards can be used when you want to relax the restri
variable,
For example, say you want to write a method that works on List < Integer >,
List and List , you can do this using an upper bounded
wildcard.
To declare an upper-bounded wildcard, use the wildcard character (‘?”),
followed by the extends keyword, followed by its upper bound
Ex: public static void add(List extends Number> list)[ADVANCE JAVA
Example: Program that demonstrates Upper Bounded Wildcards
import java.util. Arrays;
import java.util.List;
class UpperBoundedWildeardDemo
t
public static void main(String[] args)
{
//Upper Bounded Integer List
List listl= Arrays.asList(4,5,6,7);
printing the sum of elements in list
System.out.printin("Total sum is:"-+sum(list1));
{/Upper Bounded Double list
List list2—Arrays.asList(4.1,5.1,6.1);
printing the sum of elements in list2
System.out.print("Total sum is:"+sum(ist2));
+
private static double sum(List extends Number> list)
{
double sum=0.0;
for (Number i: list)
t
sum#=i.doubleValue();
}
return sum;
}
}
Output
‘Total sum is:22.0
Total sum is:15.299999999999999
Here, the sum method is used to calculate the sum of both Integer list and Double
list elements as it accepts list as a parameter whse upper bound is Number.Chapter 1: Collection and Generics
2. LOWER BO!
NDED WILDCARDS
* Ifwe use the lower-bounded wildcards you can restrict the type of the “?” to
a particular type or a super type of it
* It is expressed using the wildcard character (‘2’), followed by the super
keyword, followed by its lower bound:
Syntax: Collectiontype super A>
Example: Program that demonstrates Lower Bounded Wildcars
import java.util. Arrays;
import java.util.List;
class LowerBoundedWildcardDemo {
public static void main(String[] args) {
//Lower Bounded Integer List
List list] = Arrays.asList(1,2,3,4);
/Minteger list object is being passed
print(list1);
{/Lower Bounded Number list
List list2 = Arrays.asList(1,2,3,4);
iMnteger list object is being passed
print(list2);
public static void print(List super Integer> list) {
System.out printIn(list);
Output
U1, 2,3, 4]
U1, 2,3, 4]
Here, the print method is used to calculate the print both Integer list and Number
list elements as it accepts list as a parameter whse lower bound is Integer.
3. UNBOUNDED WILDCARDS
The unbounded wildcard type is specified using the wildcard character (2), for
example, List>. This is called a list of unknown type.[ADVANCE JAVA
Consider the following method, printList
public static void printList(List,
List, List, and so on, because they are not subtypes of
List.
To write a generic printList method, use List>:
Example: Program that demonstrates UnBounded Wildcards
import java.util. Arrays;
import java.util.List;
public class UnboundedWildcardDemo {
public static void printList(List> list) {
for (Object elem : list) {
‘System.out printin(elem +" ");
}
System. out printin();
3
public static void main(String argsf]) {
List li Arrays.asList(1, 2, 3);
List Is = Arrays.asList("one", "two", "three");
printList(li);
printList(ls);
Output
ree
one
two
three
Here, li and Is are Integer and String lists created from Arrays and both li
printed using the generic method printList.
areChapter 1: Collection and Generics
1.3 Introduction To Java Collections
Before Collections, the standard way used for grouping data was using the array,
Veetor and HashTable, But all of these have different methods and syntax for
accessing data and performing operations on it. For example, Arrays uses the
square brackets symbol [] to access individual data members whereas Vector uses
the method elementAt(). These differences led to a lot of discrepancies. Thus, the
“Collection Framework” was introduced in JDK 1.2 to bring a unified mechanism
to store and manipulate a group of objects,
1.3.1 JAVA COLLECTION FRAMEWORK
Any group of objects which are represented as a single unit is known as the
collection of the objects. In Java Collections, individual objects are called as
elements.
The “Collection Framework” holds all the collection classes and interface in it,
These classes and interfaces define all operations that you can perform uniformly
on different types of data such as searching, sorting, insertion, manipulation, and
deletion,
‘The Java Collection framework has
1. Interfaces and its implementations, i.e., classes,
2, Algorithm
1.3.2 JAVA COLLECTION HIERARCHY
The java.util package contains all the classes and interfaces for the Collection
framework.
EEE)
The Collection interface is the root of the collection hierarchy and is implemented
by all the classes in the collection framework.
ul[ADVANCE JAVA
The Collections framework has a set of core interfaces. They are:
> List
> Set
> Map
> Queue
The Collection classes implement these interfaces and provide plenty of methods
for adding, removing and manipulating data.
1.3.3 ADVANTAGES OF COLLECTION FRAMEWORK
1. Consistent API: The API has a basic set of interfaces like Collection, Set,
List, or Map, all the classes (ArrayList , LinkedList, Vector, etc) that
implement these interfaces have some common set of methods.
2, Reduces programming effort: A programmer doesn’t have to worry about
the design of the Collection but rather he can focus on its best use in his
program, Therefore, the basic concept of Object-oriented programming (i.¢.)
abstraction has been successfully implemented.
3. Increases program speed and quality: Increases performance by providing
high-performance implementations of useful data structures and algorithms
4, Clean code - These APIs have been written with all good coding practices
and documented very well. They follow a certain standard across whole Java
collection framework. It makes the programmer code look good and clean.
1.3.4 BASIC AND BULK OPERATIONS ON JAVA COLLECTION
The Collection Interface provides methods that performs basic operations on data
such as:
‘Methods Description
boolean add(E element) Used to add an element in the collection
boolean remove(Object Used to delete an element from the collection
element)
int size Retums the total number of elements in the
collection
Tterator iterator() Returns an iterator over the elements in the
collection
boolean contains(Object Retums true if the collection contains the
element) specified element
boolean isEmpty) Retums true if the collection is emptyChapter 1: Collection and Generics
The Collection Interface also contains methods that performs operations on entire
collections which are also called as bulk operations.
Methods
Description
boolean containsAll(Collection> c)
Used to check if this collection
contains all the elements in the
invoked collection,
boolean addAll(Collection extends E>
)
Used to insert the specified
collection elements in the invoking
collection
boolean removeAll(Collection> ©)
Used to delet
the specified collection from the
invoking collection,
all the elements of
boolean retainAll(Collection<> o)
Used to delete all the elements of
invoking collection except the
specified collection.
void clear)
Removes all the elements from the
collection.
Herator interface
It provides the facility of iterating the elements in a collection.
Method
Description
public boolean hasNext()
It returns true if the iterator has more
elements otherwise it returns false.
public Object next()
It returns the element and moves the
cursor pointer to the next element.
public void remove()
It removes the last elements returned
by the iterator. It is less used.
LIST
List in Java provides the facility to maintain the ordered collection. It contains the
index-based methods to insert, update, delete and search the elements. It can have
the duplicate elements also. We can also st
tore the null elements in the list.
The List interface is found in the java.util package and inherits the Collection
interface. It is a factory of Listlterator interface. Through the ListIterator, we can
iterate the list in forward and backward directions.[ADVANCE JAVA
The List interface is declared as:
Public interface List extends Collection
1.4.1 METHODS OF LIST INTERFACE
Method Description
void add(int index, E | It is used to insert the specified element al the
element) specified position in a list
Tt is used to append the specified element at the end
r E
boolean add(E e) of alist.
Itis used to remove all of the elements from this,
void elear() lice
Itis used to compare the specified object with the
bool als(Object
oolean equals(Obieet ©) | sements of alist
int hashcode() It is used to return the hash code value for a list,
boolean isEmptyO) Itretums true if the list is empty, otherwise false.
It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list
does not contain this element,
int lastindexOM(Object
0)
1.4.2 HOW TO CREATE LIST?
Since List is an interface, a concrete implementation of the interface needs to be
instantiated, in order to use it.
The implementation classes of List interface are ArrayList, LinkedList, Stack and
Vector.
= //Creating a List of type String using java.util. ArrayList
List list-new ArrayList();
= Creating a List of type String using LinkedList
List list-new LinkedList();
= java.util. Vector
List listl=new Vector);
= java.util. Stack
List list] =new Stack();
The ArrayList and LinkedList are widely used in Java programming.
ArrayList
ArrayList is a variable length array of object references. It can dynamically increase
or decrease in size, It can be created with an initial size. When this size is
exceeded,the collection is automatically enlarged, When objects are removed, the
array may be shrunk,Chapter
Collection and Genetics
Example: Program that demonstrates List using ArrayLis
fimport java.util.
[public class ArrayListDemo {
publie static void main(String{] args) {
1 Creating a list
List I= new ArrayList0;
1! Adds 1 at 0 index
I.add(0, 1);
1 Adds 2 at 1 index
I add(1, 2);
System. out printin(11);
1/ Creating another list
List I2= new ArrayList();
I2.add(1);
I2.add(2);
I2.add(3);
1 Will add list 12 from 1 index
IL addAtl(1, 12);
System.out.printin(11);
1/ Removes element from index 1
11 xemove(!);
System.out printin(I1);
1/ Prints element at index 3
System.out.printin(I1.get(3));
1/ Replace Oth element with 5
I1.set(0, 5);
System.out.printin(11);
Output:
(1,2)
11,1,2,3,2]
(1,2, 3,2]
2
15, 2,3, 2][ADVANCE JAVA
LinkedList
LinkedList is a class which is implemented in the collection framework which
inherently implements the linked list data structure. It is a linear data structure
where the elements are not stored in contiguous locations and every element is a
separate object with a data part and address part. The elements are linked using
pointers and addresses. Each element is known as a node. Linked List permits
insertion and deletion of nodes at any point in the list in constant time, but do not
allow random access, It permits all elements including null,
[Example: Program that demonstrates List using LinkedList class
limport java.io.*;
jimport java.util.*;
class LinkedListDemo {
public static void main(Stringf] args)
t
1! Size of the LinkedList
intn=5;
1! Declaring the List with initial size n
List Il = new LinkedList();
1! Appending the new elements
Mal the end of the list
for (int i= 1; i <=n5 i#
Madd(i);
1 Printing elements
System.out printin(il);
1/ Remove element at index 3
Iremove(3);
1! Displaying the list after deletion
System.out.printin(ll);
1 Printing elements one by one
for (int i= 0; i < IL.size(); i++)
System.out print(ll.get(i) +"");Chapter 1: Collection and Generics
Output:
U1, 2,3, 4, 5]
1,2,3,5]
1235
1.4.3 ITERATING THROUGH THE LIST
There are multiple ways to iterate through the List. The most famous ways are by
using the basic for loop in combination with a get() method to get the element at a
specific index and the advanced for loop.
Exam
Program that iterates through an ArrayLis
import java.util.*;
public class ArrayListlteration {
public static void main(String argsf])
{
List al= new ArrayList();
aladd("Ann");
al.add("Bill");
aladd(“Cathy”);
1/ Using the Get method and the for loop
yt
System.out print(al.get(i) +");
for (int i = 0; i h = new HashSet();Chapter 1: Collection and Generics
// Adding elements into the HashSet
h.add("India");
h.add(""Australia");
h.add("South Africa");
// Adding the duplicate element
h.add("India");
/ Displaying the HashSet
System.out println(h);
1/ Removing items from HashSet
h.remove("Australia");
System.out printin("Set after removing "+ "Australia:" + h);
1! Tterating over hash set items
System.out printhn("Iterating over set:");
Iterator i = h.iterator();
while (i.hasNext())
System.out printIn(i.next());
}
Qutput:
[South Africa, Australia, India]
Set after removing Australia:[South Africa, India]
Iterating over set:
South Africa
India
1.5.3. TREESET CLASS
TreeSet class which is implemented in the collections framework and
implementation of the SortedSet Interface and SortedSet extends Set Interface. It
behaves like a simple set with the exception that it stores elements in a sorted
format, TreeSet uses a tree data structure for storage. Objects are stored in sorted,
ascending order.[ADVANCE JAVA
Example: Program that demonstrates TreeSet implementation
import java.util.
class TreeSetDemo {
publie static void main(Stringf] args)
{
Set ts = new TreeSet(;
1/ Adding elements into the TreeSet
ts.add("India");
ts.add(""Australia");
ts.add("South Africa”
11 Adding the duplicate element
ts.add("India");
/ Displaying the TreeSet
System.out.printin(ts);
1/ Removing items from TreeSet
ts.remove("Australia");
System.out.printin("Set after removing "+ "Australia:” + ts);
!Iterating over Tree set items
System.out printin("Iterating over set:");
Iterator i = ts.iterator(
while (i,hasNext())
‘System.out.printin(i.next);
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Kterating over set
India
South Africa
20Chapter 1: Collection and Generics
1.6 Maps
The Map interface present in java.util package represents a mapping between a key
and a value, A map contains unique keys and each key can map to at most one
value. Some implementations allow null key and null value like the HashMap and
LinkedHashMap, but some do not like the TreeMap. The order of a map depends
on the specific implementations. For example, TreeMap and LinkedHashMap have
predictable order, while HashMap does not.
The Map interface is not a subtype of the Collection interface. Therefore, it behaves
abit differently from the rest of the collection types.
The classes which implement the Map interface are HashMap, LinkedHashMap
and TreeMap.
1.6.1 METHODS OF MAP INTERFACE
Method Description
This method is used to clear and remove all of the
clear() elements or mappings from a specified Map
collection.
This method is used to check for equality between
two maps. It verifies whether the elements of one
map passed as a parameter is equal to the elements of
this map or not,
equals(Object)
This method is used to retrieve or fetch the value
mapped by a particular key mentioned in the
parameter. It returns NULL when the map contains
no such mapping for the key.
get(Object)
This method is used to generate a hashCode for the
hashCode) given map containing key and values.
This method is used to check if'a map is having any
isEmpty) entry for key and value pairs. If'no mapping exists,
then this returns true.
This method is used to clear and remove all of the
clear() elements or mappings from a specified Map
collection.
1.6.2, HASHMAP
HashMap class implements the Map interface which allows us fo 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. It is easy to perform operations
au[ADVANCE JAVA
using the key index like updation, deletion, ete. HashMap class is found in the
java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It
allows us to store the null elements as well, but there should be only one null key.
Since Java 5, it is denoted as HashMap, where K stands for key and V for
value.
Example: _Program that demonstrates HashMap implementation
import java.util*;
public class HashMapDemo {
public static void main(String[] args) {
Map map = new HashMap<>();
‘map.put("Angel", 10);
map put("Liza”, 30);
map.put(""Steve", 20);
for (Map.Entry e : map.entrySet()) {
System.out printin(e.getKey() +" + e.getValue());
Output:
vaibhav 20
vishal 10
chin 30
1.6.3 LINKEDHASHMAP
LinkedHashMap is just like HashMap with an additional feature of maintaining the
order of elements inserted into it, HashMap provided the advantage of quick
insertion, search and deletion but it never maintained the track and order of
insertion which the LinkedHashMap provides where the elements can be accessed
in their insertion order.
2Chapter 1: Collection and Generics
jimport java.util";
public class LinkedHashMapDemo {
public static void main(Stringf] args)
{
Map map= new LinkedHashMap<>();
map.put("Angel", 10);
map. put("Liza”, 30);
map put("Steve", 20);
for (Map.Entry e : map.entrySet())
tem.out.printin(e.getKey() + " "+ e.getValue());
Output
Angel 10
Liza 30
Steve 20
1.6.4 TREEMAP
The TreeMap in Java is used to implement Map interface and NavigableMap along
with the Abstract Class. It provides an efficient means of storing key-value pairs in
sorted order. TreeMap contains only unique elements and cannot have a null key
but can have multiple null values.
TreeMap is non synchronized and maintains ascending order.
fimport java.util";
class TreeMapDemo {
public static void main(String argsf]) {
TreeMap map ~ new TreeMap;
2B[ADVANCE JAVA
‘map put(100, "Angel");
‘map put(101, "Chris");
map put(103, "Bill");
‘map.put(102, "Steve");
for (Map.Entry m : map.entrySet()) {
System.out printin(m.getKey() +" " + m.getValue());
Output:
100 Angel
101 Chris
102 Steve
103 Bill
1.7 Let Us Sum Up
The “Collection Framework” holds all the collection classes and interface in
it and interfaces that define all operations that you can perform uniformly on
different types of data such as searching, sorting, insertion, manipulation, and
deletion.
The java.util package contains all the classes and interfaces for the Collection
framework.
Generics allows to program generically. It allows creating classes and
methods that work in the same way on different types of objects while
providing type-safety right at the compile-time,
Generics can also be used with classes.
A generic method declaration can have arguments of different types.
Bounded type parameters can be used to restrict the kinds of types that are
allowed to be passed to a type parameter.
The question mark (?)known as the wildcard represents an unknown type and
can be used in a variety of situations such as the type of a parameter, field, or
local variable. There are three types of wildcards-Upper Bounded, Lower
Bounded and UnBounded.
24Chapter 1: Collection and Generics
List contains the index-based methods to insert, update, delete, and search
the elements. It can have duplicate elements also.
* The Set follows the unordered way and can store only unique elements.
* Map represents a mapping between a key and a value. Each key is linked to
a specific value,
1.8 List of References
1. Java 8 Programming, BlackBook, DreamTech Pres:
2. Core Java 8 for Beginners, Sharanam Shah, Vaishali Shah, Third Edition,
sPD
Ref
ces
1. hitps://www.geeksforgeeks.org
2. hitps://www.javatpoint.com
3. https://Awww.tutorialspoint.com
1.9 Chapter End Exercises
QI. What are the advantages of collections over primitive datatypes?
Q2. What are generies?List down the advantages of using generics.
plain the concept of bounded parameters.
Q4, Differentiate between List,Set and Maps.
QS. What is a wildcard character? Explain the various types of wildcard characters.
Q6. Explain the difference between ArrayList and LinkedList
Q7. Explain the difference between HashMap, LinkedHashMap and TreeMap with
example programs,
seees
25Module 1
LAMBDA EXPRESSIONS
Unit Structure
2.0 Objectives
2.1 Introduction
2.1.1 What is Lambda Expression?
2.1.2 Why to use Lambda Expression?
2.1.3 Syntax of Lambda Expression
2.1.4 Where can Lambda Expressions be used?
2.2 Lambda Type Inference
2.3 Lambda Parameters
2.4 Lambda Function Body
2.5 Returning a Value from a Lambda Expression
2.6 Lambdas as Objects
2.7 Lambdas in Collections
2.8 Let us Sum Up
2.9 List of References
2.10 Chapter End Exercises
2.0 Objectives
After going through this chapter, you will be able to:
* Understand what are Lambda Expressions and how to write lambda
expressions
* State the advantages of using lambda expressions
* Explain the different ways parameters can be passed in a Lambda
Expressions
© Understand target type inferencing
Simplify programs and reduce code length using Lambda Expressions
2.1 Introduction
Lambda expressions is a new and significant feature of Java which was introduced
in Java SE 8 and became very popular as it simplifies code development. It provides
a very clear and concise way to represent single method interfaces using an
expression. It is very useful in collection library. It helps to iterate, filter and extract
data from collection, Lambda Expressions is Java’s first step towards functional
26(Chapter 2: Lambda Expressions
programming, Lambda expression is treated as a function, so compiler does not
create .class file
‘An interface having a single abstract method is called a Funetional Interface or
Single Abstract Method Interface. Lambda expression is used to provide the
implementation of such a functional interface, 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 which saves a lot of code. Pre-Java 8, an
approach for implementing functional interfaces were anonymous inner classes.
However, syntax of anonymous inner classes may seem unclear and cumbersome
at times,
To better understand lambda expressions, let us first look into an example for
implementing functional interfaces with anonymous inner classes.
In the following program, we have an interface Square with a single abstract
method area() in it, We have a class AnonymousClassEx which implements the
method in interface Square using anonymous inner class.
Program to demonstrate Functional Interface Using Anonymous
interface Square { Functional Interface
public void area();
}
public class AnonymousClassEx {
public static void main(String[] args) {
int side ~ 10;
* Without Lambda Expressions, Implementation of Square interfai
Anonymous Inner Class */
Square s = new Square() { _ //Anonymous Class
public void area()
t
System.out printin("Area of square =" + side * side);
using
3
‘
s.area();
Outpu
Area of square = 100
Here you can note that we are rewriting the method declaration code public void
area() written in the interface again in the anonymous inner class. This repetitive
code can be eliminated if we use Lambda Express
ions.
”[ADVANCE JAVA
2.1.1 WHAT IS LAMBDA EXPRESSION?
A lambda expression refers to a method that has no name and no access specifier
(private, public, or protected) and no return value declaration. This type of method
is also known as ‘Anonymous methods’, ‘Closures’ or simply ‘Lambdas*. It
provides a way to represent one method interface simply by using an expression
Like anonymous class, a lambda expression can be used for performing a task
without a name.
2.1.2 WHY TO USE LAMBDA EXPRESSIONS?
1, Lambda Expressions provides the ability to pass behaviours to methods
2, Itprovides simplified implementation of Functional Interfaces.
3. Clear and compact syntax
4, Reduces repetitive coding
5. Faster execution time
2.1.3 SYNTAX OF LAMBDA EXPRESSION
The basic structure of a lambda expression comprises:
(Parameters-list) -> (Expression body}
* Parameter list: It can be empty or non-empty as well. If non-empty, there is
no need to declare the type of the parameters. The compiler can inference the
same from the value of the parameter. Also, if there is only one parameter,
the parenthesis around the parameter list is optional.
© Arrow-token (->): It is used to link parameters-list and body of expression.
* Expression body: It contains body of lambda expression. If the body has
only one statement then curly braces are optional. You can also use a return
statement, but it should be enclosed in braces as it is not an expression.
Consider the following code snippet for understanding the concept of lambda
expression, in which a simple method is created for showing a message. Let’s first
declare a simple message as
public void display) {
System.out.printin(“Hello World”);
}
Now, we can convert the above method into a lambda expression by removing the
public access specifier, return type declaration, such as void, and the name of
method ‘display’
28(Chapter 2: Lambda Expressions
The lambda expression is shown as follows:
Ot
System.out println(“Hello World”);
}
Thus, we have simplified the code.
Now since we know how to write a Lambda Expression, let’s rewrite Example 2.1
using Lambda Expressions:
Example: Program to demonstrate Functional Interface Implementation Using
Lambda Expressions
interface Square { //Functional Interface
public void area);
}
public class LambdaExpressionEx {
public static void main(String[] args) {
int side=10;
/Implementation of Square Interface using Lambda Expression
Square s=() > {
System.out printin("Area of square= "+side*side);
b
s.area();
Area of square = 100
Here, you can observe that we have not written the method declaration public void
area() present in the interface while implementing it in the class using lambda
expression. Thus reducing repetitive code.
2.1.4 WHERE CAN LAMBDA EXPRESSIONS BE USED?
Lambda Expressions can be written in any context that has a target datatype. The
contexts that have target type are:
29[ADVANCE JAVA
* Variable declarations, assignments and array initializers
© Retum statements
* Method or constructor arguments
© Temnary Conditional Expressions (?:)
2.2 LAMBDA TYPE INFERENCE
Type Inference means that the data type of any expression (for e.g., a method return
type or parameter type) can be understood automatically by the compiler. Lambda
Expressions support Type Inference. Type inference allows us to not specify
datatypes for lambda expression parameters. Types in the parameter list can be
omitted since java already know the types of the expected parameters for the single
abstract method of functional interface. The compiler infers the type of a
parameter by looking elsewhere for the type - in this case the method definition.
Syntax:
(parameter_namel, parameter_name2 ...) -> { method body }
Example:
interface Operation{
int add(int a,int b);
}
public class Addition {
public static void main(String] args) {
Operation ad1=(a,b)->(a+b);
System.out println(ad]_add(10,20));
Here, the compiler can infer that a and b must be int because the lambda
expression is assigned to a Operation reference variable.
2.3 LAMBDA PARAMETERS
* A lambda expression can be written with zero to any number of parameters
* If there are no parameters to be passed, then empty parentheses can be given.
For Example:
(0 > { System.out.printin(“Zero Parameter Lambda Expression”); }
30(Chapter 2: Lambda Expressions
Example: Program demonstrating Lambda Expression with no parameter
//Functional Interface
interface MyFunctionalInterface {
1A method with no parameter
public void say();_}
public class ZeroParamLambda {
public static void main(String argsf]) {
I lambda expr
n
MyFunetionalinterface msg = () > {
System.out printin("Hello");
B
msg.say();
Quiput
Hello
© When there is a single parameter, if its type is inferred, it is not mandatory to
use parentheses.
For Example:
(str) > { System. out printin(“Single Parameter Lambda Expression” + str); }
Example: Program demonstrating Lambda Expression with Single Parameter
//Functional Interface
interface MyFunetionalInterface {
A method with single parameter
public void say(String str);
}
public class SingleParamLambda {
public static void main(String argsf]) {
lambda expression
MyFunctionalinterface msg = (str) > {
System.out. printin(str);
hb
msg.say("Hello World");[ADVANCE JAVA
Output
Hello World
© When there are multiple parameters, they are enclosed in parentheses and
separated by commas.
For Example:
(strl, str2) >f
System.out printin(“Multiple Parameter Lambda Expression ” +strl+ str2);
}
Example: Program demonstrating Lambda Expression with Multiple Parameters
7/Functional Interface
interface MyFunctionallnterface {
// method with single parameter
public void say(String strl, String str2);
}
public class SingleParamLambda {
public static void main(String argsf}) {
{lambda expression
MyFunctionalinterface msg = (str1, stt2) -> {
System.out printIn(strl +" "+ str2);
msg.say("Hello”, "Java"
}
I
Output
Hello Java
2.4 LAMBDA FUNCTION BODY
* The body of a lambda expression, and thus the body of the function / method
it represents, is specified to the right of the -> in the lambda declaration.
Omt
System.out.printin("Hello");
b
‘A lambda Expression body can have zero to any number of statements,
Statements should be enclosed in curly braces.
If there is only one statement, curly brace is not needed.
When there is more than one statement in body then these must be enclosed
in curly brackets and the return type of the anonymous function is the same
as the type of the value returned within the code block or void if nothing is
returned.(Chapter 2: Lambda Expressions
2.5 RETURNING A VALUE FROM A LAMBDA EXPRESSION
Java lambda expressions can return values , just like from a method. You just add
a return statement to the lambda function body, like this:
(param) -> {
System.out printin("param: "
+ param);
return "return value";
i
In case all your lambda expression is doing is to calculate a retum value and
retum it, you can specify the retum value in a shorter way. Instead of this:
(num, num2) —> {return numi > num2; }
You can write:
(num1, num?) —> numl > num2;
The compiler then figures out that the expression al > a2 is the return value of the
lambda expression
Note: A return statement is not an expression in a lambda expression, We must
enclose statements in curly braces ({}). However, we do not have to enclose a void
‘method invocation in braces.
Example: Program to demonstrate returning a value from lambda expression
interface Operation{
int add(int a,int b);
public class Addition {
public static void mai
‘String[] args) {
7/ Lambda expression without return keyword.
Operation ad1=(a,b)->(a+b);
System. out printIn(ad1 add(10,20));
/ Lambda expression with return keyword.
Operation ad2=(int a,int b)->{
return (a+b);
System.out printIn(ad2.add(30,40));
3
}
Qutput[ADVANCE JAVA
30
70
2.6 LAMBDAS AS OBJECTS
‘A Java lambda expression is essentially an object. You can assign a lambda
expression to a variable and pass it around, like you do with any other object. Here
is an example:
public interface MyComparator {
public boolean compare(int num1, int num2);
}
‘MyComparator ¢ = (numl, num2) -> numl > num2;
boolean result = c.compare(2, 5);
The first code block shows the interface which the lambda expression implements.
The second code block shows the definition of the lambda expression, how the
lambda expression is assigned to variable, and finally how the lambda expression
is invoked by invoking the interface method it implements,
2.6 LAMBDAS IN COLLECTIONS
Lambda Expressions can also be used with different collections such as ArrayList,
TreeSet, Treemap, ete... to sort elements in it
Example: Program to sort numbers in an ArrayList using Lambda Expression
import java.util.
public class Demo {
public static void main(Stringf] args)
{
ArrayList al = new ArrayList();
al.add(205);
al.add(102);
al.add(98);
al.add(275);
al.add(203);
System. out printin("Elements of the ArrayList before sorting : " + al);
/ using lambda expression in place of comparator object
Collections.sort(al, (01, 02) > (01 > 02)? -1 : (01 <02) 71: 0);
System.out printin("Elements of the ArrayList after sorting : "+ al);(Chapter 2: Lambda Expressions
Elements of the ArrayList before sorting : [205, 102, 98, 275, 203]
Elements of the ArrayList after sorting : [275, 205, 203, 102, 98]
2.7 MORI
‘AMPLE PROGRAMS USING LAMBDA EXPRESSIONS
1. Write a program using Lambda expression to calculate average of 3 numbers.
interface Operation {
double average(int a, int b, int ¢);
'
class Caleulate {
public static void main(String args[]) {
Operation opr = (a, b, €) > {
double sum =a +b +e;
retum (sum / 3);
b
System.out.printin(opr.average(10, 20, 5));
}
}
Output
11,666666666666666
2, Write a program fo store integer values 1 to 5 in an ArrayList and print all
numbers,even numbers and odd numbers using Lambda expression,
import java.util.ArrayList;
class Test
{
public static void main(String argsf])
{
1/ Creating an ArrayList with elements 1,2,3,4,5
ArrayList arrL = new ArrayList();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
arrL.add(5);
System.out.printin("Displaying all numbers");
1/ Using lambda expression to print all elements
atLforEach(n -> System.out.printIn(n));
System. out printIn( "Displaying even numbers");
// Using lambda expression to print even elements
arrL.forEach(n -> {
if (n%2 = 0) System.out printIn(n);
35[ADVANCE JAVA
3
%
System.out printin("Displaying odd numbers");
1/ Using lambda expression to print odd elements
antL.forEach(n > {
if (n%2 != 0) System.out printin(n);
}
%
}
}
Output
Displaying all numbers
vauUne
Displaying even numbers
2
4
Displaying odd numbers
1
3
5
3. Write a program using Lambda Expressions (o calculate the area of circle
with radius 5.
interface Area {
double calculate(int 1);
}
class AreaofCircle {
public static void main(String argsf])) {
Areaa=(r)-> {
double area = 3.142 * r*r;
return (area);
b
System.out printin(a.caleulate(5));
Area of cirele=78,55(Chapter 2: Lambda Expressions
4, Write a program to create a Student class to store student details such as
id,name and age.Sort student names on the basis of their first names and age
using Lambda Expression.
import java.util. ArrayList;
import java.util.List;
class Student {
String name;
int age;
int id;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getld() {
return id;
t
Student(String n, int a int i){
name =n;
age =a;
id=i;
t
@Override
public String toString) {
retum ("Student[ "+"Name:"*this.getName()+
" Age: "+ this.getAge() +
"Id: "+ this.getldQ+"]");
}
}
public class Testl {
public static void main(String[] args) {
List studentlist = new ArrayList();
studentlist.add(new Student("John", 22, 1001));
studentlist.add(new Student("Steve", 19, 1003));
studentlist.add(new Student("Kevin", 23, 1005));
studentlist.add(new Student("Ron", 20, 1010));
7[ADVANCE JAVA
studentlist.add(new Student("Chris", 18, 1111));
System. out printin("Before Sorting the student data:");
{iforEach for printing the list using lambda expression
studentlist.forach((s)->System.out printIn(s));
System.out.printin("\nA fier Sorting the student data by Age:");
//Lambda expression for sorting student data by age and printing it
studentlist sort((Student s1, Student s2)->s1.getAge()-s2.getA ge());
studentlist.forEach((s)->System.out.printIn(s));
System.out printin("\nA ter Sorting the student data by Name:");
J/Lambda expression for sorting the list by student name and printing it
studentlist sort((Student s1, Student s2)-
>s1.getName().compareTo(s2.getName()));
studentlist.forEach((s)->System.out printIn(s));
Output
Before Sorting the student data:
Student{ Name:John Age: 22 Id: 1001]
Student{ Name:Steve Age: 19 Id: 1003]
Student{ Name:Kevin Age: 23 Id: 1005]
Student{ Name:Ron Age: 20 Id: 1010]
Student{ Name:Chris Age: 18 Id: 1111]
After Sorting the student data by Age:
Student{ Name:Chris Age: 18 Id: 1111]
Student{ Name:Steve Age: 19 Id: 1003]
Student{ Name:Ron Age: 20 Id: 1010]
Student[ Name:John Age: 22 Id: 1001]
Student{ Name:Kevin Age: 23 Id: 1005]
After Sorting the student data by Name:
Student{ Name:Chris Age: 18 Id: 1111]
Student{ Name:John Age: 22 Id: 1001]
Student] Name:Kevin Age: 23 Id: 1005]
Student{ Name:Ron Age: 20 Id: 1010]
Student{ Name:Steve Age: 19 Id: 1003](Chapter 2: Lambda Expressions
2.8 Let us Sum up
1. Lambda Expressions is a function which can be created without belonging to
any clas
2. Ithas no name and no access specifier and no return value declaration.
It provides a very clear and concise way to represent functional interfaces.
Lambda Expression supports type inference.
aos
Lambda Expression Parameter list can have zero to any number of
parameters.
6, Lambda expression can be assigned to a variable and we can pass it around,
like we do with any other object.
2.9 List of References
1. Java 8 Programming, BlackBook, DreamTech Press, Edition 2015
2. Core Java 8 for Beginners, Sharanam Shah, Vaishali Shah, Third Edition,
SPD
Web References
1. httpy/tutorials.jenkov.com
2. https://www.geeksforgeeks.org
3. hittps://beginnersbook.com
2.10 Chapter End Exercises
QI. What is Functional Interface? How do you use Lambda Expression with
Functional Interfaces?
Q2. Which one of these is a valid Lambda Expression?
(int x, inty) -> x+y;
OR
(y) “> x+y
Q3. State the advantages of using Lambda Expressions
Q4. Write a program using Lambda Expression to calculate the area of a triangle.
Q5. Can Lambda Expressions be passed to different target types? Justify.
epeeModule?
3
JSP ARCHITECTURE, JSP BUILDING BLOCKS,
SCRIPTING TAGS, IMPLICIT OBJECT
INTRODUCTION TO JSP STANDARD TAG
LIBRARY (JSTL) AND JSTL TAGS
Unit Structure
3.0 Objectives
3.1 Introduction
3.2. Problems of Servlets
3.2.1 Static Content
3.2.2 For each client request you have to write service()
3.2.3 Any modification made in static content the Servlets need to be
recompiled and redeployed.
3.3. Servlet Life Cycle
3.3. a Diagram
3.4 ISP Architecture
3.4.a Diagram
3.5 ISP building blocks
3.5. a Scriptlet tags
3.5. b Declaration tags
3.5. ¢ Expression tags
3.6 Scripting Tags
3.6.a Comments
3.6.b Directives
3.6.c Declaration
3.6.d JSP scriptlet tags
3.6.e Expression
3.7 Implicit Objects
3.7.1 Out
3.7.2 request
3.7.3 response
3.7.4 config
3.7.5 application
3.7.6 session
3.7.7 page context
3.7.8 page
3.7.9 Exception
Introduction to JSP Standard Tag Library (JSTL) and JSTL Tags.
Summary
3.10. Reference for further reading
40Chapter 3: Tnteoduetion Jap Standard Tag Library ISTI) And JSTL Taps
3.0 Objectives
The primary objectives of learning this course will help the students to understand
the basic concepts of Servlets, deployment of JSP, development of dynamic web
pages, uses of various implicit objects and JSTL predefined library.
3.1 Introduction
ISP (Java Server Pages) it is an extension or we can say add- on of Servlets
technology. JSP provides more functionality as compared to Servlets. It is
basically used to develop web applications. It is nothing but similar to Servlets
which works on processing the request and generating the response objects, it is
vets we accept the request from
the same applies to JSP applications also. In $
the client, we process the request and then the Servlets generate the response. The
same way we can implement the process of accepting the request and generating
the response using JSP in much more simpler way without overriding much more
methods as of Servlets. JSP comprises of HTML and JSP tags that is why it said
that JSP pages are easier to maintain than Servlets because it gives you a separate
spi
for designing and development of web applications.
Before starting with JSP we should have a rough idea about the Servlets and how
it works and the reason behind the use of JSP over Servlets technology. It means
that we can say how JSP overcomes the drawbacks of Servlets. Servlets are
actually the base of web applications and it has its own life cycle which gets
executed each time the request is made from the client side. Servlets are some
time also known as server-side coding that is (Business logic).
Diagram a) How Servlets works using GetRequest() method
Servlet
CENT
<—_——t
GetResponse Response
.
4[ADVANCE JAVA
b) How Servlets works using PostRequest()
Servlet
| PosRemuest 5! se Request}
cunt senven Senieey >)
|¢ PostResponss | [Response a
3.2
Problems of Servlets:
»
2)
3)
Not
will
Static Content: - using Servlets we can generate static content, but it was
difficult to generate dynamic content using Servlets. So in such cases
designing in Servlets was a difficult task.
Solution using JSP: - so using JSP we can create dynamic content(dynamic web
pages) without wasting much more time on writing the code using HTML tags
embedding the java code in it.
For each client request you have to write service() method :~ In Servlets
for every new request you have to write the service() method which was
causing more processing time at the server end. In short to handle each
request in Servlets, we need to have service() for each upcoming request
from the client, So this creates a burden on the server-side to handle too
much of request and its service() method for each request.
Solution using JSP: - So the solution for it is there should no pressure of writing
the code of service() method for each request made by the client. The request
can be processed without taking much more time for processing the request. It
means that the request should get processed directly without its service() method
using JSP,
Any modification made in static content the Servlets need to be
recompiled and redeployet
changes in the static content that is (html code) in the presentation logic
then the Servlets need to be recompiled and redeployed which is again time
consuming part at the server-end.
‘o whenever we make any modification or
Solution using JSP: - Using JSP any changes or modification made in the
presentation logic (front-end) that is your static content so it does not required to
change its dynamic content that is your java code. It means that the java code
needs not to be recompiled and redeployed. So this helps to lower the burden of
processing the changes made at the server-side.
Before starting with JSP just go through the Servlets life cycles which
help you further to understand JSP in an easy way.
2Chapter 3: Tnteoduetion to Jap Standard Tag Library IST) And JSTL Ts
3.3. Servlets Life Cycle::
When we talk about the Servlets creation and its destruction there are some stages
that the Servlets undergoes during its life cycle. The various stages are:
i) Servlets class is loaded
ii) Servlets instance (object) is created
iii) inti) method is called
iv) _ service() method is called
v) destroy() method is called
Basically Servlets is a server-side program which is actually resides at the server-
end and whenever any request comes from the client to the server, the Servlets
gets executed to generate the appropriate response for the request.
Suppose a very first time the request comes from the client its first go to the:-
a) Web Container: - it is responsible for maintaining the Servlets life eycle
instance (object creation). So the web container is responsible for creating
the object of an Servlets as the request comes from the client, it means that
the Servlets class is loaded and the Servlets object is created (instantiated),
b) The second steps is to initializes the object of the Servlets, the Servlets will
invoking the its init() method which is responsible for the initialization of
Servlets.
©) After the init() method is called, at this stage the request came from the
client has not yet processed. To processed the request of the client, the
Servlets will call the service() method which is the most important method
of Servlets because its contains the business logic of the Servlets.
Note: In the entire life
le of Servlets the object is created only once
and its init() method is also called once.
4) After calling the service() method it will starts processing the request of the
client and the execution of business logic of service() method gets invoked,
Note: - For every new request the service () method is called each time by
the Servlets.
©) After processing the request and the execution of service() method , the web
container will starts destroying or you can say starts releasing the
resources used by the Servlets for processing the request and invoking the
serviee() method,
f) The last stage is to call or invoke the destroy() method of the Servlets and
its object.
43[ADVANCE JAVA
Diagram 3.3 (a) Life Cycle of Servlets
Client
h
Request / |, Response
Go 4
sence)
Calls destroy) to
Callsint) for
cae destroy the
initialization Service) is calledto Servlets and its
purpose ‘process the request object.
and invoking the
‘business logic.
3.4. JSP Architecture
ISP: - it is known for server-side programming that gives features like creating
dynamic web pages, platform independent method which helps in building web-
based applications. JSP have gain access to the family of Java API, including
IDBC APT which allows to access enterprise databases.
JAVA + HTML = JSP
Before starting JSP you should know about the use of HTML tags. It is a
Hypertext Markup Language which helps the programmer to describe or you can.
say design the structure of web pages. So java is embedded in html tags to create
dynamic web pages called as JSP.
ISP: - itis a technology that is supported to develop dynamic web pages using
Java code, Html tags and some scripting tags. The JSP pages follow these phases:
1) Translation of ISP page.
2) Compilation of JSP page
3) Classloading
4) Instantiation
5) Initialization
6) Request Processing( web container invokes jspService() method)
7) Destroy (web container invokes jspDestroy() method)
44Chapter 3: Tnteoduetion to Jap Standard Tag Library IST) And JSTL Ts
Note: The life cycle methods of JSP are: jspInit(, jspService(, jspDestroy
Step 1: With the help of JSP translator the JSP page is first translated into
Servlets.
Step 2: The JSP translator is a part of web server which handles the translation of
ISP page into Servlets.
Step 3: After that the Servlet page is compiled by the compiler and .class file is
created which is binary file.
Step 4: All processes that take place in Servlets are performed same in JSL later
that is initialization and sending response to the browser and then at the end
invoking destroy () method.
Diagram 3.4.a Life cycle of JSP Page:
Co 13 “3
SE &
a C ON
compile >
Clase hte
3.5 JSP building blocks
There are three building blocks of JSP code:
a) Scriptlet tag
b) Expression tag
©) Declaration tag
Java provide various scripting elements that helps the
programmer to insert java code from your JSP code into the Servlets. The
scriptlet elements have different components which help to write the code in jsp.
Scripting elements in JSP must be written within the <% %> tags. The JSP engine
45[ADVANCE JAVA
will process any code written within the pair of the <% %> tags, and any other
text within the Isp page will be treated as a html code. In short the sciptlet tag is
used to execute the java code in JSP.
Syntax: -<% Java code %>
Example:
<% out-print(“Welcome to JSP”)
y
3.5. b, Expressions Tag: - Expressions elements are comprises of scripting
Ianguage expressions, which gets executed and converted to String by the JSP
engine and i
is meant as a response that is output stream. So there is no need for
writing out.print() method.
Syntax: <%=statement %>
Example:
<%=" ISP based String” %.>
3.5. e. Declaration Tag:- It is used to define or you can say declare methods and
variables in JSP. The code written inside the jsp declaration tag is placed outside
the service() method.
Syntax: <%! Declaration %>
3.6 Scripting Tags
There are five different Scriptlet elements in JSP are:-
1) Comments
2) Directives
3) Declaration
4) ISP seriptlet Tag
5) Expressions
46Chapter 3: Tnteoduetion to Jap Standard Tag Library IST) And JSTL Ts
3.6.1 Comments
Comments are used to write some text or statements that are ignored by the JSP
compiler. It is very useful when someone wants to remember some logic or
information in future.
Syntax: <%- A JSP COMMENT--"%>
3.6.2 Directives
Itiis used to give some specific instructions to web container when the jsp page is
translated. It has three subcategories:
«© Page:<%@ page...>
© Include:<%@ include...%>
© Taglib:<%@ taglib....%>
3.6.3 Declaration
It is used to declare methods and variables used in java code within a jsp file. In
isp it is the rule to declare any variable before it is used.
Syntax: <%! Declaration;[declaration;}+...%>
Example: <%! int a=62; %>
3.6.4 JSP scriptlet Tag: please refer to( 3.5. a ) Scriptlet Tag
3.6.5 Expressions
Its contains the seripting language expressions which is gets evaluated and
converted to String by the JSP engine and it is meant to the output stream of the
response, So there is no need to write the out.print() method.
Example:
<%=“ a JSB String” %>
3.7 implicit objects
There are 9 implicit objects in JSP. These objects are created by the web
container and it is available to all the JSP pages.ADVANCE JAVA
Object ‘ype
Out Javax.servlet.jsp.JspWriter
Request Javax.servlet http. HttpservletRequest
Response Javax servlet http HttpservletResponse
Config Javax.serviet ServletConfig
‘Application Javax,servlet.ServletContext
Session TJavax.serviet http HupSession
pageContext Javax servlet jsp.PageContext
Page Java lang.Objects
Exception Java lang. Throwable
3:7-Tout:- The out implicit object is an instance of a javax servlet jsp. JspWriter
object. It is used to send the content in a response.
Example: _ out.printin(“Hello Java”);
3.7.2 Request: - The request object is an instance of a
javax servlet http.HtpServletRequest object. Each time a client requests a page
the JSP engine creates a new object to represent that request. It is used to request
information such as parameters, header information, server names, cookies, and
HTTP methods.
Example: String name=request.getParameter("rname”};
Some of the methods of request implicit objects are:
a) getAttributesNames()
b) _getCookies0)
©) getParameterNames0)
@ _getHeaderNames()
®) _getSesssion
1) _getSession(Boolean create)
g) _ getLocaleQ)
bh) getAttribute(String name)
48Chapter 3: Tnteoduetion to Jap Standard Tag Library IST) And JSTL Ts
3.7.3 Response: - The response object is an instance of a
javax.servlet http. HitpServletResponse object. Just as the server creates the
request object, it also creates an object to represent the response to the client,
Example: response.sendRedirect{http://www google.com);
3.7.4 Config: - In JSP, config is an implicit object of type ServletConfig. This
object can be used to get initialization parameter for a particular JSP page. The
config object is created by the web container for each jsp page.
Example: String x=config getParamter(“rname”);
3.7.5 Application: - In JSP, application is an implicit object of type
ServletContext. The instance of ServletContext is created only once by the web
container when application or project is deployed on the server.
Example: String x=application getinitParameter(“mame”);
3.7.6 Session: - In JSP, session is an implicit object of type HttpSession. In java
developer can use this object to set, get, and remove attribute or to get session,
information.
Example: session setAttribute(“user”, x);
3.7.7 pageContext := In JSP, pageContext is an implicit object of type
PageConteat class. The pageContext object can be used to set, get and remove
attribute from one of the following scopes:
i) Page
ii) request
iii) session
iv) application
3.7.8 Page: - This object acts as an actual reference to the instance of the page.
This object can be used to represent the entire jsp page.
Example: pageContext.removeAttribute("attrName”, PAGE_SCOPE);
3.7.9 Exception: - In JSP, exception is an implicit object of type
java lang. Throwable class. This object can be used to print the exception but it
should be used only in error pages.
49[ADVANCE JAVA
3.8 Introduction to JSP Standard Tag Library (JSTL) and JSTL.
Tags
ISTL - it is a collection of predefined tags to simply the jsp development. To
develop any jsp application we write the code in java so for writing this java code
we need some tags such as scriptlet tags. So writing the logical code in java, this
leads the increase in the length of the code which results in more processing time
Advantages of JST!
1) _ Fast Development: - provides many tags that simply the JSP. To write the
logical code in jsp you nced to use the scriptlet tags. To avoid using this
logical code, JSTL provides some pre-defined logical tags.
2) Code Reusability:
We can use the JSTL tags on various pages.
3) Noneed to use scriptlet tags: - It avoids the use of scriptlet tags.
JSTL Tags:
Itis a predefined library which provides custom tags.
1) Core tags: - it helps in variables support, URL management, flow control,
ete.
2) Funetions tags: - it provides support for String manipulation and getting
the String length,
3) Formatting tags: - it provides support for messaging, number, date
formatting ete.
4) XML tags: - itis used for manipulating and for e1
ting XML documents.
5) SQL tags: - it provides SQL. support such as database connectivity.
3.7 Summary
This course will helps to build skills gained by the students in Java fundamentals
and advanced java programming skills.
3.8 Reference for further reading.
javadocs.in
javapoint.com
W3schools.in
3.9 Bilbliograpgy
https://www.javapoint.com
https://www.w3schools.in
soCChapte 3 Intoduetion to Jsp Standard Tag Library IST) And JSTL Tags
MCQ FOR PRACTICE
Which page directive should be used in JSP to generate a PDF page?
content Type
typePDF
a
b. — generatePdf
°
d. contentPDF
Application is instance of which class?
javax.servlet. Application
javax.servlet.Context
javax servlet ServletContext
_jspService() method of HutpJspPage class should not be overridden.
a
b. _javax.servlet.HtpContext
.
d
a, True
b. False
Which of the following is not a directive in JSP?
a, Include
b, Page
©. Export
d. useBean
In JSP config instance is of which class?
a, javax.servlet.ServletContext
b. _ javax.servlet ServletConfig
¢. —_javax.servlet.Context
=
javax.servlet. Application
slModule?
4
INTRODUCTION TO BEAN, STANDARD
ACTIONS, SESSION TRACKING TYPES AND
METHODS. CUSTOM TAGS
Unit Structure
4.0
4.1
42
43
44
441
442
443
444
45
47
Objectives
Introduction
Introduction to Bean
Standard actions
43.1 jspruseBean
4.3.2 jsp:include
4.3.3 jsp:setProperty
4.3.4 jsp:forward
4.3.5 jsp:plugin
43.6 jsp:attribute
4.3.7 jsp:body
43.8 jsp:text
4.3.9 jsp:param
4.3.10jsp:attribute
4.3.11 jsp:output
jon tracking types and methods
Cookies
Hidden Fields
URL Rewriting
Session Object
Custom tags
Reference for further reading
4.0 Objectives
EJP stands for Enterprise Java Beans. It is a server-side component. It means that
EJB is basically used at server-side coding. So if we have client-side and server-
side, EJB is used for server-side and not for client-side.
52Chapter 4 Tneoduetion To Bea, Standard Actions, Session Tracking Types and Methods. Custom Tags
4.1 Introduction
EJB is an essential part of a J2EE platform.J2EE application container contains
the components that can be used by client for executing business logic. These
components are called business logic and business data. EJB mainly comprises of
business logic and business data, The EJB component always lies in some
container which is called as EJB container. The EJB component is an EJB class
which is written by the developer that implement business logic.
4.2 Introduction to Beans
JavaBeans are nothing it’s a class that encapsulates many objects into a single
object that is nothing but a bean, Java beans should follow some protocol such as:
1) They are serializable
2) Have a zero- argument constructor.
3) Allows access to properties using as getter and setter methods.
package mypack;
public cl
{
private int RollNo;
students implements java.io Serializable
private String name;
public students(){}
public void setRollNo(int id)
{
this.RolINo=RollNo;
}
public int getld()
{
return RollNo;
}
public void setName(String name)
{
this.name=name;[ADVANCE JAVA
}
public String getName()
t
return name;
}
}
How to access the JavaBean.
To access the JavaBean class, we should use getter and setter methods.
package mypack;
public class Test
t
public static void main(String argsf])
t
students s=new students(); //object is created
s.setName("Rahul"); —_//setting value to the object
System.out printin(s.getName());
}
}
4.3 standard actions
Standard actions in JSP are used to control the behaviour of the Servlets engine.
In JSP there are 11 standard actions tag. With the help of these tags we can
dynamically insert a file, reuse the beans components, forward user ete,
Syntax:
4.3.2 jsp:inelude:- This tag is used to insert a jsp file into another file , same as
include directive . It is compute at the time request processing phase.
Syntax:
4.3.4 jsp:getProperty:- To get the property of a bean we use this tag. It inserts
the output in a string format which is converted into string.
Syntax:
4.3.5 jsp:forward:- It is basically used to forward the request to another jsp or
any static page. Here the request can be forwarded with or with no
parameters.
Syntax:
.8 jsp:body:~ This tag is used for defining the xml dynamically that is the
elements can be generated during the request time than at the compilation
time.
Syntax:
4.3.9 jsp:attribute:-This tag is used for defining the xml dynamically that is the
elements can be generated during the request time than at the compilation
time.
Syntax:
4.3.10 jsp:text:- To template text in JSP pages this tag is used. The body of this
tag does not contains any elements .It only contains text and EL
expressions.
Syntax: template
4.3.11jsp: output: - Its consists of XML template text which is placed within text
action objects.In this output is declared as XML and DOCTYPE.
Syntax: