0% found this document useful (0 votes)
13 views338 pages

17CS553 Notes 2019 20

The document provides study material on Advanced Java & J2EE, focusing on Enumeration, Auto Boxing, and Annotations. It explains the concept of Enumeration in Java, its differences from C++, and includes examples of creating and using enumerations, as well as the predefined methods associated with them. Additionally, it covers type wrappers, boxing, unboxing, and the advantages and disadvantages of auto-boxing and auto-unboxing in Java.

Uploaded by

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

17CS553 Notes 2019 20

The document provides study material on Advanced Java & J2EE, focusing on Enumeration, Auto Boxing, and Annotations. It explains the concept of Enumeration in Java, its differences from C++, and includes examples of creating and using enumerations, as well as the predefined methods associated with them. Additionally, it covers type wrappers, boxing, unboxing, and the advantages and disadvantages of auto-boxing and auto-unboxing in Java.

Uploaded by

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

Advanced Java & J2EE (17CS553) Study Material

Module-1
Enumeration, Auto Boxing and Annotations
Enumeration

What is Enumeration in Java?


Enumeration is a list of named constants in Java.
How Enumeration in Java different from C++?
In C++ Enumerations are simply list of named integer constants.
In Java, an enumeration defines a class type, which can have constructors, methods and
instance variables.

Enumeration Fundamentals

Enumeration is created using the enum keyword.

Example:

enum Car{Hatchback, Sedan, MPV, SUV, Crossover, Coupe, Convertible}


o The identifiers Hatchback, Sedan, MPV, SUV, Crossover, Coupe, Convertible, are called
ENUMERATION CONSTANTS.
o Each is implicitly declared as public, static and final member of Car.
o The type of the identifier is of type enumeration in which they are declared.
o In Java these constants are called SELF-TYPED, where self refers to the enclosing
enumeration.
Once enumeration is defined, variables of that type can be created.
o Example: Car cr; where cr is a variable of enumeration type Car.
o There is no need to use new operator to instantiate enum, though enumeration defines
class type.
The only variables that can be assigned for cr are those defined by the enumeration.
o Example: cr=Car.MPV;
Two Enumeration constants can be compared for equality by using the == relational operator.
o Example: if(cr==Car.MPV){…}
An enumeration value can also be used to control a switch statement.
o Example: switch(cr){

Case Hatchback:

//…

break;

CSE, KSIT, 2019-20 Page 1


Advanced Java & J2EE (17CS553) Study Material

Case MPV:

//…

break;

default:

//…

Note: In case statements there is no need to qualify the names of the enumeration constants by
their enumeration type name.
When an enumeration constant is displayed, such as in println() statement, its name is output.
o Example: System.out.println(Car.MPV); will output MPV.

The complete program on Car enumeration

enum Car{Hatchback, Sedan, MPV, SUV }


class EnumDemo
{
Public static void main(String args[])
{
Car cr;
cr=Car.SUV;
System.out.println(“Value of car: “+cr);
System.out.println();
cr=Car.MPV;
if(cr==Car.MPV)
System.out.println(“cr contains MPV);
switch(cr)
{
case Hatchback:
System.out.println(“Hatchback is compact car”);
break;
case Sedan:
System.out.println(“Sedan is luxury car”);
break;
case MPV:
System.out.println(“MPV is big family car”);

CSE, KSIT, 2019-20 Page 2


Advanced Java & J2EE (17CS553) Study Material

break;
case SUV:
System.out.println(“SUV is very comfort car”);
Break;
}
}

}
O/P:
Value of cr:MPV
Value of cr:MPV
cr contains SUV
It is a sports car

The values() and valueOf() methods


All enumerations automatically contain two predefined methods values() and valueOf()

General form:

Public static enum-type[] values() Returns an array that contains a list


of the enumeration constants.

Public static enum-type valueOf(String str) Returns the enumeration constant


whose value corresponds to the
string passed in str.

Complete Program
enum Car{Hatchback,Sedan,MPV,SUV}
class EnumDemo
{
public static void main(String[] args)
{
Car cr;
cr=Car.MPV;
System.out.println("Value of cr:"+cr);
System.out.println("Value of cr:"+Car.MPV);
cr=Car.SUV;
if(cr==Car.SUV)
System.out.println("cr contains SUV");
switch(cr)
CSE, KSIT, 2019-20 Page 3
Advanced Java & J2EE (17CS553) Study Material

{
case Hatchback:
System.out.println("It is a compact car");
break;
case Sedan:
System.out.println("It is a comfort car");
break;
case MPV:
System.out.println("It is a car for big family");
break;
case SUV:
System.out.println("It is a sports car");
break;
}

System.out.println("Displaying All Cars using values()");


for(Car c: Car.values())
System.out.println(c);
System.out.println("Displaying MPV using valueOf()");
System.out.println(Car.valueOf("MPV"));
}
}
O/P:
Value of cr:MPV
Value of cr:MPV
cr contains SUV
It is a sports car
Displaying All Cars using values()
Hatchback
Sedan
MPV
SUV
Displaying MPV using valueOf()
MPV

Java Enumeration are class types:

Features:

All enumerations automatically inherit Enum class of java.lang package


Need not to instantiate enum using new operator.
Enum can have constructors, instance variables and methods.
CSE, KSIT, 2019-20 Page 4
Advanced Java & J2EE (17CS553) Study Material

Enum can implement interfaces.


Enum constants are objects of its enumeration type.
The constructor when defined in enumeration is called when each enumeration constant is
created.
Each enumeration constant has its own copy of any instance variable defined in its enumeration
type.
Constructors in enumeration can be overloaded.

Two Restrictions on enumeration:

1. An enumeration cannot inherit another class.


2. An enum cannot be a superclass i.e. enum cannot be extended.

Example 1: Passing one argument to constructor

enum Car{
Hatchback(9),Sedan(12),MPV(20),SUV(35);
int price;
Car (int price)
{
this.price=price;

}
int getPrice()
{
return price;
}

}
class EnumClassDemo
{

public static void main(String[] args)


{
Car cr;
System.out.println("Displaying Prices of Cars");
for(Car c:Car.values())
System.out.println(c+" Car price is "+c.getPrice()+" Lakh ");
}

}
O/P:
Displaying Prices of Cars
Hatchback Car price is 9 Lakh
CSE, KSIT, 2019-20 Page 5
Advanced Java & J2EE (17CS553) Study Material

Sedan Car price is 12 Lakh


MPV Car price is 20 Lakh
SUV Car price is 35 Lakh

Example 2: Passing Two arguments to constructor and constructor overloading

enum Car{
Hatchback(9,"Maruti"),Sedan(12,"Hyundai"),MPV(20,"Toyota"),SUV(35,"Ford"),KIA("KIA");
int price;
String make;
Car(String make)
{
price=-1;
this.make=make;
}
Car (int price,String make)
{
this.price=price;
this.make=make;
}

void display()
{
System.out.println("Car Manufacture Name: "+make+",Price in Lakh: "+price);
}
}
class EnumClassDemo
{

public static void main(String[] args)


{
Car cr;
System.out.println("Displaying Prices of Cars");
for(Car c:Car.values())
c.display();
}

}
O/P:
Displaying Prices of Cars
Car Manufacture Name: Maruti,Price in Lakh: 9
Car Manufacture Name: Hyundai,Price in Lakh: 12
Car Manufacture Name: Toyota,Price in Lakh: 20
Car Manufacture Name: Ford,Price in Lakh: 35
Car Manufacture Name: KIA,Price in Lakh: -1
CSE, KSIT, 2019-20 Page 6
Advanced Java & J2EE (17CS553) Study Material

Enumeration inherits Enum class:


All enumerations automatically inherit java.lang.Enum
Enum class defines several methods that are available for use by all enumerations.
The following list important three methods defined in Enum class:
final int ordinal() This method returns the enumeration constant’s position in the
list (called ordinal value).
Ordinal value begin at zero.

final int compareTo(enum-type e) This method compares ordinal value of two constants of the
same enumeration type.
enum-type is the type of enumeration and e is the constant
being compared to the invoking constant.
If the invoking constant has ordinal value less than e’s, then this
method returns a negative value.
If the two ordinal values are same, then this method returns
zero.
If the invoking constant has ordinal value greater than e’s, then
this method returns a positive value.

boolean equals(Object other) This method returns true if the specified object is equal to this enum
constant.
Note: double equals(==) can be used to compare two enumeration references for equality.

Example: Java program to demonstrate ordinal(), compareTo(), equals() methods, and == operator.
enum Car{Hatchback,Sedan,MPV,SUV}
class EnumMethodsDemo
{
public static void main(String[] args)
{
Car c1,c2,c3;
System.out.println("All Car constants and ordinal value");
for(Car c:Car.values())
System.out.println(c+" "+c.ordinal());
c1=Car.Sedan;
c2=Car.MPV;
c3=Car.SUV;

if(c1.compareTo(c2)<0)
System.out.println(c1+" comes after "+c2);
if(c1.compareTo(c2)>0)
System.out.println(c1+" comes before "+c2);
if(c1.compareTo(c3)==0)
System.out.println(c1+" equals "+c2);
c1=Car.Sedan;
c2=Car.MPV;

CSE, KSIT, 2019-20 Page 7


Advanced Java & J2EE (17CS553) Study Material

c3=Car.Sedan;
if(c1.equals(c2))
System.out.println("Error");
if(c1.equals(c3))
System.out.println(c1+" equals "+c3);

if(c1==c3)
System.out.println(c1+"=="+c3);
}
}

O/P:
All Car constants and ordinal value
Hatchback 0
Sedan 1
MPV 2
SUV 3
Sedan comes after MPV
Sedan equals Sedan
Sedan==Sedan

Type Wrappers
Type wrappers in Java are classes that encapsulate a primitive type within an object.
Type wrappers are Byte, Short, Integer, Long, Float, Double, Character and Boolean.

Character
Character is a wrapper around a char.
The constructor:
o Character(char ch), where, ch specifies that will be wrapped by the Character object being
created.
Method to obtain the char value contained in a Character object
o char charValue(), it returns encapsulated character.

Boolean
Boolean is a wrapper around Boolean values.
Constructors:
o Boolean(Boolean boolValue), where boolValue must be true or false.
o Boolean(String boolString), where boolString must be the string ―true‖ or ―false‖ in upper or
lower case.
Method to obtain a Boolean value from a Boolean object
o boolean booleanValue(), this method return the Boolean equivalent of the invoking
object.

CSE, KSIT, 2019-20 Page 8


Advanced Java & J2EE (17CS553) Study Material

The Numeric type wrappers: Byte, Short, Integer, Long, Float and Double
All of the numeric type wrappers inherit the abstract class Number.
Number declares methods that return the value of an object that return the value of an object in each
of the different number formats.
Constructors:
o Byte(byte value), Byte(String str)
o Short(short value), Short (String str)
o Integer(int value), Integer(String str)
o Long(long value), Long(String str)
o Float(float value), Float(String str)
o Double(double value), Double(String str)
Methods: (defined in Number class)
o byte byteValue(),Returns the value of the specified number as a byte.
o short shortValue(),Returns the value of the specified number as a short.
o int intValue(),Returns the value of the specified number as a int.
o long longValue(),Returns the value of the specified number as a long.
o float floatValue(),Returns the value of the specified number as a float.
o double doubleValue(),Returns the value of the specified number as a double.

Example:

class Wrap
{
public static void main(String[] args)
{
Integer iOb=new Integer(100);
int i=iOb.intValue();
System.out.println("iOb="+iOb+",i="+i);

}
}

O/P:
iOb=100,i=100

Boxing: The process of encapsulating a value within an object is called boxing.


e.g. Integer iOb=new Integer(100);
Unboxing: The process of extracting a value from a type wrapper is called unboxing.
e.g. int i=iOb.intValue();

Auto-boxing and Auto-Unboxing( Handled by the compiler)


Prevents manually boxing and unboxing.

CSE, KSIT, 2019-20 Page 9


Advanced Java & J2EE (17CS553) Study Material

The modern Java code should be written using AutoBoxing/ Unboxing


Autoboxing is the process by which the value of a boxed object is automatically extracted (unboxed) from a
wrapper type when its value is needed.

Example:

class Autobox
{
public static void main(String[] args)
{
Integer iOb=new Integer(100);// autobox int
int i=iOb;//auto-unbox
System.out.println("iOb="+iOb+",i="+i);//displays 100,100

}
}

Autoboxing is applied on
Assignment statements.
Arguments passed to a method.
When a value is returned by a method.
Expressions.
Boolean and Character values

Advantages of Autoboxing and auto-unboxing:


Streamlines the coding of several algorithms.
Removes the tedium of manually boxing and unboxing values
Errors can be prevented.
It is important to generics, which operates only on objects.
Autoboxing makes working with the Collection Framework much easier.
Disadvantages:
There is a overhead added in each auto-boxing and auto-unboxing in the code, which actually is far
less efficient than the equivalent code written using the primitive types.
Restriction
Use type wrappers to only those case in which an object representation of a primitive type is
required. It is not a back door way of eliminating the primitive types.

Autoboxing and Methods

CSE, KSIT, 2019-20 Page 10


Advanced Java & J2EE (17CS553) Study Material

The autoboxing and auto-unboxing might occur when an argument is passed to a method, or when a value is
returned by a method.

Example

class AutoBoxMethods
{
static int method(Integer v)
{
return v; //auto-unbox to int
}
public static void main(String[] args)
{
Integer iOb= method(iOb);
System.out.println("iOb="+iOb);
}
}
O/P
iOb=100

Autoboxing/ Unboxing occurs in Expressions

Within an expression, a numeric object is automatically unboxed. The outcome of the expression is reboxed.

Example

class AutoBoxExpressions
{

public static void main(String[] args)


{
Integer iOb1,iOb2;
int i;
iOb1=100;
System.out.println("Original value of iOb1:"+iOb1);
++iOb1;//automatically unboxed, incremented and then reboxed
iOb2=iOb1+(iOb1/3);//iOb1 is unboxed, result is evaluated and then reboxed
System.out.println("iOb2 after expression:"+iOb2);
i=iOb1+(iOb1/3);//iOb1 is unboxed, result is evaluated and not reboxed
System.out.println("i after expression:"+iOb2);
}
}

O/P

CSE, KSIT, 2019-20 Page 11


Advanced Java & J2EE (17CS553) Study Material

Original value of iOb1:100


iOb2 after expression:134
i after expression:134

Auto-Unboxing allows to mix different types of numeric objects.


Example

class AutoBoxDiffNumObjs
{

public static void main(String[] args)


{
Integer iOb1=100;
Double dOb1=99.99;
/*
iOb1 and dOb1 unboxed, standard type conversion applied and then reboxed
*/

dOb1=iOb1+dOb1;
System.out.println("dOb1="+dOb1);
}
}
O/P
dOb1=199.99

Because of auto-unboxing, the numeric integer object can be used to control a switch statement.
Example

class AutoUnBoxInSwtch
{

public static void main(String[] args)


{
Integer iOb=2;
switch(iOb)
{
case 1:
System.out.println("One");
break;
CSE, KSIT, 2019-20 Page 12
Advanced Java & J2EE (17CS553) Study Material

case 2:
System.out.println("Two");
break;
default:
System.out.println("Error");
}
}
}

O/P
Two

Autoboxing/ Unboxing Boolean and Character Values


Boolean object can also be used to control any of Java’s loop statements.

Example
class AutoBoxChAndBool
{
public static void main(String[] args)
{
Boolean b=true;
//b is auto-unboxed in if expression
if(b) System.out.println("b is true");
Character c='h';
char ch=c; //auto-unboxed
System.out.println("ch is:"+ch);
System.out.println("Unboxing in for loop");
int i=0;
for(;b!=false;)
{
System.out.println(++i);
if(i>=5) b=false;
}
b=true;
i=0;
System.out.println("Unboxing in while loop");
while(b)
{
System.out.println(++i);
if(i>=5) b=false;
}
b=true;
b=true;
i=0;
CSE, KSIT, 2019-20 Page 13
Advanced Java & J2EE (17CS553) Study Material

System.out.println("Unboxing in do-while loop");


do
{
System.out.println(++i);
if(i>=5) b=false;
}while(b);
}

}
/*
O/P
b is true
ch is:h
Unboxing in for loop
1
2
3
4
5
Unboxing in while loop
1
2
3
4
5
Unboxing in do-while loop
1
2
3
4
5
*/

Autoboxing/Unboxing helps prevent Errors

Example:
class AutoBoxPrvntErrs
{
public static void main(String[] args)
{
Integer iOb=1000;
int i=iOb.byteValue(); //manually unbox as byte
System.out.println(i); //Result is garbage
}
CSE, KSIT, 2019-20 Page 14
Advanced Java & J2EE (17CS553) Study Material

O/P
-24

A word of warning
The primitive types should not be abandoned in favor of type wrappers.

The following code snippet demonstrates the bad use of Autoboxing/Unboxing:

Double a,b,c;
a=3;
b=4;
c=Math.sqrt((a*a)+(b*b));
System.out.println(―Hypotenuse is: ―+c);

In the above code autoboxing/ unboxing adds overhead that is not present if the primitive types are used.

Annotations
Annotations, a form of metadata, provide data about a program that is not part of the program itself.
Annotations have no direct effect on the operation of the code they annotate.

Annotations have a number of uses, among them:

Information for the compiler — Annotations can be used by the compiler to detect errors or
suppress warnings.
Compile-time and deployment-time processing — Software tools can process annotation
information to generate code, XML files, and so forth.
Runtime processing — Some annotations are available to be examined at runtime.

Where Annotations Can Be Used


Annotations can be applied to declarations: declarations of classes, fields, methods, and other program
elements. When used on a declaration, each annotation often appears, by convention, on its own line.

Predefined Annotation Types


A set of annotation types are predefined in the Java SE API. Some annotation types are used by the Java
compiler, and some apply to other annotations.

Annotation Types Used by the Java Language


The predefined annotation types defined in java.lang are

@Deprecated @Deprecated annotation indicates that the

CSE, KSIT, 2019-20 Page 15


Advanced Java & J2EE (17CS553) Study Material

marked element is deprecated and should no


longer be used. The compiler generates a
warning whenever a program uses a method,
class, or field with the @Deprecated
annotation.
e.g.
// Javadoc comment follows
/**
* @deprecated
* explanation of why it was
deprecated
*/
@Deprecated
static void deprecatedMethod()
{ }
}

@Override @Override annotation informs the compiler


that the element is meant to override an
element declared in a superclass.
e.g.
// mark method as a superclass
method
// that has been overridden
@Override
int overriddenMethod() { }

While it is not required to use this


annotation when overriding a method, it
helps to prevent errors. If a method marked
with @Override fails to correctly override
a method in one of its superclasses, the
compiler generates an error.

@SuppressWarnings. @SuppressWarnings annotation tells the


compiler to suppress specific warnings that it
would otherwise generate.
e.g.
// use a deprecated method and
tell
// compiler not to generate a
warning

@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
// deprecation warning
// - suppressed

objectOne.deprecatedMethod();
}

To suppress multiple categories of


warnings, use the following syntax:

CSE, KSIT, 2019-20 Page 16


Advanced Java & J2EE (17CS553) Study Material
@SuppressWarnings({"unchecked",
"deprecation"})

Annotations That Apply to Other Annotations


Annotations that apply to other annotations are called meta-annotations. There are several meta-annotatio n
types defined in java.lang.annotation.

@Retention @Retention annotation specifies how the


marked annotation is stored:

RetentionPolicy.SOURCE – The
marked annotation is retained only in
the source level and is ignored by the
compiler.
RetentionPolicy.CLASS – The
marked annotation is retained by the
compiler at compile time, but is ignored
by the Java Virtual Machine (JVM).
RetentionPolicy.RUNTIME – The
marked annotation is retained by the
JVM so it can be used by the runtime
environment.

@Documented @Documented annotation indicates that whenever


the specified annotation is used those elements
should be documented using the Javadoc tool.
@Target @Target annotation marks another annotation
to restrict what kind of Java elements the
annotation can be applied to. A target
annotation specifies one of the following
element types as its value:

ElementType.ANNOTATION_TYPE can
be applied to an annotation type.
ElementType.CONSTRUCTOR can be
applied to a constructor.
ElementType.FIELD can be applied to
a field or property.
ElementType.LOCAL_VARIABLE can be
applied to a local variable.
ElementType.METHOD can be applied
to a method-level annotation.
ElementType.PACKAGE can be applied
to a package declaration.
ElementType.PARAMETER can be

CSE, KSIT, 2019-20 Page 17


Advanced Java & J2EE (17CS553) Study Material

applied to the parameters of a method.


ElementType.TYPE can be applied to
any element of a class.

@Inherited @Inherited annotation indicates that the


annotation type can be inherited from the super
class. When the user queries the annotation type
and the class has no annotation for this type, the
class' superclass is queried for the annotation type.
This annotation applies only to class declarations.
@Repeatable @Repeatable annotation, introduced in Java SE 8,
indicates that the marked annotation can be
applied more than once to the same declaration or
type use.

Types of Annotations:
A Marker annotations It is a special kind of annotations that contains no
members. Its sole purpose is to mark a declaration.

e.gs. @Documented, @Inherited, @Override,


@Deprecated
Single Member A single member annotation contains only one
annotations member.

Multi-Member A Multi-Member annotations contains more than one


annotations member.

Restrictions on Annotation declarations:


No annotation can inherit another.
All methods declared by annotations must be without parameters.
They must return one of the following:
o A primitive type, such as int or double.
o An object of type String or Class.
o An enum type.
o Another annotation type.
o An Array of one of the preceding types.
Annotations cannot be generic. In other words, they cannot take type parameters.
CSE, KSIT, 2019-20 Page 18
Advanced Java & J2EE (17CS553) Study Material

Annotation methods cannot specify a throws clause.

Module-2:
The Collections Framework

Trail: Collections
This section describes the Java Collections Framework. Here, you will learn what collections are and how
they can make your job easier and programs better. You'll learn about the core elements — interfaces,
implementations, aggregate operations, and algorithms — that comprise the Java Collections Framework.

Introduction tells you what collections are, and how they'll make your job easier and your programs
better. You'll learn about the core elements that comprise the Collections Framework: interfaces,
implementations and algorithms.

Interfaces describes the core collection interfaces, which are the heart and soul of the Java Collections

CSE, KSIT, 2019-20 Page 19


Advanced Java & J2EE (17CS553) Study Material

Framework. You'll learn general guidelines for effective use of these interfaces, including when to use
which interface. You'll also learn idioms for each interface that will help you get the most out of the
interfaces.

Aggregate Operations iterate over collections on your behalf, which enable you to write more concise
and efficient code that process elements stored in collections.

Implementations describes the JDK's general-purpose collection implementations and tells you when to
use which implementation. You'll also learn about the wrapper implementations, which add functionality
to general-purpose implementations.

Algorithms describes the polymorphic algorithms provided by the JDK to operate on collections. With
any luck you'll never have to write your own sort routine again!

Custom Implementations tells you why you might want to write your own collection implementation
(instead of using one of the general-purpose implementations provided by the JDK), and how you'd go
about it. It's easy with the JDK's abstract collection implementations!

Interoperability tells you how the Collections Framework interoperates with older APIs that predate the
addition of Collections to Java. Also, it tells you how to design new APIs so that they'll interoperate
seamlessly with other new APIs.

Introduction to Collections
collection — sometimes called a container — is simply an object that groups multiple elements into a single
unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they
represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a
collection of letters), or a telephone directory (a mapping of names to phone numbers).

What Is a Collections Framework?

A collections framework is a unified architecture for representing and manipulating collections. All
collections frameworks contain the following:

Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be
manipulated independently of the details of their representation. In object-oriented languages,
interfaces generally form a hierarchy.
Implementations: These are the concrete implementations of the collection interfaces. In essence,
they are reusable data structures.
Algorithms: These are the methods that perform useful computations, such as searching and sorting,
on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is,
the same method can be used on many different implementations of the appropriate collection
interface. In essence, algorithms are reusable functionality.

Benefits of the Java Collections Framework

The Java Collections Framework provides the following benefits:

CSE, KSIT, 2019-20 Page 20


Advanced Java & J2EE (17CS553) Study Material

Reduces programming effort: By providing useful data structures and algorithms, the Collections
Framework frees you to concentrate on the important parts of your program rather than on the low-
level "plumbing" required to make it work. By facilitating interoperability among unrelated APIs, the
Java Collections Framework frees you from writing adapter objects or conversion code to connect
APIs.
Increases program speed and quality: This Collections Framework provides high-performance,
high-quality implementations of useful data structures and algorithms. The various implementations
of each interface are interchangeable, so programs can be easily tuned by switching collection
implementations. Because you're freed from the drudgery of writing your own data structures, you'll
have more time to devote to improving programs' quality and performance.
Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by
which APIs pass collections back and forth. If my network administration API furnishes a collection
of node names and if your GUI toolkit expects a collection of column headings, our APIs will
interoperate seamlessly, even though they were written independently.
Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and
furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its
collections. There was little consistency among these ad hoc collections sub-APIs, so you had to
learn each one from scratch, and it was easy to make mistakes when using them. With the advent of
standard collection interfaces, the problem went away.
Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and
implementers don't have to reinvent the wheel each time they create an API that relies on collections;
instead, they can use standard collection interfaces.
Fosters software reuse: New data structures that conform to the standard collection interfaces are
by nature reusable. The same goes for new algorithms that operate on objects that implement these
interfaces.

The Collection Interfaces


The core collection interfaces encapsulate different types of collections, which are shown in the figure
below. These interfaces allow collections to be manipulated independently of the details of their
representation. Core collection interfaces are the foundation of the Java Collections Framework. As you can
see in the following figure, the core collection interfaces form a hierarchy.

A Set is a special kind of Collection, a SortedSet is a special kind of Set, and so forth. Note also that the
hierarchy consists of two distinct trees — a Map is not a true Collection.

The following list describes the core collection interfaces:

Interface Description
Collection The root of the collection hierarchy. A collection represents a group of objects

CSE, KSIT, 2019-20 Page 21


Advanced Java & J2EE (17CS553) Study Material

known as its elements.

Enables to work with group of objects.


Set A collection that cannot contain duplicate elements. Extends Collection.
List An ordered collection (sometimes called a sequence). Lists can contain duplicate
elements.
Queue A collection used to hold multiple elements prior to processing. Besides basic
Collection operations, a Queue provides additional insertion, extraction, and
inspection operations.
Deque (Double-ended A collection used to hold multiple elements prior to processing. Besides basic
queue) Collection operations, a Deque provides additional insertion, extraction, and
inspection operations.
SortedSet a Set that maintains its elements in ascending order. Several additional operations
are provided to take advantage of the ordering. Sorted sets are used for naturally
ordered sets, such as word lists and membership rolls.
NavigableSet Extends SortedSet to handle retrieval of elements based on closest-match searches.
Map An object that maps keys to values. A Map cannot contain duplicate keys; each key
can map to at most one value.
SortedMap A Map that maintains its mappings in ascending key order. This is the Map analog
of SortedSet. Sorted maps are used for naturally ordered collections of key/value
pairs, such as dictionaries and telephone directories.
Other interfaces Comparator, RandomAccess, Iterator, and ListIterators
Comparator Defines how two objects are compared.
Iterator and Both enumerates the objects within a collection.
ListIterator
RandomAccess A list indicates that it supports efficient, random access to its elements.

Optional Methods of interfaces

For the purpose of flexibility, the collection interfaces allows some methods to be optional.
The optional methods enable to modify the contents of a collection.
Collections that support these methods are called MODIFIABLE.
Collections that do not allow their contents to be changed are called UNMODIFIABLE.
If an attempt is made to use one of these methods on unmodifiable collection, an
UnsupportedException is thrown.
All the built-in collections are modifiable.

The Collection Interface

The Collection interface is the foundation upon which the Collection Framework is built because it
must be implemented by any class that defines collection.
Collection is a generic interface that has this declaration:

Interface Collection<E>

E specifies the type of objects that Collection will hold.


Collection extends the Iterable interface. This means that all collections can be cycled through by
use of for-each style for loop.

CSE, KSIT, 2019-20 Page 22


Advanced Java & J2EE (17CS553) Study Material

Methods Summary
Methods

Modifier and
Method and Description
Type

add(E e)
boolean
Ensures that this collection contains the specified element (optional operation).

addAll(Collection<? extends E> c)


boolean
Adds all of the elements in the specified collection to this collection (optional operation).

clear()
void
Removes all of the elements from this collection (optional operation).

contains(Object o)
boolean
Returns true if this collection contains the specified element.

containsAll(Collection<?> c)
boolean
Returns true if this collection contains all of the elements in the specified collection.

equals(Object o)
boolean
Compares the specified object with this collection for equality.

hashCode()
int
Returns the hash code value for this collection.

isEmpty()
boolean
Returns true if this collection contains no elements.

iterator()
Iterator<E>
Returns an iterator over the elements in this collection.

remove(Object o)
boolean Removes a single instance of the specified element from this collection, if it is present
(optional operation).

CSE, KSIT, 2019-20 Page 23


Advanced Java & J2EE (17CS553) Study Material

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

retainAll(Collection<?> c)
boolean Retains only the elements in this collection that are contained in the specified collection
(optional operation).

size()
int
Returns the number of elements in this collection.

toArray()
Object[]
Returns an array containing all of the elements in this collection.

toArray(T[] a)
<T> T[] Returns an array containing all of the elements in this collection; the runtime type of the
returned array is that of the specified array.

Exceptions thrown by the Collection methods

UnsupportedOperationException
ClassCastException
IllegalArgumentException
IllegalStateException

Interface List<E>
Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>

Methods Summary
Modifier and
Method and Description
Type
add(int index, E element)
void
Inserts the specified element at the specified position in this list (optional operation).
addAll(Collection<? extends E> c)
boolean Appends all of the elements in the specified collection to the end of this list, in the order
that they are returned by the specified collection's iterator (optional operation).
boolean addAll(int index, Collection<? extends E> c)

CSE, KSIT, 2019-20 Page 24


Advanced Java & J2EE (17CS553) Study Material

Inserts all of the elements in the specified collection into this list at the specified position
(optional operation).
get(int index)
E
Returns the element at the specified position in this list.
indexOf(Object o)
int Returns the index of the first occurrence of the specified element in this list, or -1 if this
list does not contain the element.
lastIndexOf(Object o)
int Returns the index of the last occurrence of the specified element in this list, or -1 if this
list does not contain the element.
listIterator()
ListIterator<E>
Returns a list iterator over the elements in this list (in proper sequence).
listIterator(int index)
ListIterator<E> Returns a list iterator over the elements in this list (in proper sequence), starting at the
specified position in the list.
remove(int index)
E
Removes the element at the specified position in this list (optional operation).
set(int index, E element)
E Replaces the element at the specified position in this list with the specified element
(optional operation).
subList(int fromIndex, int toIndex)
List<E> Returns a view of the portion of this list between the specified fromIndex, inclusive, and
toIndex, exclusive.

Interface Set<E>
Type Parameters:
E - the type of elements maintained by this set
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Subinterfaces:
NavigableSet<E>, SortedSet<E>

Methods Summary
Modifier and
Method and Description
Type
add(E e)
boolean
Adds the specified element to this set if it is not already present (optional operation).
addAll(Collection<? extends E> c)
boolean Adds all of the elements in the specified collection to this set if they're not already present
(optional operation).
void clear()

CSE, KSIT, 2019-20 Page 25


Advanced Java & J2EE (17CS553) Study Material

Removes all of the elements from this set (optional operation).


contains(Object o)
boolean
Returns true if this set contains the specified element.
containsAll(Collection<?> c)
boolean
Returns true if this set contains all of the elements of the specified collection.
equals(Object o)
boolean
Compares the specified object with this set for equality.
hashCode()
int
Returns the hash code value for this set.
isEmpty()
boolean
Returns true if this set contains no elements.
iterator()
Iterator<E>
Returns an iterator over the elements in this set.
remove(Object o)
boolean
Removes the specified element from this set if it is present (optional operation).
removeAll(Collection<?> c)
boolean Removes from this set all of its elements that are contained in the specified collection
(optional operation).
retainAll(Collection<?> c)
boolean Retains only the elements in this set that are contained in the specified collection (optional
operation).
size()
int
Returns the number of elements in this set (its cardinality).
toArray()
Object[]
Returns an array containing all of the elements in this set.
toArray(T[] a)
<T> T[] Returns an array containing all of the elements in this set; the runtime type of the returned
array is that of the specified array.

Interface SortedSet<E>
Type Parameters:
E - the type of elements maintained by this set
All Superinterfaces:
Collection<E>, Iterable<E>, Set<E>
All Known Subinterfaces:
NavigableSet<E>

Methods Summary
Modifier and Type Method and Description
Comparator<? super comparator()
E> Returns the comparator used to order the elements in this set, or null if this set uses the

CSE, KSIT, 2019-20 Page 26


Advanced Java & J2EE (17CS553) Study Material

natural ordering of its elements.


first()
E
Returns the first (lowest) element currently in this set.
headSet(E toElement)
SortedSet<E> Returns a view of the portion of this set whose elements are strictly less than
toElement.
last()
E
Returns the last (highest) element currently in this set.
subSet(E fromElement, E toElement)
SortedSet<E> Returns a view of the portion of this set whose elements range from fromElement,
inclusive, to toElement, exclusive.
tailSet(E fromElement)
SortedSet<E> Returns a view of the portion of this set whose elements are greater than or equal to
fromElement.

Interface NavigableSet<E>
Type Parameters:
E - the type of elements maintained by this set
All Superinterfaces:
Collection<E>, Iterable<E>, Set<E>, SortedSet<E>

Methods Summary
Modifier and
Method and Description
Type
ceiling(E e)
E Returns the least element in this set greater than or equal to the given element, or null if
there is no such element.
descendingIterator()
Iterator<E>
Returns an iterator over the elements in this set, in descending order.
descendingSet()
NavigableSet<E>
Returns a reverse order view of the elements contained in this set.
floor(E e)
E Returns the greatest element in this set less than or equal to the given element, or null if
there is no such element.
headSet(E toElement, boolean inclusive)
NavigableSet<E> Returns a view of the portion of this set whose elements are less than (or equal to, if
inclusive is true) toElement.
higher(E e)
E Returns the least element in this set strictly greater than the given element, or null if
there is no such element.
lower(E e)
E
Returns the greatest element in this set strictly less than the given element, or null if

CSE, KSIT, 2019-20 Page 27


Advanced Java & J2EE (17CS553) Study Material

there is no such element.


pollFirst()
E
Retrieves and removes the first (lowest) element, or returns null if this set is empty.
pollLast()
E
Retrieves and removes the last (highest) element, or returns null if this set is empty.
subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
NavigableSet<E> Returns a view of the portion of this set whose elements range from fromElement to
toElement.
tailSet(E fromElement, boolean inclusive)
NavigableSet<E> Returns a view of the portion of this set whose elements are greater than (or equal to, if
inclusive is true) fromElement.

Interface Queue<E>

Type Parameters:
E - the type of elements held in this collection
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Subinterfaces:
BlockingDeque<E>, BlockingQueue<E>, Deque<E>, TransferQueue<E>

Methods Summary

Modifier
Method and Description
and Type
add(E e)
Inserts the specified element into this queue if it is possible to do so immediately without
boolean
violating capacity restrictions, returning true upon success and throwing an
IllegalStateException if no space is currently available.
element()
E
Retrieves, but does not remove, the head of this queue.
offer(E e)
boolean Inserts the specified element into this queue if it is possible to do so immediately without
violating capacity restrictions.
peek()
E
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
poll()
E
Retrieves and removes the head of this queue, or returns null if this queue is empty.
remove()
E
Retrieves and removes the head of this queue.

Interface Deque<E>
Type Parameters:
E - the type of elements held in this collection

CSE, KSIT, 2019-20 Page 28


Advanced Java & J2EE (17CS553) Study Material

All Superinterfaces:
Collection<E>, Iterable<E>, Queue<E>
All Known Subinterfaces:
BlockingDeque<E>

Methods Summary
Modifier
Method and Description
and Type
addFirst(E e)
void Inserts the specified element at the front of this deque if it is possible to do so immediately
without violating capacity restrictions.
addLast(E e)
void Inserts the specified element at the end of this deque if it is possible to do so immediately
without violating capacity restrictions.
descendingIterator()
Iterator<E>
Returns an iterator over the elements in this deque in reverse sequential order.
getFirst()
E
Retrieves, but does not remove, the first element of this deque.
getLast()
E
Retrieves, but does not remove, the last element of this deque.
offer(E e)
Inserts the specified element into the queue represented by this deque (in other words, at the
boolean
tail of this deque) if it is possible to do so immediately without violating capacity restrictions,
returning true upon success and false if no space is currently available.
offerFirst(E e)
boolean Inserts the specified element at the front of this deque unless it would violate capacity
restrictions.
offerLast(E e)
boolean Inserts the specified element at the end of this deque unless it would violate capacity
restrictions.
peek()
E Retrieves, but does not remove, the head of the queue represented by this deque (in other
words, the first element of this deque), or returns null if this deque is empty.
peekFirst()
E Retrieves, but does not remove, the first element of this deque, or returns null if this deque is
empty.
peekLast()
E Retrieves, but does not remove, the last element of this deque, or returns null if this deque is
empty.
poll()
E Retrieves and removes the head of the queue represented by this deque (in other words, the
first element of this deque), or returns null if this deque is empty.
pollFirst()
E
Retrieves and removes the first element of this deque, or returns null if this deque is empty.

CSE, KSIT, 2019-20 Page 29


Advanced Java & J2EE (17CS553) Study Material

pollLast()
E
Retrieves and removes the last element of this deque, or returns null if this deque is empty.
pop()
E
Pops an element from the stack represented by this deque.
push(E e)
Pushes an element onto the stack represented by this deque (in other words, at the head of this
void
deque) if it is possible to do so immediately without violating capacity restrictions, returning
true upon success and throwing an IllegalStateException if no space is currently available.
removeFirst()
E
Retrieves and removes the first element of this deque.
removeFirstOccurrence(Object o)
boolean
Removes the first occurrence of the specified element from this deque.
removeLastOccurrence(Object o)
boolean
Removes the last occurrence of the specified element from this deque.

CSE, KSIT, 2019-20 Page 30


Advanced Java & J2EE (17CS553) Study Material

The Collection Classes summary


Class Description

AbstractCollection Implements most of the Collection interface.

AbstractList Extends AbstractCollection and implements most of the List Interface.

AbstractQueue Extends AbstractCollection and implements most of the Queue


Interface.

AbstractSequentialList Extends AbstractList for use by a collection that uses sequential rather
than random access of its elements.

LinkedList Implements a linked list by extending AbstractSequentialList.

ArrayList Implements a dynamic array by extending AbstractList.

ArrayDeque Implements a dynamic double-ended queue by extending


AbstractCollection and implementing the Deque interface.

AbstractSet Extends AbstractCollection and implements most of the Set interface.

EnumSet Extends AbstractSet for use with enum elements.

HashSet Extends AbstarctSet for use with a hash table.

LinkedHashSet Extends HashSet to allow insertion-order iterations.

PriorityQueue Extends AbsstractQueue to support a priority-based queue.

TreeSet Implements a set stored in a tree. Extends AbstractSet.

Note: None of the collection classes are synchronized.

The ArrayList Class


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

<E> specifies the type of object that the ArrayList will hold.

ArrayList supports dynamic array that can grow as needed.


ArrayList is a variable-length array of object references.
ArrayList can dynamically increase or decrease in size.
ArrayLists are created with an initial size. When this size is exceeded, the collection is automatically
enlarged. When objects are removed, the array can be shrunk.

Constructors Summary

Constructor and Description

CSE, KSIT, 2019-20 Page 31


Advanced Java & J2EE (17CS553) Study Material

ArrayList()

Constructs an empty list with an initial capacity of ten.

ArrayList(Collection<? extends E> c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the
collection's iterator.

Or

This constructor builds an array list that is initialized with the elements of the collection c.

ArrayList(int initialCapacity)

Constructs an empty list with the specified initial capacity.

Methods Summary
Methods

Modifier and
Method and Description
Type

add(E e)
boolean
Appends the specified element to the end of this list.

add(int index, E element)


void
Inserts the specified element at the specified position in this list.

addAll(Collection<? extends E> c)


boolean Appends all of the elements in the specified collection to the end of this list, in the order that
they are returned by the specified collection's Iterator.

addAll(int index, Collection<? extends E> c)


boolean Inserts all of the elements in the specified collection into this list, starting at the specified
position.

clear()
void
Removes all of the elements from this list.

CSE, KSIT, 2019-20 Page 32


Advanced Java & J2EE (17CS553) Study Material

clone()
Object
Returns a shallow copy of this ArrayList instance.

contains(Object o)
boolean
Returns true if this list contains the specified element.

ensureCapacity(int minCapacity)
void Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at
least the number of elements specified by the minimum capacity argument.

get(int index)
E
Returns the element at the specified position in this list.

indexOf(Object o)
int Returns the index of the first occurrence of the specified element in this list, or -1 if this list
does not contain the element.

isEmpty()
boolean
Returns true if this list contains no elements.

iterator()
Iterator<E>
Returns an iterator over the elements in this list in proper sequence.

lastIndexOf(Object o)
int Returns the index of the last occurrence of the specified element in this list, or -1 if this list
does not contain the element.

remove(int index)
E
Removes the element at the specified position in this list.

remove(Object o)
boolean
Removes the first occurrence of the specified element from this list, if it is present.

removeAll(Collection<?> c)
boolean
Removes from this list all of its elements that are contained in the specified collection.

CSE, KSIT, 2019-20 Page 33


Advanced Java & J2EE (17CS553) Study Material

removeRange(int fromIndex, int toIndex)


protected void Removes from this list all of the elements whose index is between fromIndex, inclusive, and
toIndex, exclusive.

retainAll(Collection<?> c)
boolean
Retains only the elements in this list that are contained in the specified collection.

set(int index, E element)


E
Replaces the element at the specified position in this list with the specified element.

size()
int
Returns the number of elements in this list.

subList(int fromIndex, int toIndex)


List<E> Returns a view of the portion of this list between the specified fromIndex, inclusive, and
toIndex, exclusive.

toArray()
Object[] Returns an array containing all of the elements in this list in proper sequence (from first to
last element).

toArray(T[] a)
<T> T[] Returns an array containing all of the elements in this list in proper sequence (from first to
last element); the runtime type of the returned array is that of the specified array.

trimToSize()
void
Trims the capacity of this ArrayList instance to be the list's current size.

Example program:

import java.util.*;

class ArrayListDemo
{
public static void main(String[] args)
{
//Create an array list

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

CSE, KSIT, 2019-20 Page 34


Advanced Java & J2EE (17CS553) Study Material

System.out.println("Initial size of a1: "+a1.size());

//Add elements to the array


a1.add("C");
a1.add("A");
a1.add("E");
a1.add("B");
a1.add("D");
a1.add("F");
a1.add(1,"A2");
System.out.println("size of a1 after addition: "+a1.size());
//Display array list
System.out.println("Contents of a1: "+a1);
//Remove elements from the array list
a1.remove("F");
a1.remove(2);
System.out.println("size of a1 after deletion: "+a1.size());
System.out.println("Contents of a1: "+a1);
}
}
The output of the program is shown here:

Initial size of a1: 0


size of a1 after addition: 7
Contents of a1: [C, A2, A, E, B, D, F]
size of a1 after deletion: 5
Contents of a1: [C, A2, E, B, D]
Obtaining an Array from an ArrayList

The actual array can be obtained from an ArrayList.

Methods:

toArray()
Object[] Returns an array containing all of the elements in this list in proper sequence (from first to last
element).

toArray(T[] a)
<T> T[] Returns an array containing all of the elements in this list in proper sequence (from first to last
element); the runtime type of the returned array is that of the specified array.

Example:

import java.util.*;
class ArrayListToArray
{
public static void main(String[] args)
CSE, KSIT, 2019-20 Page 35
Advanced Java & J2EE (17CS553) Study Material

{
//Create an array list

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


//Add elements to the array
a1.add(1);
a1.add(2);
a1.add(3);
a1.add(4);

//Display array list


System.out.println("Contents of a1: "+a1);
//Get the array
Integer[] ia=new Integer[a1.size()];
ia=a1.toArray(ia);
//Sum the array
int sum=0;
for(int a:a1) sum+=a;
System.out.println("Sum is: "+sum);

}
}
The output of the program is shown here:
Contents of a1: [1, 2, 3, 4]
Sum is: 10

The LinkedList Class


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

Constructors Summary
Constructors

Constructor and Description

LinkedList()

Constructs an empty list.

LinkedList(Collection<? extends E> c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the
collection's iterator.

Methods Summary

CSE, KSIT, 2019-20 Page 36


Advanced Java & J2EE (17CS553) Study Material

Methods

Modifier and
Method and Description
Type

add(E e)
boolean
Appends the specified element to the end of this list.

add(int index, E element)


void
Inserts the specified element at the specified position in this list.

addAll(Collection<? extends E> c)


boolean Appends all of the elements in the specified collection to the end of this list, in the order
that they are returned by the specified collection's iterator.

addAll(int index, Collection<? extends E> c)


boolean Inserts all of the elements in the specified collection into this list, starting at the specified
position.

addFirst(E e)
void
Inserts the specified element at the beginning of this list.

addLast(E e)
void
Appends the specified element to the end of this list.

clear()
void
Removes all of the elements from this list.

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

contains(Object o)
boolean
Returns true if this list contains the specified element.

descendingIterator()
Iterator<E>
Returns an iterator over the elements in this deque in reverse sequential order.

CSE, KSIT, 2019-20 Page 37


Advanced Java & J2EE (17CS553) Study Material

element()
E
Retrieves, but does not remove, the head (first element) of this list.

get(int index)
E
Returns the element at the specified position in this list.

getFirst()
E
Returns the first element in this list.

getLast()
E
Returns the last element in this list.

indexOf(Object o)
int Returns the index of the first occurrence of the specified element in this list, or -1 if this
list does not contain the element.

lastIndexOf(Object o)
int Returns the index of the last occurrence of the specified element in this list, or -1 if this
list does not contain the element.

listIterator(int index)
ListIterator<E> Returns a list-iterator of the elements in this list (in proper sequence), starting at the
specified position in the list.

offer(E e)
boolean
Adds the specified element as the tail (last element) of this list.

offerFirst(E e)
boolean
Inserts the specified element at the front of this list.

offerLast(E e)
boolean
Inserts the specified element at the end of this list.

peek()
E
Retrieves, but does not remove, the head (first element) of this list.

CSE, KSIT, 2019-20 Page 38


Advanced Java & J2EE (17CS553) Study Material

peekFirst()
E Retrieves, but does not remove, the first element of this list, or returns null if this list is
empty.

peekLast()
E Retrieves, but does not remove, the last element of this list, or returns null if this list is
empty.

poll()
E
Retrieves and removes the head (first element) of this list.

pollFirst()
E
Retrieves and removes the first element of this list, or returns null if this list is empty.

pollLast()
E
Retrieves and removes the last element of this list, or returns null if this list is empty.

pop()
E
Pops an element from the stack represented by this list.

push(E e)
void
Pushes an element onto the stack represented by this list.

remove()
E
Retrieves and removes the head (first element) of this list.

remove(int index)
E
Removes the element at the specified position in this list.

remove(Object o)
boolean
Removes the first occurrence of the specified element from this list, if it is present.

removeFirst()
E
Removes and returns the first element from this list.

boolean removeFirstOccurrence(Object o)

CSE, KSIT, 2019-20 Page 39


Advanced Java & J2EE (17CS553) Study Material

Removes the first occurrence of the specified element in this list (when traversing the list
from head to tail).

removeLast()
E
Removes and returns the last element from this list.

removeLastOccurrence(Object o)
boolean Removes the last occurrence of the specified element in this list (when traversing the list
from head to tail).

set(int index, E element)


E
Replaces the element at the specified position in this list with the specified element.

size()
int
Returns the number of elements in this list.

toArray()
Object[] Returns an array containing all of the elements in this list in proper sequence (from first to
last element).

toArray(T[] a)
<T> T[] Returns an array containing all of the elements in this list in proper sequence (from first to
last element); the runtime type of the returned array is that of the specified array.

Example program

import java.util.*;
class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList<String> ll=new LinkedList<String>();

//Add elements
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");

CSE, KSIT, 2019-20 Page 40


Advanced Java & J2EE (17CS553) Study Material

ll.addLast("Z");
ll.addFirst("A");
ll.add(1,"A2");
System.out.println("Original Contents of ll : "+ll);
//Remove elements from linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents after ll deletion : "+ll);
//Remove first and last
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last : "+ll);
//Get and Set
String s=ll.get(2);
ll.set(2,"Changed");
System.out.println("ll after change : "+ll);
}
}

The output of the program is shown here:

Original Contents of ll : [A, A2, F, B, D, E, C, Z]


Contents after ll deletion : [A, A2, D, E, C, Z]
ll after deleting first and last : [A2, D, E, C]
ll after change : [A2, D, Changed, C]

The HashSet Class


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

Note:
A hash table stores information by using a mechanism called hasing. In hashing, the informational content of
a key is used to determine a unique value called hash code. The hash code is then used as the index at which
the data associated with the key is stored.

This class offers constant time performance for the basic operations (add, remove, contains and size),
assuming the hash function disperses the elements properly among the buckets. Iterating over this set
requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the
"capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the
initial capacity too high (or the load factor too low) if iteration performance is important.

Constructors Summary
Constructors

Constructor and Description

CSE, KSIT, 2019-20 Page 41


Advanced Java & J2EE (17CS553) Study Material

HashSet()

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor
(0.75).

HashSet(Collection<? extends E> c)

Constructs a new set containing the elements in the specified collection.

HashSet(int initialCapacity)

Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default
load factor (0.75).

HashSet(int initialCapacity, float loadFactor)

Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the
specified load factor.

HashSet does not define any additional methods beyond those provided by its superclasses and
interfaces.
HashSet does not guarantee the order of its elements.

Example Program:

import java.util.*;
class HashSetDemo
{
public static void main(String[] args)
{
HashSet<String> hs=new HashSet<String>();
//Add elements to the hash set
hs.add("A");
hs.add("B");
hs.add("C");
hs.add("D");
hs.add("E");
hs.add("F");
System.out.println(hs);
}
}

The output of the program is shown here:

[D, E, F, A, B, C]

CSE, KSIT, 2019-20 Page 42


Advanced Java & J2EE (17CS553) Study Material

The LinkedHashSet Class

public class LinkedHashSet<E>


extends HashSet<E>
implements Set<E>, Cloneable, Serializable

LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were
inserted. This allows insertion-order iteration over the set. That is, when cycling through a
LinkedHashSet using an iterators, the elements will be returned in the order in which they were
inserted.
This class adds no members of its own.

Constructors Summary
Constructors

Constructor and Description

LinkedHashSet()

Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).

LinkedHashSet(Collection<? extends E> c)

Constructs a new linked hash set with the same elements as the specified collection.

LinkedHashSet(int initialCapacity)

Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).

LinkedHashSet(int initialCapacity, float loadFactor)

Constructs a new, empty linked hash set with the specified initial capacity and load factor.

Example Program:

import java.util.*;
class LinkedHashSetDemo
{
public static void main(String[] args)
{
LinkedHashSet<String> lhs=new LinkedHashSet<String>();
//Add elements to the linked hash set
lhs.add("A");
lhs.add("B");
lhs.add("C");
lhs.add("D");
CSE, KSIT, 2019-20 Page 43
Advanced Java & J2EE (17CS553) Study Material

lhs.add("E");
lhs.add("F");
System.out.println(lhs);
}
}

The output of the program is shown here:


[A, B, C, D, E, F]

The TreeSet Class


public class TreeSet<E>
extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable

This class creates a collection that uses a tree for storge.


Objects are stored in sorted, ascending order.
Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing
large amount of sorted information that must be found quickly.

Constructors Summary
Constructors

Constructor and Description

TreeSet()

Constructs a new, empty tree set, sorted according to the natural ordering of its elements.

TreeSet(Collection<? extends E> c)

Constructs a new tree set containing the elements in the specified collection, sorted according to the natural
ordering of its elements.

TreeSet(Comparator<? super E> comparator)

Constructs a new, empty tree set, sorted according to the specified comparator.

TreeSet(SortedSet<E> s)

Constructs a new tree set containing the same elements and using the same ordering as the specified sorted
set.

Methods Summary
Methods

CSE, KSIT, 2019-20 Page 44


Advanced Java & J2EE (17CS553) Study Material

Modifier and Type Method and Description

add(E e)
boolean
Adds the specified element to this set if it is not already present.

addAll(Collection<? extends E> c)


boolean
Adds all of the elements in the specified collection to this set.

ceiling(E e)
E Returns the least element in this set greater than or equal to the given element, or null
if there is no such element.

clear()
void
Removes all of the elements from this set.

clone()
Object
Returns a shallow copy of this TreeSet instance.

comparator()
Comparator<? super
E> Returns the comparator used to order the elements in this set, or null if this set uses
the natural ordering of its elements.

contains(Object o)
boolean
Returns true if this set contains the specified element.

descendingIterator()
Iterator<E>
Returns an iterator over the elements in this set in descending order.

descendingSet()
NavigableSet<E>
Returns a reverse order view of the elements contained in this set.

first()
E
Returns the first (lowest) element currently in this set.

floor(E e)
E
Returns the greatest element in this set less than or equal to the given element, or null

CSE, KSIT, 2019-20 Page 45


Advanced Java & J2EE (17CS553) Study Material

if there is no such element.

headSet(E toElement)
SortedSet<E> Returns a view of the portion of this set whose elements are strictly less than
toElement.

headSet(E toElement, boolean inclusive)


NavigableSet<E> Returns a view of the portion of this set whose elements are less than (or equal to, if
inclusive is true) toElement.

higher(E e)
E Returns the least element in this set strictly greater than the given element, or null if
there is no such element.

isEmpty()
boolean
Returns true if this set contains no elements.

iterator()
Iterator<E>
Returns an iterator over the elements in this set in ascending order.

last()
E
Returns the last (highest) element currently in this set.

lower(E e)
E Returns the greatest element in this set strictly less than the given element, or null if
there is no such element.

pollFirst()
E
Retrieves and removes the first (lowest) element, or returns null if this set is empty.

pollLast()
E
Retrieves and removes the last (highest) element, or returns null if this set is empty.

remove(Object o)
boolean
Removes the specified element from this set if it is present.

int size()

CSE, KSIT, 2019-20 Page 46


Advanced Java & J2EE (17CS553) Study Material

Returns the number of elements in this set (its cardinality).

subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)


NavigableSet<E> Returns a view of the portion of this set whose elements range from fromElement to
toElement.

subSet(E fromElement, E toElement)


SortedSet<E> Returns a view of the portion of this set whose elements range from fromElement,
inclusive, to toElement, exclusive.

tailSet(E fromElement)
SortedSet<E> Returns a view of the portion of this set whose elements are greater than or equal to
fromElement.

tailSet(E fromElement, boolean inclusive)


NavigableSet<E> Returns a view of the portion of this set whose elements are greater than (or equal to,
if inclusive is true) fromElement.

Example Program
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet<String> ts=new TreeSet<String>();
//Add elements to the tree set
ts.add("E");
ts.add("A");
ts.add("F");
ts.add("C");
ts.add("D");
ts.add("B");

System.out.println(ts);

//subSet() of Navigatable
System.out.println(ts.subSet("C","F"));
}
}
The program output is shown here:

[A, B, C, D, E, F]
[C, D, E]

CSE, KSIT, 2019-20 Page 47


Advanced Java & J2EE (17CS553) Study Material

The PriorityQueue Class


public class PriorityQueue<E>
extends AbstractQueue<E>
implements Serializable

It creates a queue that is prioritized based on the queue‘s comparator.

An unbounded priority queue based on a priority heap.

The elements of the priority queue are ordered according to their natural ordering, or by a
Comparator provided at queue construction time, depending on which constructor is used.

A priority queue does not permit null elements.

A priority queue relying on natural ordering also does not permit insertion of non-comparable objects
(doing so may result in ClassCastException).

The head of this queue is the least element with respect to the specified ordering. If multiple elements are
tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval
operations poll, remove, peek, and element access the element at the head of the queue.

A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the
elements on the queue. It is always at least as large as the queue size. As elements are added to a priority
queue, its capacity grows automatically. The details of the growth policy are not specified.

Constructors Summary
Constructors

Constructor and Description

PriorityQueue()

Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their
natural ordering.

PriorityQueue(Collection<? extends E> c)

Creates a PriorityQueue containing the elements in the specified collection.

PriorityQueue(int initialCapacity)

Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural
ordering.

CSE, KSIT, 2019-20 Page 48


Advanced Java & J2EE (17CS553) Study Material

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)

Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified
comparator.

PriorityQueue(PriorityQueue<? extends E> c)

Creates a PriorityQueue containing the elements in the specified priority queue.

PriorityQueue(SortedSet<? extends E> c)

Creates a PriorityQueue containing the elements in the specified sorted set.

Methods Summary
Methods

Modifier and
Method and Description
Type

add(E e)
boolean
Inserts the specified element into this priority queue.

clear()
void
Removes all of the elements from this priority queue.

comparator()
Comparator<?
super E> Returns the comparator used to order the elements in this queue, or null if this queue is
sorted according to the natural ordering of its elements.

contains(Object o)
boolean
Returns true if this queue contains the specified element.

iterator()
Iterator<E>
Returns an iterator over the elements in this queue.

offer(E e)
boolean
Inserts the specified element into this priority queue.

CSE, KSIT, 2019-20 Page 49


Advanced Java & J2EE (17CS553) Study Material

peek()
E Retrieves, but does not remove, the head of this queue, or returns null if this queue is
empty.

poll()
E
Retrieves and removes the head of this queue, or returns null if this queue is empty.

remove(Object o)
boolean
Removes a single instance of the specified element from this queue, if it is present.

size()
int
Returns the number of elements in this collection.

toArray()
Object[]
Returns an array containing all of the elements in this queue.

toArray(T[] a)
<T> T[] Returns an array containing all of the elements in this queue; the runtime type of the
returned array is that of the specified array.

The ArrayDeque Class


public class ArrayDeque<E>
extends AbstractCollection<E>
implements Deque<E>, Cloneable, Serializable

This class has no methods of its own.


This class creates a dynamic array and has no capacity restrictions.
This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when
used as a queue.

Constructors Summary
Constructors

Constructor and Description

ArrayDeque()

CSE, KSIT, 2019-20 Page 50


Advanced Java & J2EE (17CS553) Study Material

Constructs an empty array deque with an initial capacity sufficient to hold 16 elements.

ArrayDeque(Collection<? extends E> c)

Constructs a deque containing the elements of the specified collection, in the order they are returned by the
collection's iterator.

ArrayDeque(int numElements)

Constructs an empty array deque with an initial capacity sufficient to hold the specified number of elements.

Program Example:

import java.util.*;
class ArrayDequeDemo
{
public static void main(String[] args)
{
// Create a tree set
ArrayDeque<String> adq=new ArrayDeque<String>();

//Use an ArrayDeque like a stack


adq.push("A");
adq.push("B");
adq.push("C");
adq.push("D");
adq.push("E");
adq.push("F");
System.out.println("ArrayDeque stack contents:\n"+adq);
System.out.println("Popping the stack");
while(adq.peek()!=null)
System.out.print(adq.pop()+" ");
}
}

The program output is shown here:

ArrayDeque stack contents:


[F, E, D, C, B, A]
Popping the stack
FEDCBA

Class EnumSet<E extends Enum<E>>


public abstract class EnumSet<E extends Enum<E>>
extends AbstractSet<E>
implements Cloneable, Serializable

CSE, KSIT, 2019-20 Page 51


Advanced Java & J2EE (17CS553) Study Material

Method Summary
Methods

Modifier and Type Method and Description

static <E extends allOf(Class<E> elementType)


Enum<E>>
EnumSet<E> Creates an enum set containing all of the elements in the specified element type.

clone()
EnumSet<E>
Returns a copy of this set.

static <E extends complementOf(EnumSet<E> s)


Enum<E>> Creates an enum set with the same element type as the specified enum set, initially
EnumSet<E> containing all the elements of this type that are not contained in the specified set.

static <E extends copyOf(Collection<E> c)


Enum<E>>
EnumSet<E> Creates an enum set initialized from the specified collection.

static <E extends copyOf(EnumSet<E> s)


Enum<E>> Creates an enum set with the same element type as the specified enum set, initially
EnumSet<E> containing the same elements (if any).

static <E extends noneOf(Class<E> elementType)


Enum<E>>
EnumSet<E> Creates an empty enum set with the specified element type.

static <E extends of(E e)


Enum<E>>
EnumSet<E> Creates an enum set initially containing the specified element.

static <E extends of(E first, E... rest)


Enum<E>>
EnumSet<E> Creates an enum set initially containing the specified elements.

static <E extends of(E e1, E e2)


Enum<E>>
EnumSet<E> Creates an enum set initially containing the specified elements.

CSE, KSIT, 2019-20 Page 52


Advanced Java & J2EE (17CS553) Study Material

static <E extends of(E e1, E e2, E e3)


Enum<E>>
EnumSet<E> Creates an enum set initially containing the specified elements.

static <E extends of(E e1, E e2, E e3, E e4)


Enum<E>>
EnumSet<E> Creates an enum set initially containing the specified elements.

static <E extends of(E e1, E e2, E e3, E e4, E e5)


Enum<E>>
EnumSet<E> Creates an enum set initially containing the specified elements.

static <E extends range(E from, E to)


Enum<E>> Creates an enum set initially containing all of the elements in the range defined by the
EnumSet<E> two specified endpoints.

Accessing a Collection via an Iterator


To cycle through the elements in a collection is to employ an iterator which is an object that implements
either Interfaces : Iterator or the ListIterator

Interface Iterator<E>
Type Parameters:
E - the type of elements returned by this iterator

All Known Subinterfaces:

ListIterator<E>, XMLEventReader

All Known Implementing Classes:

BeanContextSupport.BCSIterator, EventReaderDelegate, Scanner

public interface Iterator<E>

Method Summary
Methods

Modifier and
Method and Description
Type

CSE, KSIT, 2019-20 Page 53


Advanced Java & J2EE (17CS553) Study Material

hasNext()
boolean
Returns true if the iteration has more elements.

next()
E
Returns the next element in the iteration.

remove()
void Removes from the underlying collection the last element returned by this iterator
(optional operation).

Interface ListIterator<E>
public interface ListIterator<E>
extends Iterator<E>

Method Summary
Methods

Modifier and
Method and Description
Type

add(E e)
void
Inserts the specified element into the list (optional operation).

hasNext()
boolean Returns true if this list iterator has more elements when traversing the list in the forward
direction.

hasPrevious()
boolean Returns true if this list iterator has more elements when traversing the list in the reverse
direction.

next()
E
Returns the next element in the list and advances the cursor position.

nextIndex()
int
Returns the index of the element that would be returned by a subsequent call to next().

CSE, KSIT, 2019-20 Page 54


Advanced Java & J2EE (17CS553) Study Material

previous()
E
Returns the previous element in the list and moves the cursor position backwards.

previousIndex()
int Returns the index of the element that would be returned by a subsequent call to
previous().

remove()
void Removes from the list the last element that was returned by next() or previous() (optional
operation).

set(E e)
void Replaces the last element returned by next() or previous() with the specified element
(optional operation).

Example program:
import java.util.*;
class IteratorDemo
{
public static void main(String[] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
al.add("F");
System.out.print("Original Contents of al: ");
Iterator<String> itr=al.iterator();
while(itr.hasNext())
System.out.print(itr.next()+" ");
System.out.println();
//Modify list
ListIterator<String> litr=al.listIterator();
while(litr.hasNext())
{
String s=litr.next();
litr.set(s+"+");

}
//display list
litr=al.listIterator();

CSE, KSIT, 2019-20 Page 55


Advanced Java & J2EE (17CS553) Study Material

System.out.print("Modified Contents of al: ");


while(litr.hasNext())
System.out.print(litr.next()+" ");
System.out.println();
//display list backward
//litr=al.listIterator();
System.out.print("Modified list backwards: ");
while(litr.hasPrevious())
System.out.print(litr.previous()+" ");
System.out.println();
}
}
The output of the program is shown here:
Original Contents of al: A B C D E F
Modified Contents of al: A+ B+ C+ D+ E+ F+
Modified list backwards: F+ E+ D+ C+ B+ A+

The For-Each alternate to Iterators


If there is no modification to the contents of a collection or obtaining elements in reverse order then
for-each version of the for loop is very convenient alternative to cycle through a collection that uses
an iterators.
The for-each can cycle through any collections of objects that implements the iterable interface.
Example program:
import java.util.*;
class ForEachDemo
{
public static void main(String[] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
al.add("F");
System.out.print("Contents of al: ");
/*Iterator<String> itr=al.iterator();
while(itr.hasNext())
System.out.print(itr.next()+" ");
System.out.println();
*/
for(String s:al)
System.out.print(s+" ");
System.out.println();
}
}
The output of the program is shown here:
Contents of al: A B C D E F

CSE, KSIT, 2019-20 Page 56


Advanced Java & J2EE (17CS553) Study Material

Storing User-Defined Classes in Collections


Collections can store any type of objects i.e. like built-in objects or user defined objects.
Example Program

import java.util.*;
class Student
{
String name;
String usn;
String addr;
Student(String n,String u,String a)
{
name=n;
usn=u;
addr=a;
}
public String toString()
{
return name+"\n"+usn+"\n"+addr+"\n";
}
}
class StudAddr
{
public static void main(String args[])
{
LinkedList<Student> std=new LinkedList<Student>();
std.add(new Student("HJR","007","BLR"));
std.add(new Student("SMS","008","KAR"));
std.add(new Student("HJH","009","BHARATH"));
System.out.println("Display address list");
for(Student a:std)
System.out.println(a);
}
}
The output of the program is shown here:
Display address list
HJR
007
BLR

SMS
008
KAR

HJH
009
BHARATH

Working with Maps


CSE, KSIT, 2019-20 Page 57
Advanced Java & J2EE (17CS553) Study Material

A map is an object that stores associations between keys and values, or key/value pairs.
Given a key, its value can be found.
Both keys and values are objects.
The keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, others cannot.
Maps don‘t implement Iterable i.e. for-each cannot be used to cycle through a map.
Maps supports collection-view of a map, which does allow the use of either the for-each loop or an
iterator.

The Map interfaces:


Interface Description
Map Maps unique keys to values.
Map.Entry Describes an element (a key/value pair) in a map. This is an inner-class of
Map.
NavigableMap Extends SortedMap to handle the retrieval of entries based on the closest-
match searches.
SortedMap Extends Map so that the keys are maintained in ascending orde.

The Map Classes:


Classes Description
AbstractMap Implements most of the Map interface.
EnumMap Extends AbstractMap for use with enum keys.
HashMap Extends AbstractMap to use a hash table.
TreeMap Extends AbstractMap to use a tree.
WeakHashMap Extends AbstractMap to use a hash table with
weak keys.
LinkedHashMap Extends HashMap to allow insertion-order
iterations.
IdentityHashMap Extends AbstractMap and uses reference
equality when comparing documents.

The Map Interfaces

Interface Map<K,V>
Type Parameters:
K - the type of keys maintained by this map

V - the type of mapped values

public interface Map<K,V>

An object that maps keys to values.


A map cannot contain duplicate keys; each key can map to at most one value.

This interface takes the place of the Dictionary class, which was a totally abstract class rather than an
interface.

CSE, KSIT, 2019-20 Page 58


Advanced Java & J2EE (17CS553) Study Material

The Map interface provides three collection views, which allow a map's contents to be viewed as
o a set of keys,
o collection of values, or
o set of key-value mappings.
The order of a map is defined as the order in which the iterators on the map's collection views return
their elements.
Some map implementations, like the TreeMap class, make specific guarantees as to their order; others,
like the HashMap class, do not.

Nested Class Summary

Nested Classes

Modifier and Type Interface and Description

Map.Entry<K,V>
static interface
A map entry (key-value pair).

Method Summary

Methods

Modifier and Type Method and Description

clear()
void
Removes all of the mappings from this map (optional operation).

containsKey(Object key)
boolean
Returns true if this map contains a mapping for the specified key.

containsValue(Object value)
boolean
Returns true if this map maps one or more keys to the specified value.

entrySet()
Set<Map.Entry<K,V>>
Returns a Set view of the mappings contained in this map.

equals(Object o)
boolean
Compares the specified object with this map for equality.

get(Object key)
V
Returns the value to which the specified key is mapped, or null if this map contains no

CSE, KSIT, 2019-20 Page 59


Advanced Java & J2EE (17CS553) Study Material

mapping for the key.

hashCode()
int
Returns the hash code value for this map.

isEmpty()
boolean
Returns true if this map contains no key-value mappings.

keySet()
Set<K>
Returns a Set view of the keys contained in this map.

put(K key, V value)


V
Associates the specified value with the specified key in this map (optional operation).

putAll(Map<? extends K,? extends V> m)


void
Copies all of the mappings from the specified map to this map (optional operation).

remove(Object key)
V
Removes the mapping for a key from this map if it is present (optional operation).

size()
int
Returns the number of key-value mappings in this map.

values()
Collection<V>
Returns a Collection view of the values contained in this map.

Interface SortedMap<K,V>
Type Parameters:
K - the type of keys maintained by this map

V - the type of mapped values

All Superinterfaces:

Map<K,V>

All Known Subinterfaces:

CSE, KSIT, 2019-20 Page 60


Advanced Java & J2EE (17CS553) Study Material

ConcurrentNavigableMap<K,V>, NavigableMap<K,V>

All Known Implementing Classes:

ConcurrentSkipListMap, TreeMap

The SortedMap interface extends Map.


This interface ensures that the entries are maintained in ascending order based on keys.

The general form is:

public interface SortedMap<K,V>


extends Map<K,V>

Nested Class Summary


o Nested classes/interfaces inherited from interface java.util.Map

Map.Entry<K,V>

Method Summary

Methods

Modifier and Type Method and Description

comparator()
Comparator<? super
K> Returns the comparator used to order the keys in this map, or null if this map uses the
natural ordering of its keys.

entrySet()
Set<Map.Entry<K,V>>
Returns a Set view of the mappings contained in this map.

firstKey()
K
Returns the first (lowest) key currently in this map.

headMap(K toKey)
SortedMap<K,V>
Returns a view of the portion of this map whose keys are strictly less than toKey.

keySet()
Set<K>
Returns a Set view of the keys contained in this map.

K lastKey()

CSE, KSIT, 2019-20 Page 61


Advanced Java & J2EE (17CS553) Study Material

Returns the last (highest) key currently in this map.

subMap(K fromKey, K toKey)


SortedMap<K,V> Returns a view of the portion of this map whose keys range from fromKey, inclusive,
to toKey, exclusive.

tailMap(K fromKey)
SortedMap<K,V> Returns a view of the portion of this map whose keys are greater than or equal to
fromKey.

values()
Collection<V>
Returns a Collection view of the values contained in this map.

The Map.Entry interface

Interface Map.Entry<K,V>
All Known Implementing Classes:
AbstractMap.SimpleEntry, AbstractMap.SimpleImmutableEntry

Enclosing interface:

Map<K,V>

General form:
public static interface Map.Entry<K,V>

A map entry (key-value pair).

The Map.entrySet method returns a collection-view of the map, whose elements are of this class.
The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry
objects are valid only for the duration of the iteration;

Method Summary
Methods

Modifier and Type Method and Description

equals(Object o)
boolean
Compares the specified object with this entry for equality.

getKey()
K
Returns the key corresponding to this entry.

CSE, KSIT, 2019-20 Page 62


Advanced Java & J2EE (17CS553) Study Material

getValue()
V
Returns the value corresponding to this entry.

hashCode()
int
Returns the hash code value for this map entry.

setValue(V value)
V
Replaces the value corresponding to this entry with the specified value (optional operation).

The Map Classes

Class HashMap<K,V>
java.lang.Object

o java.util.AbstractMap<K,V>
o
 java.util.HashMap<K,V>

Type Parameters:
K - the type of keys maintained by this map

V - the type of mapped values

All Implemented Interfaces:

Serializable, Cloneable, Map<K,V>

Direct Known Subclasses:

LinkedHashMap, PrinterStateReasons

The General form is:

public class HashMap<K,V>


extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

Hash table based implementation of the Map interface.

This implementation provides all of the optional map operations, and permits null values and
the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is
unsynchronized and permits nulls.)

CSE, KSIT, 2019-20 Page 63


Advanced Java & J2EE (17CS553) Study Material

This class makes no guarantees as to the order of the map; in particular, it does not guarantee
that the order will remain constant over time.

Nested Class Summary


o Nested classes/interfaces inherited from class java.util.AbstractMap

AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>

Constructor Summary

Constructors

Constructor and Description

HashMap()

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).

HashMap(int initialCapacity)

Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).

HashMap(int initialCapacity, float loadFactor)

Constructs an empty HashMap with the specified initial capacity and load factor.

HashMap(Map<? extends K,? extends V> m)

Constructs a new HashMap with the same mappings as the specified Map.

Method Summary

Methods

Modifier and Type Method and Description

clear()
void
Removes all of the mappings from this map.

clone()
Object Returns a shallow copy of this HashMap instance: the keys and values themselves are
not cloned.

containsKey(Object key)
boolean
Returns true if this map contains a mapping for the specified key.

CSE, KSIT, 2019-20 Page 64


Advanced Java & J2EE (17CS553) Study Material

containsValue(Object value)
boolean
Returns true if this map maps one or more keys to the specified value.

entrySet()
Set<Map.Entry<K,V>>
Returns a Set view of the mappings contained in this map.

get(Object key)
V Returns the value to which the specified key is mapped, or null if this map contains no
mapping for the key.

isEmpty()
boolean
Returns true if this map contains no key-value mappings.

keySet()
Set<K>
Returns a Set view of the keys contained in this map.

put(K key, V value)


V
Associates the specified value with the specified key in this map.

putAll(Map<? extends K,? extends V> m)


void
Copies all of the mappings from the specified map to this map.

remove(Object key)
V
Removes the mapping for the specified key from this map if present.

size()
int
Returns the number of key-value mappings in this map.

values()
Collection<V>
Returns a Collection view of the values contained in this map.

Example Program:

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

CSE, KSIT, 2019-20 Page 65


Advanced Java & J2EE (17CS553) Study Material

//Create a hash map


HashMap<String,Double> hp=new HashMap<String,Double>();
//Put elements to the map
hp.put("HJR",new Double(99.99));
hp.put("SMS",new Double(999.99));
hp.put("HJH",new Double(9999.99));
//Get a set of the entries
Set<Map.Entry<String,Double>> set=hp.entrySet();
//Display the set
for(Map.Entry<String,Double> me: set)
{
System.out.println("Name: "+me.getKey());
System.out.println("Bal: "+me.getValue());
}
//Deposit 999 to HJH
Double bal=hp.get("HJH");
hp.put("HJH",bal+999);
System.out.println("HJH's new balance: "+hp.get("HJH"));
}
}

The output of the program is here:


Name: HJH
Bal: 9999.99
Name: HJR
Bal: 99.99
Name: SMS
Bal: 999.99
HJH's new balance: 10998.99

Class TreeMap<K,V>

java.lang.Object

o java.util.AbstractMap<K,V>
o
 java.util.TreeMap<K,V>

Type Parameters:
K - the type of keys maintained by this map

V - the type of mapped values

All Implemented Interfaces:

Serializable, Cloneable, Map<K,V>, NavigableMap<K,V>, SortedMap<K,V>

The general form is:

public class TreeMap<K,V>


extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable

A Red-Black tree based NavigableMap implementation.

CSE, KSIT, 2019-20 Page 66


Advanced Java & J2EE (17CS553) Study Material

It creates maps stored in a tree structure.


This class provides an efficient means of storing key/value pairs in sorted order and allows rapid
retrieval.
The map is sorted according to the natural ordering of its keys.

Nested Class Summary


o Nested classes/interfaces inherited from class java.util.AbstractMap

AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>

Constructor Summary

Constructors

Constructor and Description

TreeMap()

Constructs a new, empty tree map, using the natural ordering of its keys.

TreeMap(Comparator<? super K> comparator)

Constructs a new, empty tree map, ordered according to the given comparator.

TreeMap(Map<? extends K,? extends V> m)

Constructs a new tree map containing the same mappings as the given map, ordered according to the natural
ordering of its keys.

TreeMap(SortedMap<K,? extends V> m)

Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted
map.

Method Summary

Methods

Modifier and Type Method and Description

ceilingEntry(K key)
Map.Entry<K,V> Returns a key-value mapping associated with the least key greater than or equal to the
given key, or null if there is no such key.

ceilingKey(K key)
K
Returns the least key greater than or equal to the given key, or null if there is no such

CSE, KSIT, 2019-20 Page 67


Advanced Java & J2EE (17CS553) Study Material

key.

clear()
void
Removes all of the mappings from this map.

clone()
Object
Returns a shallow copy of this TreeMap instance.

comparator()
Comparator<? super
K> Returns the comparator used to order the keys in this map, or null if this map uses the
natural ordering of its keys.

containsKey(Object key)
boolean
Returns true if this map contains a mapping for the specified key.

containsValue(Object value)
boolean
Returns true if this map maps one or more keys to the specified value.

descendingKeySet()
NavigableSet<K>
Returns a reverse order NavigableSet view of the keys contained in this map.

descendingMap()
NavigableMap<K,V>
Returns a reverse order view of the mappings contained in this map.

entrySet()
Set<Map.Entry<K,V>>
Returns a Set view of the mappings contained in this map.

firstEntry()
Map.Entry<K,V> Returns a key-value mapping associated with the least key in this map, or null if the
map is empty.

firstKey()
K
Returns the first (lowest) key currently in this map.

floorEntry(K key)
Map.Entry<K,V> Returns a key-value mapping associated with the greatest key less than or equal to the
given key, or null if there is no such key.

CSE, KSIT, 2019-20 Page 68


Advanced Java & J2EE (17CS553) Study Material

floorKey(K key)
K Returns the greatest key less than or equal to the given key, or null if there is no such
key.

get(Object key)
V Returns the value to which the specified key is mapped, or null if this map contains no
mapping for the key.

headMap(K toKey)
SortedMap<K,V>
Returns a view of the portion of this map whose keys are strictly less than toKey.

headMap(K toKey, boolean inclusive)


NavigableMap<K,V> Returns a view of the portion of this map whose keys are less than (or equal to, if
inclusive is true) toKey.

higherEntry(K key)
Map.Entry<K,V> Returns a key-value mapping associated with the least key strictly greater than the
given key, or null if there is no such key.

higherKey(K key)
K
Returns the least key strictly greater than the given key, or null if there is no such key.

keySet()
Set<K>
Returns a Set view of the keys contained in this map.

lastEntry()
Map.Entry<K,V> Returns a key-value mapping associated with the greatest key in this map, or null if
the map is empty.

lastKey()
K
Returns the last (highest) key currently in this map.

lowerEntry(K key)
Map.Entry<K,V> Returns a key-value mapping associated with the greatest key strictly less than the
given key, or null if there is no such key.

lowerKey(K key)
K
Returns the greatest key strictly less than the given key, or null if there is no such key.

CSE, KSIT, 2019-20 Page 69


Advanced Java & J2EE (17CS553) Study Material

navigableKeySet()
NavigableSet<K>
Returns a NavigableSet view of the keys contained in this map.

pollFirstEntry()
Map.Entry<K,V> Removes and returns a key-value mapping associated with the least key in this map,
or null if the map is empty.

pollLastEntry()
Map.Entry<K,V> Removes and returns a key-value mapping associated with the greatest key in this
map, or null if the map is empty.

put(K key, V value)


V
Associates the specified value with the specified key in this map.

putAll(Map<? extends K,? extends V> map)


void
Copies all of the mappings from the specified map to this map.

remove(Object key)
V
Removes the mapping for this key from this TreeMap if present.

size()
int
Returns the number of key-value mappings in this map.

subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)


NavigableMap<K,V>
Returns a view of the portion of this map whose keys range from fromKey to toKey.

subMap(K fromKey, K toKey)


SortedMap<K,V> Returns a view of the portion of this map whose keys range from fromKey, inclusive,
to toKey, exclusive.

tailMap(K fromKey)
SortedMap<K,V> Returns a view of the portion of this map whose keys are greater than or equal to
fromKey.

tailMap(K fromKey, boolean inclusive)


NavigableMap<K,V> Returns a view of the portion of this map whose keys are greater than (or equal to, if
inclusive is true) fromKey.

CSE, KSIT, 2019-20 Page 70


Advanced Java & J2EE (17CS553) Study Material

values()
Collection<V>
Returns a Collection view of the values contained in this map.

Example Program:

import java.util.*;
class TreeMapDemo
{
public static void main(String[] args)
{
//Create a hash map
TreeMap<String,Double> tm=new TreeMap<String,Double>();
//Put elements to the map
tm.put("HJR",new Double(99.99));
tm.put("SMS",new Double(999.99));
tm.put("HJH",new Double(9999.99));
//Get a set of the entries
Set<Map.Entry<String,Double>> set=tm.entrySet();
//Display the set
for(Map.Entry<String,Double> me: set)
{
System.out.println("Name: "+me.getKey());
System.out.println("Bal: "+me.getValue());
}
//Deposit 999 to HJH
Double bal=tm.get("HJH");
tm.put("HJH",bal+999);
System.out.println("HJH's new balance: "+tm.get("HJH"));
}
}
The program output is shown here:
Name: HJH
Bal: 9999.99
Name: HJR
Bal: 99.99
Name: SMS
Bal: 999.99
HJH's new balance: 10998.99

Class LinkedHashMap<K,V>

java.lang.Object

o java.util.AbstractMap<K,V>
o
 java.util.HashMap<K,V>

 java.util.LinkedHashMap<K,V>

Type Parameters:
K - the type of keys maintained by this map

CSE, KSIT, 2019-20 Page 71


Advanced Java & J2EE (17CS553) Study Material

V - the type of mapped values

All Implemented Interfaces:

Serializable, Cloneable, Map<K,V>

The general form is:

public class LinkedHashMap<K,V>


extends HashMap<K,V>
implements Map<K,V>

Hash table and linked list implementation of the Map interface, with predictable iteration order.

This implementation differs from HashMap in that it maintains a doubly-linked list running
through all of its entries.
This linked list defines the iteration ordering, which is normally the order in which keys were
inserted into the map (insertion-order).

Nested Class Summary


o Nested classes/interfaces inherited from class java.util.AbstractMap

AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>

Constructor Summary

Constructors

Constructor and Description

LinkedHashMap()

Constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load
factor (0.75).

LinkedHashMap(int initialCapacity)

Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and a default
load factor (0.75).

LinkedHashMap(int initialCapacity, float loadFactor)

Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and load
factor.

LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)

Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering
mode.

CSE, KSIT, 2019-20 Page 72


Advanced Java & J2EE (17CS553) Study Material

LinkedHashMap(Map<? extends K,? extends V> m)

Constructs an insertion-ordered LinkedHashMap instance with the same mappings as the specified map.

Method Summary

Methods

Modifier and
Method and Description
Type

clear()
void
Removes all of the mappings from this map.

containsValue(Object value)
boolean
Returns true if this map maps one or more keys to the specified value.

get(Object key)
V Returns the value to which the specified key is mapped, or null if this map contains no
mapping for the key.

removeEldestEntry(Map.Entry<K,V> eldest)
protected boolean
Returns true if this map should remove its eldest entry.

Class EnumMap<K extends Enum<K>,V>

java.lang.Object

o java.util.AbstractMap<K,V>
o
 java.util.EnumMap<K,V>

All Implemented Interfaces:


Serializable, Cloneable, Map<K,V>

The general form is:

public class EnumMap<K extends Enum<K>,V>


extends AbstractMap<K,V>
implements Serializable, Cloneable

A specialized Map implementation for use with enum type keys.

CSE, KSIT, 2019-20 Page 73


Advanced Java & J2EE (17CS553) Study Material

All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly,
when the map is created. Enum maps are represented internally as arrays. This representation is extremely
compact and efficient.

Enum maps are maintained in the natural order of their keys (the order in which the enum constants
are declared).

Null keys are not permitted. Attempts to insert a null key will throw NullPointerException. Attempts to
test for the presence of a null key or to remove one will, however, function properly. Null values are
permitted.

Nested Class Summary


o Nested classes/interfaces inherited from class java.util.AbstractMap

AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>

o Nested classes/interfaces inherited from interface java.util.Map

Map.Entry<K,V>

Constructor Summary

Constructors

Constructor and Description

EnumMap(Class<K> keyType)

Creates an empty enum map with the specified key type.

EnumMap(EnumMap<K,? extends V> m)

Creates an enum map with the same key type as the specified enum map, initially containing the same
mappings (if any).

EnumMap(Map<K,? extends V> m)

Creates an enum map initialized from the specified map.

Method Summary

Methods

Modifier and Type Method and Description

void clear()

CSE, KSIT, 2019-20 Page 74


Advanced Java & J2EE (17CS553) Study Material

Removes all mappings from this map.

clone()
EnumMap<K,V>
Returns a shallow copy of this enum map.

containsKey(Object key)
boolean
Returns true if this map contains a mapping for the specified key.

containsValue(Object value)
boolean
Returns true if this map maps one or more keys to the specified value.

entrySet()
Set<Map.Entry<K,V>>
Returns a Set view of the mappings contained in this map.

equals(Object o)
boolean
Compares the specified object with this map for equality.

get(Object key)
V Returns the value to which the specified key is mapped, or null if this map contains no
mapping for the key.

hashCode()
int
Returns the hash code value for this map.

keySet()
Set<K>
Returns a Set view of the keys contained in this map.

put(K key, V value)


V
Associates the specified value with the specified key in this map.

putAll(Map<? extends K,? extends V> m)


void
Copies all of the mappings from the specified map to this map.

remove(Object key)
V
Removes the mapping for this key from this map if present.

int size()

CSE, KSIT, 2019-20 Page 75


Advanced Java & J2EE (17CS553) Study Material

Returns the number of key-value mappings in this map.

values()
Collection<V>
Returns a Collection view of the values contained in this map.

Comparators

Interface Comparator<T>
Type Parameters:
T - the type of objects that may be compared by this comparator

All Known Implementing Classes:

Collator, RuleBasedCollator

The general form is:

public interface Comparator<T>

A comparison function, which imposes a total ordering on some collection of objects.

Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines
precisely what ―sorted order‖ means.
By default, these classes store their elements by using Java refers to as ―natural ordering‖. To have
different ordering specify Comparator when set or map is constructed.

Method Summary
Methods

Modifier and Type Method and Description

compare(T o1, T o2)


int
Compares its two arguments for order.

equals(Object obj)
boolean
Indicates whether some other object is "equal to" this comparator.

Program Example:

import java.util.*;
class MyComp implements Comparator<String>
{
public int compare(String a,String b)
CSE, KSIT, 2019-20 Page 76
Advanced Java & J2EE (17CS553) Study Material

{
String aStr,bStr;
aStr=a;
bStr=b;
return bStr.compareTo(aStr);
}
}
class ComparatorDemo
{
public static void main(String[] args)
{
TreeSet<String> ts=new TreeSet<String>(new MyComp());

ts.add("A");
ts.add("B");
ts.add("C");
ts.add("D");

for(String s:ts)
System.out.print(s+" ");
System.out.println();

}
}

The out put of the program is shown here:


DCBA

Example Program 2: Comparator is used to compare last name


import java.util.*;
class TComp implements Comparator<String>
{
public int compare(String a,String b)
{
int i,j,k;
String aStr,bStr;
aStr=a;
bStr=b;

i=aStr.lastIndexOf(' ');
j=bStr.lastIndexOf(' ');

k=aStr.substring(i).compareTo(bStr.substring(j));
if(k==0)
return aStr.compareTo(bStr);
else
return k;

}
}
class TreeMapDemo2
{
public static void main(String[] args)
{
TreeMap<String,Double> tm=new TreeMap<String,Double>(new TComp());

CSE, KSIT, 2019-20 Page 77


Advanced Java & J2EE (17CS553) Study Material

tm.put("Harshavardhan J.R",new Double(99.99));


tm.put("Sudha S.M",new Double(999.99));
tm.put("Hariharan J.H",new Double(9999.99));

Set<Map.Entry<String,Double>> set=tm.entrySet();
for(Map.Entry me: set)
System.out.println("Name: "+me.getKey()+" Balance: "+me.getValue());
//Deposit 999 to HJH
double bal=tm.get("Hariharan J.H");
tm.put("Hariharan J.H",bal+999);
System.out.println("Hariharan J.H's new balance: "+tm.get("Hariharan J.H"));

}
}

/*
The output of the program is shown here:
Name: Hariharan J.H Balance: 9999.99
Name: Harshavardhan J.R Balance: 99.99
Name: Sudha S.M Balance: 999.99
Hariharan J.H's new balance: 10998.99
*/

The Algorithms defined by Collections


Field Summary

Fields
Modifier and Type Field and Description
EMPTY_LIST
static List
The empty list (immutable).
EMPTY_MAP
static Map
The empty map (immutable).
EMPTY_SET
static Set
The empty set (immutable).

Method Summary

Methods
Modifier and Type Method and Description
addAll(Collection<? super T> c, T... elements)
static <T> boolean
Adds all of the specified elements to the specified collection.
asLifoQueue(Deque<T> deque)
static <T> Queue<T>
Returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
binarySearch(List<? extends Comparable<? super T>> list, T key)
static <T> int Searches the specified list for the specified object using the binary search
algorithm.

CSE, KSIT, 2019-20 Page 78


Advanced Java & J2EE (17CS553) Study Material

binarySearch(List<? extends T> list, T key, Comparator<? super T> c)


static <T> int Searches the specified list for the specified object using the binary search
algorithm.
checkedCollection(Collection<E> c, Class<E> type)
static <E> Collection<E>
Returns a dynamically typesafe view of the specified collection.
checkedList(List<E> list, Class<E> type)
static <E> List<E>
Returns a dynamically typesafe view of the specified list.
checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)
static <K,V> Map<K,V>
Returns a dynamically typesafe view of the specified map.
checkedSet(Set<E> s, Class<E> type)
static <E> Set<E>
Returns a dynamically typesafe view of the specified set.
checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)
static <K,V> SortedMap<K,V>
Returns a dynamically typesafe view of the specified sorted map.
checkedSortedSet(SortedSet<E> s, Class<E> type)
static <E> SortedSet<E>
Returns a dynamically typesafe view of the specified sorted set.
copy(List<? super T> dest, List<? extends T> src)
static <T> void
Copies all of the elements from one list into another.
disjoint(Collection<?> c1, Collection<?> c2)
static boolean
Returns true if the two specified collections have no elements in common.
emptyEnumeration()
static <T> Enumeration<T>
Returns an enumeration that has no elements.
emptyIterator()
static <T> Iterator<T>
Returns an iterator that has no elements.
emptyList()
static <T> List<T>
Returns the empty list (immutable).
emptyListIterator()
static <T> ListIterator<T>
Returns a list iterator that has no elements.
emptyMap()
static <K,V> Map<K,V>
Returns the empty map (immutable).
emptySet()
static <T> Set<T>
Returns the empty set (immutable).
enumeration(Collection<T> c)
static <T> Enumeration<T>
Returns an enumeration over the specified collection.
fill(List<? super T> list, T obj)
static <T> void
Replaces all of the elements of the specified list with the specified element.
frequency(Collection<?> c, Object o)
static int Returns the number of elements in the specified collection equal to the
specified object.
indexOfSubList(List<?> source, List<?> target)
static int Returns the starting position of the first occurrence of the specified target list
within the specified source list, or -1 if there is no such occurrence.
lastIndexOfSubList(List<?> source, List<?> target)
static int Returns the starting position of the last occurrence of the specified target list
within the specified source list, or -1 if there is no such occurrence.
static <T> ArrayList<T> list(Enumeration<T> e)

CSE, KSIT, 2019-20 Page 79


Advanced Java & J2EE (17CS553) Study Material

Returns an array list containing the elements returned by the specified


enumeration in the order they are returned by the enumeration.
static <T extends Object & max(Collection<? extends T> coll)
Comparable<? super T>> Returns the maximum element of the given collection, according to the
T natural ordering of its elements.
max(Collection<? extends T> coll, Comparator<? super T> comp)
static <T> T Returns the maximum element of the given collection, according to the order
induced by the specified comparator.
static <T extends Object & min(Collection<? extends T> coll)
Comparable<? super T>> Returns the minimum element of the given collection, according to the
T natural ordering of its elements.
min(Collection<? extends T> coll, Comparator<? super T> comp)
static <T> T Returns the minimum element of the given collection, according to the order
induced by the specified comparator.
nCopies(int n, T o)
static <T> List<T>
Returns an immutable list consisting of n copies of the specified object.
newSetFromMap(Map<E,Boolean> map)
static <E> Set<E>
Returns a set backed by the specified map.
replaceAll(List<T> list, T oldVal, T newVal)
static <T> boolean
Replaces all occurrences of one specified value in a list with another.
reverse(List<?> list)
static void
Reverses the order of the elements in the specified list.
reverseOrder()
static <T> Comparator<T> Returns a comparator that imposes the reverse of the natural ordering on a
collection of objects that implement the Comparable interface.
reverseOrder(Comparator<T> cmp)
static <T> Comparator<T> Returns a comparator that imposes the reverse ordering of the specified
comparator.
rotate(List<?> list, int distance)
static void
Rotates the elements in the specified list by the specified distance.
shuffle(List<?> list)
static void
Randomly permutes the specified list using a default source of randomness.
shuffle(List<?> list, Random rnd)
static void Randomly permute the specified list using the specified source of
randomness.
singleton(T o)
static <T> Set<T>
Returns an immutable set containing only the specified object.
singletonList(T o)
static <T> List<T>
Returns an immutable list containing only the specified object.
singletonMap(K key, V value)
static <K,V> Map<K,V> Returns an immutable map, mapping only the specified key to the specified
value.
static <T extends Comparable<? sort(List<T> list)
super T>> Sorts the specified list into ascending order, according to the natural ordering
void of its elements.
static <T> void sort(List<T> list, Comparator<? super T> c)

CSE, KSIT, 2019-20 Page 80


Advanced Java & J2EE (17CS553) Study Material

Sorts the specified list according to the order induced by the specified
comparator.
swap(List<?> list, int i, int j)
static void
Swaps the elements at the specified positions in the specified list.
synchronizedCollection(Collection<T> c)
static <T> Collection<T> Returns a synchronized (thread-safe) collection backed by the specified
collection.
synchronizedList(List<T> list)
static <T> List<T>
Returns a synchronized (thread-safe) list backed by the specified list.
synchronizedMap(Map<K,V> m)
static <K,V> Map<K,V>
Returns a synchronized (thread-safe) map backed by the specified map.
synchronizedSet(Set<T> s)
static <T> Set<T>
Returns a synchronized (thread-safe) set backed by the specified set.
synchronizedSortedMap(SortedMap<K,V> m)
static <K,V> SortedMap<K,V> Returns a synchronized (thread-safe) sorted map backed by the specified
sorted map.
synchronizedSortedSet(SortedSet<T> s)
static <T> SortedSet<T> Returns a synchronized (thread-safe) sorted set backed by the specified sorted
set.
unmodifiableCollection(Collection<? extends T> c)
static <T> Collection<T>
Returns an unmodifiable view of the specified collection.
unmodifiableList(List<? extends T> list)
static <T> List<T>
Returns an unmodifiable view of the specified list.
unmodifiableMap(Map<? extends K,? extends V> m)
static <K,V> Map<K,V>
Returns an unmodifiable view of the specified map.
unmodifiableSet(Set<? extends T> s)
static <T> Set<T>
Returns an unmodifiable view of the specified set.
unmodifiableSortedMap(SortedMap<K,? extends V> m)
static <K,V> SortedMap<K,V>
Returns an unmodifiable view of the specified sorted map.
unmodifiableSortedSet(SortedSet<T> s)
static <T> SortedSet<T>
Returns an unmodifiable view of the specified sorted set.

Class Arrays

java.lang.Object
o java.util.Arrays

public class Arrays


extends Object

Method Summary

Methods

CSE, KSIT, 2019-20 Page 81


Advanced Java & J2EE (17CS553) Study Material

Modifier and
Method and Description
Type
asList(T... a)
static <T> List<T>
Returns a fixed-size list backed by the specified array.
binarySearch(byte[] a, byte key)
static int Searches the specified array of bytes for the specified value using the binary search
algorithm.
binarySearch(byte[] a, int fromIndex, int toIndex, byte key)
static int Searches a range of the specified array of bytes for the specified value using the binary
search algorithm.
binarySearch(char[] a, char key)
static int Searches the specified array of chars for the specified value using the binary search
algorithm.
binarySearch(char[] a, int fromIndex, int toIndex, char key)
static int Searches a range of the specified array of chars for the specified value using the binary
search algorithm.
binarySearch(double[] a, double key)
static int Searches the specified array of doubles for the specified value using the binary search
algorithm.
binarySearch(double[] a, int fromIndex, int toIndex, double key)
static int Searches a range of the specified array of doubles for the specified value using the binary
search algorithm.
binarySearch(float[] a, float key)
static int Searches the specified array of floats for the specified value using the binary search
algorithm.
binarySearch(float[] a, int fromIndex, int toIndex, float key)
static int Searches a range of the specified array of floats for the specified value using the binary
search algorithm.
binarySearch(int[] a, int key)
static int Searches the specified array of ints for the specified value using the binary search
algorithm.
binarySearch(int[] a, int fromIndex, int toIndex, int key)
static int Searches a range of the specified array of ints for the specified value using the binary
search algorithm.
binarySearch(long[] a, int fromIndex, int toIndex, long key)
static int Searches a range of the specified array of longs for the specified value using the binary
search algorithm.
binarySearch(long[] a, long key)
static int Searches the specified array of longs for the specified value using the binary search
algorithm.
binarySearch(Object[] a, int fromIndex, int toIndex, Object key)
static int Searches a range of the specified array for the specified object using the binary search
algorithm.
binarySearch(Object[] a, Object key)
static int
Searches the specified array for the specified object using the binary search algorithm.
static int binarySearch(short[] a, int fromIndex, int toIndex, short key)

CSE, KSIT, 2019-20 Page 82


Advanced Java & J2EE (17CS553) Study Material

Searches a range of the specified array of shorts for the specified value using the binary
search algorithm.
binarySearch(short[] a, short key)
static int Searches the specified array of shorts for the specified value using the binary search
algorithm.
binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)
static <T> int Searches a range of the specified array for the specified object using the binary search
algorithm.
binarySearch(T[] a, T key, Comparator<? super T> c)
static <T> int
Searches the specified array for the specified object using the binary search algorithm.
copyOf(boolean[] original, int newLength)
static boolean[] Copies the specified array, truncating or padding with false (if necessary) so the copy has
the specified length.
copyOf(byte[] original, int newLength)
static byte[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy has
the specified length.
copyOf(char[] original, int newLength)
static char[] Copies the specified array, truncating or padding with null characters (if necessary) so the
copy has the specified length.
copyOf(double[] original, int newLength)
static double[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy has
the specified length.
copyOf(float[] original, int newLength)
static float[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy has
the specified length.
copyOf(int[] original, int newLength)
static int[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy has
the specified length.
copyOf(long[] original, int newLength)
static long[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy has
the specified length.
copyOf(short[] original, int newLength)
static short[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy has
the specified length.
copyOf(T[] original, int newLength)
static <T> T[] Copies the specified array, truncating or padding with nulls (if necessary) so the copy has
the specified length.
copyOf(U[] original, int newLength, Class<? extends T[]> newType)
static <T,U> T[] Copies the specified array, truncating or padding with nulls (if necessary) so the copy has
the specified length.
copyOfRange(boolean[] original, int from, int to)
static boolean[]
Copies the specified range of the specified array into a new array.
copyOfRange(byte[] original, int from, int to)
static byte[]
Copies the specified range of the specified array into a new array.
copyOfRange(char[] original, int from, int to)
static char[]
Copies the specified range of the specified array into a new array.

CSE, KSIT, 2019-20 Page 83


Advanced Java & J2EE (17CS553) Study Material

copyOfRange(double[] original, int from, int to)


static double[]
Copies the specified range of the specified array into a new array.
copyOfRange(float[] original, int from, int to)
static float[]
Copies the specified range of the specified array into a new array.
copyOfRange(int[] original, int from, int to)
static int[]
Copies the specified range of the specified array into a new array.
copyOfRange(long[] original, int from, int to)
static long[]
Copies the specified range of the specified array into a new array.
copyOfRange(short[] original, int from, int to)
static short[]
Copies the specified range of the specified array into a new array.
copyOfRange(T[] original, int from, int to)
static <T> T[]
Copies the specified range of the specified array into a new array.
copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)
static <T,U> T[]
Copies the specified range of the specified array into a new array.
deepEquals(Object[] a1, Object[] a2)
static boolean
Returns true if the two specified arrays are deeply equal to one another.
deepHashCode(Object[] a)
static int
Returns a hash code based on the "deep contents" of the specified array.
deepToString(Object[] a)
static String
Returns a string representation of the "deep contents" of the specified array.
equals(boolean[] a, boolean[] a2)
static boolean
Returns true if the two specified arrays of booleans are equal to one another.
equals(byte[] a, byte[] a2)
static boolean
Returns true if the two specified arrays of bytes are equal to one another.
equals(char[] a, char[] a2)
static boolean
Returns true if the two specified arrays of chars are equal to one another.
equals(double[] a, double[] a2)
static boolean
Returns true if the two specified arrays of doubles are equal to one another.
equals(float[] a, float[] a2)
static boolean
Returns true if the two specified arrays of floats are equal to one another.
equals(int[] a, int[] a2)
static boolean
Returns true if the two specified arrays of ints are equal to one another.
equals(long[] a, long[] a2)
static boolean
Returns true if the two specified arrays of longs are equal to one another.
equals(Object[] a, Object[] a2)
static boolean
Returns true if the two specified arrays of Objects are equal to one another.
equals(short[] a, short[] a2)
static boolean
Returns true if the two specified arrays of shorts are equal to one another.
fill(boolean[] a, boolean val)
static void
Assigns the specified boolean value to each element of the specified array of booleans.
fill(boolean[] a, int fromIndex, int toIndex, boolean val)
static void Assigns the specified boolean value to each element of the specified range of the specified
array of booleans.
fill(byte[] a, byte val)
static void
Assigns the specified byte value to each element of the specified array of bytes.

CSE, KSIT, 2019-20 Page 84


Advanced Java & J2EE (17CS553) Study Material

fill(byte[] a, int fromIndex, int toIndex, byte val)


static void Assigns the specified byte value to each element of the specified range of the specified
array of bytes.
fill(char[] a, char val)
static void
Assigns the specified char value to each element of the specified array of chars.
fill(char[] a, int fromIndex, int toIndex, char val)
static void Assigns the specified char value to each element of the specified range of the specified
array of chars.
fill(double[] a, double val)
static void
Assigns the specified double value to each element of the specified array of doubles.
fill(double[] a, int fromIndex, int toIndex, double val)
static void Assigns the specified double value to each element of the specified range of the specified
array of doubles.
fill(float[] a, float val)
static void
Assigns the specified float value to each element of the specified array of floats.
fill(float[] a, int fromIndex, int toIndex, float val)
static void Assigns the specified float value to each element of the specified range of the specified
array of floats.
fill(int[] a, int val)
static void
Assigns the specified int value to each element of the specified array of ints.
fill(int[] a, int fromIndex, int toIndex, int val)
static void Assigns the specified int value to each element of the specified range of the specified array
of ints.
fill(long[] a, int fromIndex, int toIndex, long val)
static void Assigns the specified long value to each element of the specified range of the specified
array of longs.
fill(long[] a, long val)
static void
Assigns the specified long value to each element of the specified array of longs.
fill(Object[] a, int fromIndex, int toIndex, Object val)
static void Assigns the specified Object reference to each element of the specified range of the
specified array of Objects.
fill(Object[] a, Object val)
static void
Assigns the specified Object reference to each element of the specified array of Objects.
fill(short[] a, int fromIndex, int toIndex, short val)
static void Assigns the specified short value to each element of the specified range of the specified
array of shorts.
fill(short[] a, short val)
static void
Assigns the specified short value to each element of the specified array of shorts.
hashCode(boolean[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(byte[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(char[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(double[] a)
static int
Returns a hash code based on the contents of the specified array.

CSE, KSIT, 2019-20 Page 85


Advanced Java & J2EE (17CS553) Study Material

hashCode(float[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(int[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(long[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(Object[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(short[] a)
static int
Returns a hash code based on the contents of the specified array.
sort(byte[] a)
static void
Sorts the specified array into ascending numerical order.
sort(byte[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(char[] a)
static void
Sorts the specified array into ascending numerical order.
sort(char[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(double[] a)
static void
Sorts the specified array into ascending numerical order.
sort(double[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(float[] a)
static void
Sorts the specified array into ascending numerical order.
sort(float[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(int[] a)
static void
Sorts the specified array into ascending numerical order.
sort(int[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(long[] a)
static void
Sorts the specified array into ascending numerical order.
sort(long[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(Object[] a)
static void Sorts the specified array of objects into ascending order, according to the natural ordering
of its elements.
sort(Object[] a, int fromIndex, int toIndex)
static void Sorts the specified range of the specified array of objects into ascending order, according
to the natural ordering of its elements.
sort(short[] a)
static void
Sorts the specified array into ascending numerical order.
sort(short[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
static <T> void sort(T[] a, Comparator<? super T> c)

CSE, KSIT, 2019-20 Page 86


Advanced Java & J2EE (17CS553) Study Material

Sorts the specified array of objects according to the order induced by the specified
comparator.
sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)
static <T> void Sorts the specified range of the specified array of objects according to the order induced
by the specified comparator.
toString(boolean[] a)
static String
Returns a string representation of the contents of the specified array.
toString(byte[] a)
static String
Returns a string representation of the contents of the specified array.
toString(char[] a)
static String
Returns a string representation of the contents of the specified array.
toString(double[] a)
static String
Returns a string representation of the contents of the specified array.
toString(float[] a)
static String
Returns a string representation of the contents of the specified array.
toString(int[] a)
static String
Returns a string representation of the contents of the specified array.
toString(long[] a)
static String
Returns a string representation of the contents of the specified array.
toString(Object[] a)
static String
Returns a string representation of the contents of the specified array.
toString(short[] a)
static String
Returns a string representation of the contents of the specified array.

Class Arrays
public class Arrays
extends Object
This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a
static factory that allows arrays to be viewed as lists.

This class provides various methods that are useful when working with arrays.
These methods help bridge the gap between collections and arrays.

Method Summary
Methods

Modifier and
Method and Description
Type

asList(T... a)
static <T> List<T>
Returns a fixed-size list backed by the specified array.

CSE, KSIT, 2019-20 Page 87


Advanced Java & J2EE (17CS553) Study Material

binarySearch(byte[] a, byte key)


static int
Searches the specified array of bytes for the specified value using the binary search algorithm.

binarySearch(byte[] a, int fromIndex, int toIndex, byte key)


static int
Searches a range of the specified array of bytes for the specified value using the binary search
algorithm.

binarySearch(char[] a, char key)


static int
Searches the specified array of chars for the specified value using the binary search algorithm.

binarySearch(char[] a, int fromIndex, int toIndex, char key)


static int
Searches a range of the specified array of chars for the specified value using the binary search
algorithm.

binarySearch(double[] a, double key)


static int
Searches the specified array of doubles for the specified value using the binary search algorithm.

binarySearch(double[] a, int fromIndex, int toIndex, double key)


static int
Searches a range of the specified array of doubles for the specified value using the binary search
algorithm.

binarySearch(float[] a, float key)


static int
Searches the specified array of floats for the specified value using the binary search algorithm.

binarySearch(float[] a, int fromIndex, int toIndex, float key)


static int
Searches a range of the specified array of floats for the specified value using the binary search
algorithm.

binarySearch(int[] a, int key)


static int
Searches the specified array of ints for the specified value using the binary search algorithm.

binarySearch(int[] a, int fromIndex, int toIndex, int key)


static int
Searches a range of the specified array of ints for the specified value using the binary search
algorithm.

binarySearch(long[] a, int fromIndex, int toIndex, long key)


static int
Searches a range of the specified array of longs for the specified value using the binary search
algorithm.

CSE, KSIT, 2019-20 Page 88


Advanced Java & J2EE (17CS553) Study Material

binarySearch(long[] a, long key)


static int
Searches the specified array of longs for the specified value using the binary search algorithm.

binarySearch(Object[] a, int fromIndex, int toIndex, Object key)


static int
Searches a range of the specified array for the specified object using the binary search algorithm.

binarySearch(Object[] a, Object key)


static int
Searches the specified array for the specified object using the binary search algorithm.

binarySearch(short[] a, int fromIndex, int toIndex, short key)


static int
Searches a range of the specified array of shorts for the specified value using the binary search
algorithm.

binarySearch(short[] a, short key)


static int
Searches the specified array of shorts for the specified value using the binary search algorithm.

binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)


static <T> int
Searches a range of the specified array for the specified object using the binary search algorithm.

binarySearch(T[] a, T key, Comparator<? super T> c)


static <T> int
Searches the specified array for the specified object using the binary search algorithm.

copyOf(boolean[] original, int newLength)


static boolean[]
Copies the specified array, truncating or padding with false (if necessary) so the copy has the
specified length.

copyOf(byte[] original, int newLength)


static byte[]
Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the
specified length.

copyOf(char[] original, int newLength)


static char[]
Copies the specified array, truncating or padding with null characters (if necessary) so the copy has
the specified length.

copyOf(double[] original, int newLength)


static double[]
Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the
specified length.

CSE, KSIT, 2019-20 Page 89


Advanced Java & J2EE (17CS553) Study Material

copyOf(float[] original, int newLength)


static float[]
Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the
specified length.

copyOf(int[] original, int newLength)


static int[]
Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the
specified length.

copyOf(long[] original, int newLength)


static long[]
Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the
specified length.

copyOf(short[] original, int newLength)


static short[]
Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the
specified length.

copyOf(T[] original, int newLength)


static <T> T[]
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the
specified length.

copyOf(U[] original, int newLength, Class<? extends T[]> newType)


static <T,U> T[]
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the
specified length.

copyOfRange(boolean[] original, int from, int to)


static boolean[]
Copies the specified range of the specified array into a new array.

copyOfRange(byte[] original, int from, int to)


static byte[]
Copies the specified range of the specified array into a new array.

copyOfRange(char[] original, int from, int to)


static char[]
Copies the specified range of the specified array into a new array.

copyOfRange(double[] original, int from, int to)


static double[]
Copies the specified range of the specified array into a new array.

copyOfRange(float[] original, int from, int to)


static float[]
Copies the specified range of the specified array into a new array.

CSE, KSIT, 2019-20 Page 90


Advanced Java & J2EE (17CS553) Study Material

copyOfRange(int[] original, int from, int to)


static int[]
Copies the specified range of the specified array into a new array.

copyOfRange(long[] original, int from, int to)


static long[]
Copies the specified range of the specified array into a new array.

copyOfRange(short[] original, int from, int to)


static short[]
Copies the specified range of the specified array into a new array.

copyOfRange(T[] original, int from, int to)


static <T> T[]
Copies the specified range of the specified array into a new array.

copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)
static <T,U> T[]
Copies the specified range of the specified array into a new array.

deepEquals(Object[] a1, Object[] a2)


static boolean
Returns true if the two specified arrays are deeply equal to one another.

deepHashCode(Object[] a)
static int
Returns a hash code based on the "deep contents" of the specified array.

deepToString(Object[] a)
static String
Returns a string representation of the "deep contents" of the specified array.

equals(boolean[] a, boolean[] a2)


static boolean
Returns true if the two specified arrays of booleans are equal to one another.

equals(byte[] a, byte[] a2)


static boolean
Returns true if the two specified arrays of bytes are equal to one another.

equals(char[] a, char[] a2)


static boolean
Returns true if the two specified arrays of chars are equal to one another.

equals(double[] a, double[] a2)


static boolean
Returns true if the two specified arrays of doubles are equal to one another.

static boolean equals(float[] a, float[] a2)

CSE, KSIT, 2019-20 Page 91


Advanced Java & J2EE (17CS553) Study Material

Returns true if the two specified arrays of floats are equal to one another.

equals(int[] a, int[] a2)


static boolean
Returns true if the two specified arrays of ints are equal to one another.

equals(long[] a, long[] a2)


static boolean
Returns true if the two specified arrays of longs are equal to one another.

equals(Object[] a, Object[] a2)


static boolean
Returns true if the two specified arrays of Objects are equal to one another.

equals(short[] a, short[] a2)


static boolean
Returns true if the two specified arrays of shorts are equal to one another.

fill(boolean[] a, boolean val)


static void
Assigns the specified boolean value to each element of the specified array of booleans.

fill(boolean[] a, int fromIndex, int toIndex, boolean val)


static void
Assigns the specified boolean value to each element of the specified range of the specified array of
booleans.

fill(byte[] a, byte val)


static void
Assigns the specified byte value to each element of the specified array of bytes.

fill(byte[] a, int fromIndex, int toIndex, byte val)


static void
Assigns the specified byte value to each element of the specified range of the specified array of
bytes.

fill(char[] a, char val)


static void
Assigns the specified char value to each element of the specified array of chars.

fill(char[] a, int fromIndex, int toIndex, char val)


static void
Assigns the specified char value to each element of the specified range of the specified array of
chars.

fill(double[] a, double val)


static void
Assigns the specified double value to each element of the specified array of doubles.

CSE, KSIT, 2019-20 Page 92


Advanced Java & J2EE (17CS553) Study Material

fill(double[] a, int fromIndex, int toIndex, double val)


static void
Assigns the specified double value to each element of the specified range of the specified array of
doubles.

fill(float[] a, float val)


static void
Assigns the specified float value to each element of the specified array of floats.

fill(float[] a, int fromIndex, int toIndex, float val)


static void
Assigns the specified float value to each element of the specified range of the specified array of
floats.

fill(int[] a, int val)


static void
Assigns the specified int value to each element of the specified array of ints.

fill(int[] a, int fromIndex, int toIndex, int val)


static void
Assigns the specified int value to each element of the specified range of the specified array of ints.

fill(long[] a, int fromIndex, int toIndex, long val)


static void
Assigns the specified long value to each element of the specified range of the specified array of
longs.

fill(long[] a, long val)


static void
Assigns the specified long value to each element of the specified array of longs.

fill(Object[] a, int fromIndex, int toIndex, Object val)


static void
Assigns the specified Object reference to each element of the specified range of the specified array
of Objects.

fill(Object[] a, Object val)


static void
Assigns the specified Object reference to each element of the specified array of Objects.

fill(short[] a, int fromIndex, int toIndex, short val)


static void
Assigns the specified short value to each element of the specified range of the specified array of
shorts.

fill(short[] a, short val)


static void
Assigns the specified short value to each element of the specified array of shorts.

CSE, KSIT, 2019-20 Page 93


Advanced Java & J2EE (17CS553) Study Material

hashCode(boolean[] a)
static int
Returns a hash code based on the contents of the specified array.

hashCode(byte[] a)
static int
Returns a hash code based on the contents of the specified array.

hashCode(char[] a)
static int
Returns a hash code based on the contents of the specified array.

hashCode(double[] a)
static int
Returns a hash code based on the contents of the specified array.

hashCode(float[] a)
static int
Returns a hash code based on the contents of the specified array.

hashCode(int[] a)
static int
Returns a hash code based on the contents of the specified array.

hashCode(long[] a)
static int
Returns a hash code based on the contents of the specified array.

hashCode(Object[] a)
static int
Returns a hash code based on the contents of the specified array.

hashCode(short[] a)
static int
Returns a hash code based on the contents of the specified array.

sort(byte[] a)
static void
Sorts the specified array into ascending numerical order.

sort(byte[] a, int fromIndex, int toIndex)


static void
Sorts the specified range of the array into ascending order.

sort(char[] a)
static void
Sorts the specified array into ascending numerical order.

static void sort(char[] a, int fromIndex, int toIndex)

CSE, KSIT, 2019-20 Page 94


Advanced Java & J2EE (17CS553) Study Material

Sorts the specified range of the array into ascending order.

sort(double[] a)
static void
Sorts the specified array into ascending numerical order.

sort(double[] a, int fromIndex, int toIndex)


static void
Sorts the specified range of the array into ascending order.

sort(float[] a)
static void
Sorts the specified array into ascending numerical order.

sort(float[] a, int fromIndex, int toIndex)


static void
Sorts the specified range of the array into ascending order.

sort(int[] a)
static void
Sorts the specified array into ascending numerical order.

sort(int[] a, int fromIndex, int toIndex)


static void
Sorts the specified range of the array into ascending order.

sort(long[] a)
static void
Sorts the specified array into ascending numerical order.

sort(long[] a, int fromIndex, int toIndex)


static void
Sorts the specified range of the array into ascending order.

sort(Object[] a)
static void
Sorts the specified array of objects into ascending order, according to the natural ordering of its
elements.

sort(Object[] a, int fromIndex, int toIndex)


static void
Sorts the specified range of the specified array of objects into ascending order, according to the
natural ordering of its elements.

sort(short[] a)
static void
Sorts the specified array into ascending numerical order.

static void sort(short[] a, int fromIndex, int toIndex)

CSE, KSIT, 2019-20 Page 95


Advanced Java & J2EE (17CS553) Study Material

Sorts the specified range of the array into ascending order.

sort(T[] a, Comparator<? super T> c)


static <T> void
Sorts the specified array of objects according to the order induced by the specified comparator.

sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)


static <T> void
Sorts the specified range of the specified array of objects according to the order induced by the
specified comparator.

toString(boolean[] a)
static String
Returns a string representation of the contents of the specified array.

toString(byte[] a)
static String
Returns a string representation of the contents of the specified array.

toString(char[] a)
static String
Returns a string representation of the contents of the specified array.

toString(double[] a)
static String
Returns a string representation of the contents of the specified array.

toString(float[] a)
static String
Returns a string representation of the contents of the specified array.

toString(int[] a)
static String
Returns a string representation of the contents of the specified array.

toString(long[] a)
static String
Returns a string representation of the contents of the specified array.

toString(Object[] a)
static String
Returns a string representation of the contents of the specified array.

toString(short[] a)
static String
Returns a string representation of the contents of the specified array.

Example Program: The following program illustrates how to use some methods of the Arrays class:

CSE, KSIT, 2019-20 Page 96


Advanced Java & J2EE (17CS553) Study Material

import java.util.*;
class ArraysDemo
{
static void display(int array[])
{
for(int i:array)
System.out.print(i+" ");
System.out.println();
}
public static void main(String[] args)
{
int array[]=new int[10];
for(int i=0;i<array.length;i++)
array[i]= (-3)*i;
//Display, sort and display
System.out.print("Original Contents: ");
display(array);
Arrays.sort(array);
System.out.print("Sorted: ");
display(array);
//Fill and display
Arrays.fill(array,2,6,-1);
System.out.print("After fill(): ");
display(array);
//sort and display
Arrays.sort(array);
System.out.print("Sorted: ");
display(array);
//Binary Search for -9
System.out.println("The position of value -9 is: "+(Arrays.binarySearch(array,-9)+1));
}
}

The output of the program is shown here:


Original Contents: 0 -3 -6 -9 -12 -15 -18 -21 -24 -27
Sorted: -27 -24 -21 -18 -15 -12 -9 -6 -3 0
After fill(): -27 -24 -1 -1 -1 -1 -9 -6 -3 0
Sorted: -27 -24 -9 -6 -3 -1 -1 -1 -1 0
The position of value -9 is: 3

Why Generic Collection?


Generics add type safety to the Collections Framework.
The addition of generics fundamentally improves the usability and safety of collections because it
Ensures that only references to objects of proper type can actually be stored in a collection. Thus, a
collection will always contain references of a known type.
Eliminates the need to cast a reference retrieved from the collection. Instead, a reference retrieved
from a collection is automatically cast into the proper type. This prevents run-time errors due to
invalid casts and avoids an entire category of errors.

The Legacy Classes and Interfaces

CSE, KSIT, 2019-20 Page 97


Advanced Java & J2EE (17CS553) Study Material

The legacy classes defined by java.util are:

Dictionary
Hashtable
Properties
Stack
Vector

The Legacy interface is Enumeration

-------------------------------------------------------------------------------------------------------------

Class Dictionary<K,V>
public abstract class Dictionary<K,V>
extends Object

Constructor Summary

Constructors
Constructor and Description
Dictionary()
Sole constructor.

Method Summary

Methods
Modifier and Type Method and Description
elements()
abstract Enumeration<V>
Returns an enumeration of the values in this dictionary.
get(Object key)
abstract V
Returns the value to which the key is mapped in this dictionary.
isEmpty()
abstract boolean
Tests if this dictionary maps no keys to value.
keys()
abstract Enumeration<K>
Returns an enumeration of the keys in this dictionary.
put(K key, V value)
abstract V
Maps the specified key to the specified value in this dictionary.
remove(Object key)
abstract V
Removes the key (and its corresponding value) from this dictionary.
size()
abstract int
Returns the number of entries (distinct keys) in this dictionary.

CSE, KSIT, 2019-20 Page 98


Advanced Java & J2EE (17CS553) Study Material

Class Hashtable<K,V>
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, Serializable

Constructor Summary

Constructors
Constructor and Description
Hashtable()
Constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75).
Hashtable(int initialCapacity)
Constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75).
Hashtable(int initialCapacity, float loadFactor)
Constructs a new, empty hashtable with the specified initial capacity and the specified load factor.
Hashtable(Map<? extends K,? extends V> t)
Constructs a new hashtable with the same mappings as the given Map.

Method Summary

Methods
Modifier and Type Method and Description
clear()
void
Clears this hashtable so that it contains no keys.
clone()
Object
Creates a shallow copy of this hashtable.
contains(Object value)
boolean
Tests if some key maps into the specified value in this hashtable.
containsKey(Object key)
boolean
Tests if the specified object is a key in this hashtable.
containsValue(Object value)
boolean
Returns true if this hashtable maps one or more keys to this value.
elements()
Enumeration<V>
Returns an enumeration of the values in this hashtable.
entrySet()
Set<Map.Entry<K,V>>
Returns a Set view of the mappings contained in this map.
equals(Object o)
boolean Compares the specified Object with this Map for equality, as per the
definition in the Map interface.
get(Object key)
V Returns the value to which the specified key is mapped, or null if this map
contains no mapping for the key.
int hashCode()
CSE, KSIT, 2019-20 Page 99
Advanced Java & J2EE (17CS553) Study Material

Returns the hash code value for this Map as per the definition in the Map
interface.
isEmpty()
boolean
Tests if this hashtable maps no keys to values.
keys()
Enumeration<K>
Returns an enumeration of the keys in this hashtable.
keySet()
Set<K>
Returns a Set view of the keys contained in this map.
put(K key, V value)
V
Maps the specified key to the specified value in this hashtable.
putAll(Map<? extends K,? extends V> t)
void
Copies all of the mappings from the specified map to this hashtable.
rehash()
protected void Increases the capacity of and internally reorganizes this hashtable, in order
to accommodate and access its entries more efficiently.
remove(Object key)
V
Removes the key (and its corresponding value) from this hashtable.
size()
int
Returns the number of keys in this hashtable.
toString()
Returns a string representation of this Hashtable object in the form of a set
String
of entries, enclosed in braces and separated by the ASCII characters ", "
(comma and space).
values()
Collection<V>
Returns a Collection view of the values contained in this map.

Example Program
import java.util.*;
class HashtableDemo
{
public static void main(String[] args)
{
//System.out.println("Hello World!");
Hashtable<String,Double> bal=new Hashtable<String,Double>();
Enumeration<String> names;
String str;
double balance;
bal.put("HJR",99.99);
bal.put("SMS",999.99);
bal.put("HJH",99999.99);
names=bal.keys();
while(names.hasMoreElements())
{
str=names.nextElement();
System.out.println(str+":"+bal.get(str));

CSE, KSIT, 2019-20 Page 100


Advanced Java & J2EE (17CS553) Study Material

}
balance=bal.get("HJH");
bal.put("HJH",balance+9999.99);
System.out.println("HJH's new balance:"+bal.get("HJH"));
//output using Iterator, get a set view of the keys
Set<String> set=bal.keySet();
Iterator<String> itr=set.iterator();
System.out.println("Output using iterator");
while(itr.hasNext()){
str=itr.next();
System.out.println(str+":"+bal.get(str));
}
//output using for-each
System.out.println("Output using for-each");
for(Object s:set)
System.out.println(s+":"+bal.get(s));

}
}

The output of the program is shown here:


SMS:999.99
HJH:99999.99
HJR:99.99
HJH's new balance:109999.98000000001
Output using iterator
SMS:999.99
HJH:109999.98000000001
HJR:99.99
Output using for-each
SMS:999.99
HJH:109999.98000000001
HJR:99.99

Class Properties

Field Summary

Fields
Modifier and
Field and Description
Type
defaults
protected
A property list that contains default values for any keys not found in this
Properties
property list.

Constructor Summary

CSE, KSIT, 2019-20 Page 101


Advanced Java & J2EE (17CS553) Study Material

Constructors
Constructor and Description
Properties()
Creates an empty property list with no default values.
Properties(Properties defaults)
Creates an empty property list with the specified defaults.

Method Summary

Methods
Modifier and
Method and Description
Type
getProperty(String key)
String
Searches for the property with the specified key in this property list.
getProperty(String key, String defaultValue)
String
Searches for the property with the specified key in this property list.
list(PrintStream out)
void
Prints this property list out to the specified output stream.
list(PrintWriter out)
void
Prints this property list out to the specified output stream.
load(InputStream inStream)
void
Reads a property list (key and element pairs) from the input byte stream.
load(Reader reader)
void Reads a property list (key and element pairs) from the input character stream in a
simple line-oriented format.
loadFromXML(InputStream in)
void Loads all of the properties represented by the XML document on the specified
input stream into this properties table.
propertyNames()
Returns an enumeration of all the keys in this property list, including distinct keys
Enumeration<?>
in the default property list if a key of the same name has not already been found
from the main properties list.
save(OutputStream out, String comments)
Deprecated.
This method does not throw an IOException if an I/O error occurs while saving
void
the property list. The preferred way to save a properties list is via the
store(OutputStream out, String comments) method or the
storeToXML(OutputStream os, String comment) method.
setProperty(String key, String value)
Object
Calls the Hashtable method put.
store(OutputStream out, String comments)
void Writes this property list (key and element pairs) in this Properties table to the
output stream in a format suitable for loading into a Properties table using the

CSE, KSIT, 2019-20 Page 102


Advanced Java & J2EE (17CS553) Study Material

load(InputStream) method.
store(Writer writer, String comments)
void Writes this property list (key and element pairs) in this Properties table to the
output character stream in a format suitable for using the load(Reader) method.
storeToXML(OutputStream os, String comment)
void
Emits an XML document representing all of the properties contained in this table.
storeToXML(OutputStream os, String comment, String encoding)
void Emits an XML document representing all of the properties contained in this table,
using the specified encoding.
stringPropertyNames()
Returns a set of keys in this property list where the key and its corresponding
Set<String>
value are strings, including distinct keys in the default property list if a key of the
same name has not already been found from the main properties list.

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

Properties defList=new Properties();


Properties capitals=new Properties(defList);
defList.put("India","New Delhi");
defList.put("Karnataka","Bengaluru");

capitals.put("Kerala","Thiruvanthapuram");
capitals.put("Tamilnadu","Chennai");

Set states=capitals.keySet();
for(Object o:states)
System.out.println(o+":"+capitals.getProperty((String)o));
System.out.println();
System.out.println("The capital of India is "+capitals.getProperty("India"));
System.out.println("The capital of Karnataka is "+capitals.getProperty("Karnataka"));

}
}

The output of the program is shown here:


Tamilnadu:Chennai
Kerala:Thiruvanthapuram

The capital of India is New Delhi


The capital of Karnataka is Bengaluru

CSE, KSIT, 2019-20 Page 103


Advanced Java & J2EE (17CS553) Study Material

Class Stack<E>
public class Stack<E>
extends Vector<E>

Field Summary
o Fields inherited from class java.util.Vector

capacityIncrement, elementCount, elementData

o Fields inherited from class java.util.AbstractList

modCount

Constructor Summary

Constructors
Constructor and Description
Stack()
Creates an empty Stack.

Method Summary

Methods
Modifier and
Method and Description
Type
empty()
boolean
Tests if this stack is empty.
peek()
E
Looks at the object at the top of this stack without removing it from the stack.
pop()
E Removes the object at the top of this stack and returns that object as the value of
this function.
push(E item)
E
Pushes an item onto the top of this stack.
search(Object o)
int
Returns the 1-based position where an object is on this stack.

Example Program:
import java.util.*;
class StackDemo
{

public static void showPush(Stack<Integer> st,int ele)


{
st.push(ele);
System.out.println("push("+ele+")");
CSE, KSIT, 2019-20 Page 104
Advanced Java & J2EE (17CS553) Study Material

System.out.println("Stack: "+st);
}
public static void showPop(Stack<Integer> st)
{
Integer i=st.pop();
System.out.println("pop-->"+i);
System.out.println("Stack: "+st);
}
public static void main(String[] args)
{
Stack<Integer> st=new Stack<Integer>();
try
{
showPush(st,100);
showPush(st,99);
showPush(st,98);
showPop(st);
showPop(st);
showPop(st);
showPop(st);
}
catch (EmptyStackException e)
{
System.out.println("Empty Stack");
}
}
}

The output of the program is shown here:


push(100)
Stack: [100]
push(99)
Stack: [100, 99]
push(98)
Stack: [100, 99, 98]
pop-->98
Stack: [100, 99]
pop-->99
Stack: [100]
pop-->100
Stack: []
Empty Stack

Class Vector<E>

Field Summary

Fields

CSE, KSIT, 2019-20 Page 105


Advanced Java & J2EE (17CS553) Study Material

Modifier and
Field and Description
Type
capacityIncrement
protected int The amount by which the capacity of the vector is automatically incremented when
its size becomes greater than its capacity.
elementCount
protected int
The number of valid components in this Vector object.
protected elementData
Object[] The array buffer into which the components of the vector are stored.

o Fields inherited from class java.util.AbstractList

modCount

Constructor Summary

Constructors
Constructor and Description
Vector()
Constructs an empty vector so that its internal data array has size 10 and its standard capacity
increment is zero.
Vector(Collection<? extends E> c)
Constructs a vector containing the elements of the specified collection, in the order they are returned
by the collection's iterator.
Vector(int initialCapacity)
Constructs an empty vector with the specified initial capacity and with its capacity increment equal
to zero.
Vector(int initialCapacity, int capacityIncrement)
Constructs an empty vector with the specified initial capacity and capacity increment.

Method Summary

Methods
Modifier and
Method and Description
Type
add(E e)
boolean
Appends the specified element to the end of this Vector.
add(int index, E element)
void
Inserts the specified element at the specified position in this Vector.
addAll(Collection<? extends E> c)
boolean Appends all of the elements in the specified Collection to the end of this Vector,
in the order that they are returned by the specified Collection's Iterator.
addAll(int index, Collection<? extends E> c)
boolean
Inserts all of the elements in the specified Collection into this Vector at the
CSE, KSIT, 2019-20 Page 106
Advanced Java & J2EE (17CS553) Study Material

specified position.
addElement(E obj)
void
Adds the specified component to the end of this vector, increasing its size by one.
capacity()
int
Returns the current capacity of this vector.
clear()
void
Removes all of the elements from this Vector.
clone()
Object
Returns a clone of this vector.
contains(Object o)
boolean
Returns true if this vector contains the specified element.
containsAll(Collection<?> c)
boolean
Returns true if this Vector contains all of the elements in the specified Collection.
copyInto(Object[] anArray)
void
Copies the components of this vector into the specified array.
elementAt(int index)
E
Returns the component at the specified index.
elements()
Enumeration<E>
Returns an enumeration of the components of this vector.
ensureCapacity(int minCapacity)
void Increases the capacity of this vector, if necessary, to ensure that it can hold at
least the number of components specified by the minimum capacity argument.
equals(Object o)
boolean
Compares the specified Object with this Vector for equality.
firstElement()
E
Returns the first component (the item at index 0) of this vector.
get(int index)
E
Returns the element at the specified position in this Vector.
hashCode()
int
Returns the hash code value for this Vector.
indexOf(Object o)
int Returns the index of the first occurrence of the specified element in this vector, or
-1 if this vector does not contain the element.
indexOf(Object o, int index)
int Returns the index of the first occurrence of the specified element in this vector,
searching forwards from index, or returns -1 if the element is not found.
insertElementAt(E obj, int index)
void
Inserts the specified object as a component in this vector at the specified index.
isEmpty()
boolean
Tests if this vector has no components.
iterator()
Iterator<E>
Returns an iterator over the elements in this list in proper sequence.

CSE, KSIT, 2019-20 Page 107


Advanced Java & J2EE (17CS553) Study Material

lastElement()
E
Returns the last component of the vector.
lastIndexOf(Object o)
int Returns the index of the last occurrence of the specified element in this vector, or
-1 if this vector does not contain the element.
lastIndexOf(Object o, int index)
int Returns the index of the last occurrence of the specified element in this vector,
searching backwards from index, or returns -1 if the element is not found.
listIterator()
ListIterator<E>
Returns a list iterator over the elements in this list (in proper sequence).
listIterator(int index)
ListIterator<E> Returns a list iterator over the elements in this list (in proper sequence), starting
at the specified position in the list.
remove(int index)
E
Removes the element at the specified position in this Vector.
remove(Object o)
boolean Removes the first occurrence of the specified element in this Vector If the Vector
does not contain the element, it is unchanged.
removeAll(Collection<?> c)
boolean Removes from this Vector all of its elements that are contained in the specified
Collection.
removeAllElements()
void
Removes all components from this vector and sets its size to zero.
removeElement(Object obj)
boolean
Removes the first (lowest-indexed) occurrence of the argument from this vector.
removeElementAt(int index)
void
Deletes the component at the specified index.
removeRange(int fromIndex, int toIndex)
protected void Removes from this list all of the elements whose index is between fromIndex,
inclusive, and toIndex, exclusive.
retainAll(Collection<?> c)
boolean Retains only the elements in this Vector that are contained in the specified
Collection.
set(int index, E element)
E Replaces the element at the specified position in this Vector with the specified
element.
setElementAt(E obj, int index)
void
Sets the component at the specified index of this vector to be the specified object.
setSize(int newSize)
void
Sets the size of this vector.
size()
int
Returns the number of components in this vector.
List<E> subList(int fromIndex, int toIndex)

CSE, KSIT, 2019-20 Page 108


Advanced Java & J2EE (17CS553) Study Material

Returns a view of the portion of this List between fromIndex, inclusive, and
toIndex, exclusive.
toArray()
Object[]
Returns an array containing all of the elements in this Vector in the correct order.
toArray(T[] a)
<T> T[] Returns an array containing all of the elements in this Vector in the correct order;
the runtime type of the returned array is that of the specified array.
toString()
String Returns a string representation of this Vector, containing the String representation
of each element.
trimToSize()
void
Trims the capacity of this vector to be the vector's current size.

Example Program:
import java.util.*;
class VectorDemo
{
public static void main(String[] args)
{
Vector<Integer> v=new Vector<Integer>(3,2);
System.out.println("Initial Size: "+v.size());
System.out.println("Initial Capacity: "+v.capacity());

v.addElement(1);
v.addElement(2);
v.addElement(3);
v.addElement(4);
System.out.println("Capacity after 4 additions: "+v.capacity());
v.addElement(5);
System.out.println("Capacity after 1 additions: "+v.capacity());
v.addElement(6);
v.addElement(7);
System.out.println("Capacity after 2 more additions: "+v.capacity());
v.addElement(8);
v.addElement(9);
System.out.println("Capacity after 2 more additions: "+v.capacity());
v.addElement(10);
v.addElement(11);
System.out.println("Capacity after 2 more additions: "+v.capacity());
System.out.println("First element: "+v.firstElement());
System.out.println("Last element: "+v.lastElement());
if(v.contains(3))
System.out.println("Vector contains 3");
//Enumerate(obtain one at a time) the elements in the vector
Enumeration e=v.elements();
System.out.println("Elements in vector-using Enumeration");
while(e.hasMoreElements())

CSE, KSIT, 2019-20 Page 109


Advanced Java & J2EE (17CS553) Study Material

System.out.print(e.nextElement()+" ");
System.out.println();

//Using iterator to display vector contents


Iterator<Integer> vItr=v.iterator();
//Iterator methods
//boolean hasNext()
//E next()
//void remove()
System.out.println("Elements in vector-using Iterator");
while (vItr.hasNext())
System.out.print(vItr.next()+" ");
System.out.println();

System.out.println("Elements in vector-using foreach");


for(int i:v)
System.out.print(i+" ");
System.out.println();

}
}

The output of the program is shown here


Initial Size: 0
Initial Capacity: 3
Capacity after 4 additions: 5
Capacity after 1 additions: 5
Capacity after 2 more additions: 7
Capacity after 2 more additions: 9
Capacity after 2 more additions: 11
First element: 1
Last element: 11
Vector contains 3
Elements in vector-using Enumeration
1 2 3 4 5 6 7 8 9 10 11
Elements in vector-using Iterator
1 2 3 4 5 6 7 8 9 10 11
Elements in vector-using foreach
1 2 3 4 5 6 7 8 9 10 11

Enumeration Interface
Interface Enumeration<E>
All Known Subinterfaces:
NamingEnumeration<T>

All Known Implementing Classes:

StringTokenizer

CSE, KSIT, 2019-20 Page 110


Advanced Java & J2EE (17CS553) Study Material

General Form:

public interface Enumeration<E>

Method Summary
Methods

Modifier and
Method and Description
Type

hasMoreElements()
boolean
Tests if this enumeration contains more elements.

nextElement()
E Returns the next element of this enumeration if this enumeration object has at least one
more element to provide.

Accessing a Collection via an Iterator


To cycle through the elements in a collection is to employ an iterator which is an object that implements
either Interfaces : Iterator or the ListIterator

Interface Iterator<E>
Type Parameters:
E - the type of elements returned by this iterator

All Known Subinterfaces:

ListIterator<E>, XMLEventReader

All Known Implementing Classes:

BeanContextSupport.BCSIterator, EventReaderDelegate, Scanner

public interface Iterator<E>

Method Summary
Methods

Modifier and Method and Description

CSE, KSIT, 2019-20 Page 111


Advanced Java & J2EE (17CS553) Study Material

Type

hasNext()
boolean
Returns true if the iteration has more elements.

next()
E
Returns the next element in the iteration.

remove()
void Removes from the underlying collection the last element returned by this iterator
(optional operation).

Interface ListIterator<E>
public interface ListIterator<E>
extends Iterator<E>

Method Summary
Methods

Modifier and
Method and Description
Type

add(E e)
void
Inserts the specified element into the list (optional operation).

hasNext()
boolean Returns true if this list iterator has more elements when traversing the list in the forward
direction.

hasPrevious()
boolean Returns true if this list iterator has more elements when traversing the list in the reverse
direction.

next()
E
Returns the next element in the list and advances the cursor position.

CSE, KSIT, 2019-20 Page 112


Advanced Java & J2EE (17CS553) Study Material

nextIndex()
int
Returns the index of the element that would be returned by a subsequent call to next().

previous()
E
Returns the previous element in the list and moves the cursor position backwards.

previousIndex()
int Returns the index of the element that would be returned by a subsequent call to
previous().

remove()
void Removes from the list the last element that was returned by next() or previous() (optional
operation).

set(E e)
void Replaces the last element returned by next() or previous() with the specified element
(optional operation).

The Algorithms defined by Collections

Field Summary

Fields
Modifier and Type Field and Description
EMPTY_LIST
static List
The empty list (immutable).
EMPTY_MAP
static Map
The empty map (immutable).
EMPTY_SET
static Set
The empty set (immutable).

Method Summary

Methods
Modifier and Type Method and Description
static <T> boolean addAll(Collection<? super T> c, T... elements)

CSE, KSIT, 2019-20 Page 113


Advanced Java & J2EE (17CS553) Study Material

Adds all of the specified elements to the specified collection.


asLifoQueue(Deque<T> deque)
static <T> Queue<T>
Returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
binarySearch(List<? extends Comparable<? super T>> list,
T key)
static <T> int
Searches the specified list for the specified object using the binary search
algorithm.
binarySearch(List<? extends T> list, T key, Comparator<?
super T> c)
static <T> int
Searches the specified list for the specified object using the binary search
algorithm.
checkedCollection(Collection<E> c, Class<E> type)
static <E> Collection<E>
Returns a dynamically typesafe view of the specified collection.
checkedList(List<E> list, Class<E> type)
static <E> List<E>
Returns a dynamically typesafe view of the specified list.
checkedMap(Map<K,V> m, Class<K> keyType,
static <K,V> Map<K,V> Class<V> valueType)
Returns a dynamically typesafe view of the specified map.
checkedSet(Set<E> s, Class<E> type)
static <E> Set<E>
Returns a dynamically typesafe view of the specified set.
checkedSortedMap(SortedMap<K,V> m, Class<K> keyType,
static <K,V> SortedMap<K,V> Class<V> valueType)
Returns a dynamically typesafe view of the specified sorted map.
checkedSortedSet(SortedSet<E> s, Class<E> type)
static <E> SortedSet<E>
Returns a dynamically typesafe view of the specified sorted set.
copy(List<? super T> dest, List<? extends T> src)
static <T> void
Copies all of the elements from one list into another.
disjoint(Collection<?> c1, Collection<?> c2)
static boolean Returns true if the two specified collections have no elements in
common.
emptyEnumeration()
static <T> Enumeration<T>
Returns an enumeration that has no elements.
emptyIterator()
static <T> Iterator<T>
Returns an iterator that has no elements.
emptyList()
static <T> List<T>
Returns the empty list (immutable).
emptyListIterator()
static <T> ListIterator<T>
Returns a list iterator that has no elements.
emptyMap()
static <K,V> Map<K,V>
Returns the empty map (immutable).
emptySet()
static <T> Set<T>
Returns the empty set (immutable).
enumeration(Collection<T> c)
static <T> Enumeration<T>
Returns an enumeration over the specified collection.
fill(List<? super T> list, T obj)
static <T> void
Replaces all of the elements of the specified list with the specified

CSE, KSIT, 2019-20 Page 114


Advanced Java & J2EE (17CS553) Study Material

element.
frequency(Collection<?> c, Object o)
static int Returns the number of elements in the specified collection equal to the
specified object.
indexOfSubList(List<?> source, List<?> target)
static int Returns the starting position of the first occurrence of the specified target
list within the specified source list, or -1 if there is no such occurrence.
lastIndexOfSubList(List<?> source, List<?> target)
static int Returns the starting position of the last occurrence of the specified target
list within the specified source list, or -1 if there is no such occurrence.
list(Enumeration<T> e)
static <T> ArrayList<T> Returns an array list containing the elements returned by the specified
enumeration in the order they are returned by the enumeration.
static <T extends Object & max(Collection<? extends T> coll)
Comparable<? super T>> Returns the maximum element of the given collection, according to the
T natural ordering of its elements.
max(Collection<? extends T> coll, Comparator<? super
T> comp)
static <T> T
Returns the maximum element of the given collection, according to the
order induced by the specified comparator.
static <T extends Object & min(Collection<? extends T> coll)
Comparable<? super T>> Returns the minimum element of the given collection, according to the
T natural ordering of its elements.
min(Collection<? extends T> coll, Comparator<? super
T> comp)
static <T> T
Returns the minimum element of the given collection, according to the
order induced by the specified comparator.
nCopies(int n, T o)
static <T> List<T>
Returns an immutable list consisting of n copies of the specified object.
newSetFromMap(Map<E,Boolean> map)
static <E> Set<E>
Returns a set backed by the specified map.
replaceAll(List<T> list, T oldVal, T newVal)
static <T> boolean
Replaces all occurrences of one specified value in a list with another.
reverse(List<?> list)
static void
Reverses the order of the elements in the specified list.
reverseOrder()
static <T> Comparator<T> Returns a comparator that imposes the reverse of the natural ordering on
a collection of objects that implement the Comparable interface.
reverseOrder(Comparator<T> cmp)
static <T> Comparator<T> Returns a comparator that imposes the reverse ordering of the specified
comparator.
rotate(List<?> list, int distance)
static void
Rotates the elements in the specified list by the specified distance.
shuffle(List<?> list)
static void Randomly permutes the specified list using a default source of
randomness.

CSE, KSIT, 2019-20 Page 115


Advanced Java & J2EE (17CS553) Study Material

shuffle(List<?> list, Random rnd)


static void Randomly permute the specified list using the specified source of
randomness.
singleton(T o)
static <T> Set<T>
Returns an immutable set containing only the specified object.
singletonList(T o)
static <T> List<T>
Returns an immutable list containing only the specified object.
singletonMap(K key, V value)
static <K,V> Map<K,V> Returns an immutable map, mapping only the specified key to the
specified value.
static <T extends sort(List<T> list)
Comparable<? super T>> Sorts the specified list into ascending order, according to the natural
void ordering of its elements.
sort(List<T> list, Comparator<? super T> c)
static <T> void Sorts the specified list according to the order induced by the specified
comparator.
swap(List<?> list, int i, int j)
static void
Swaps the elements at the specified positions in the specified list.
synchronizedCollection(Collection<T> c)
static <T> Collection<T> Returns a synchronized (thread-safe) collection backed by the specified
collection.
synchronizedList(List<T> list)
static <T> List<T>
Returns a synchronized (thread-safe) list backed by the specified list.
synchronizedMap(Map<K,V> m)
static <K,V> Map<K,V>
Returns a synchronized (thread-safe) map backed by the specified map.
synchronizedSet(Set<T> s)
static <T> Set<T>
Returns a synchronized (thread-safe) set backed by the specified set.
synchronizedSortedMap(SortedMap<K,V> m)
static <K,V> SortedMap<K,V> Returns a synchronized (thread-safe) sorted map backed by the specified
sorted map.
synchronizedSortedSet(SortedSet<T> s)
static <T> SortedSet<T> Returns a synchronized (thread-safe) sorted set backed by the specified
sorted set.
unmodifiableCollection(Collection<? extends T> c)
static <T> Collection<T>
Returns an unmodifiable view of the specified collection.
unmodifiableList(List<? extends T> list)
static <T> List<T>
Returns an unmodifiable view of the specified list.
unmodifiableMap(Map<? extends K,? extends V> m)
static <K,V> Map<K,V>
Returns an unmodifiable view of the specified map.
unmodifiableSet(Set<? extends T> s)
static <T> Set<T>
Returns an unmodifiable view of the specified set.
unmodifiableSortedMap(SortedMap<K,? extends V> m)
static <K,V> SortedMap<K,V>
Returns an unmodifiable view of the specified sorted map.
unmodifiableSortedSet(SortedSet<T> s)
static <T> SortedSet<T>
Returns an unmodifiable view of the specified sorted set.

CSE, KSIT, 2019-20 Page 116


Advanced Java & J2EE (17CS553) Study Material

Class Arrays

java.lang.Object

o java.util.Arrays

public class Arrays


extends Object

Method Summary

Methods
Modifier and
Method and Description
Type
static asList(T... a)
<T> List<T> Returns a fixed-size list backed by the specified array.
binarySearch(byte[] a, byte key)
static int Searches the specified array of bytes for the specified value using the binary search
algorithm.
binarySearch(byte[] a, int fromIndex, int toIndex, byte key)
static int Searches a range of the specified array of bytes for the specified value using the binary
search algorithm.
binarySearch(char[] a, char key)
static int Searches the specified array of chars for the specified value using the binary search
algorithm.
binarySearch(char[] a, int fromIndex, int toIndex, char key)
static int Searches a range of the specified array of chars for the specified value using the binary
search algorithm.
binarySearch(double[] a, double key)
static int Searches the specified array of doubles for the specified value using the binary search
algorithm.
binarySearch(double[] a, int fromIndex, int toIndex, double key)
static int Searches a range of the specified array of doubles for the specified value using the
binary search algorithm.
binarySearch(float[] a, float key)
static int Searches the specified array of floats for the specified value using the binary search
algorithm.
binarySearch(float[] a, int fromIndex, int toIndex, float key)
static int Searches a range of the specified array of floats for the specified value using the binary
search algorithm.
binarySearch(int[] a, int key)
static int
Searches the specified array of ints for the specified value using the binary search

CSE, KSIT, 2019-20 Page 117


Advanced Java & J2EE (17CS553) Study Material

algorithm.
binarySearch(int[] a, int fromIndex, int toIndex, int key)
static int Searches a range of the specified array of ints for the specified value using the binary
search algorithm.
binarySearch(long[] a, int fromIndex, int toIndex, long key)
static int Searches a range of the specified array of longs for the specified value using the binary
search algorithm.
binarySearch(long[] a, long key)
static int Searches the specified array of longs for the specified value using the binary search
algorithm.
binarySearch(Object[] a, int fromIndex, int toIndex, Object key)
static int Searches a range of the specified array for the specified object using the binary search
algorithm.
binarySearch(Object[] a, Object key)
static int
Searches the specified array for the specified object using the binary search algorithm.
binarySearch(short[] a, int fromIndex, int toIndex, short key)
static int Searches a range of the specified array of shorts for the specified value using the binary
search algorithm.
binarySearch(short[] a, short key)
static int Searches the specified array of shorts for the specified value using the binary search
algorithm.
binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<?
super T> c)
static <T> int
Searches a range of the specified array for the specified object using the binary search
algorithm.
binarySearch(T[] a, T key, Comparator<? super T> c)
static <T> int
Searches the specified array for the specified object using the binary search algorithm.
copyOf(boolean[] original, int newLength)
static
boolean[]
Copies the specified array, truncating or padding with false (if necessary) so the copy
has the specified length.
copyOf(byte[] original, int newLength)
static byte[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy
has the specified length.
copyOf(char[] original, int newLength)
static char[] Copies the specified array, truncating or padding with null characters (if necessary) so
the copy has the specified length.
copyOf(double[] original, int newLength)
static
double[]
Copies the specified array, truncating or padding with zeros (if necessary) so the copy
has the specified length.
copyOf(float[] original, int newLength)
static float[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy
has the specified length.
copyOf(int[] original, int newLength)
static int[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy
has the specified length.
static long[] copyOf(long[] original, int newLength)

CSE, KSIT, 2019-20 Page 118


Advanced Java & J2EE (17CS553) Study Material

Copies the specified array, truncating or padding with zeros (if necessary) so the copy
has the specified length.
copyOf(short[] original, int newLength)
static short[] Copies the specified array, truncating or padding with zeros (if necessary) so the copy
has the specified length.
copyOf(T[] original, int newLength)
static <T> T[] Copies the specified array, truncating or padding with nulls (if necessary) so the copy
has the specified length.
copyOf(U[] original, int newLength, Class<? extends T[]> newType)
static
<T,U> T[]
Copies the specified array, truncating or padding with nulls (if necessary) so the copy
has the specified length.
static copyOfRange(boolean[] original, int from, int to)
boolean[] Copies the specified range of the specified array into a new array.
copyOfRange(byte[] original, int from, int to)
static byte[]
Copies the specified range of the specified array into a new array.
copyOfRange(char[] original, int from, int to)
static char[]
Copies the specified range of the specified array into a new array.
static copyOfRange(double[] original, int from, int to)
double[] Copies the specified range of the specified array into a new array.
copyOfRange(float[] original, int from, int to)
static float[]
Copies the specified range of the specified array into a new array.
copyOfRange(int[] original, int from, int to)
static int[]
Copies the specified range of the specified array into a new array.
copyOfRange(long[] original, int from, int to)
static long[]
Copies the specified range of the specified array into a new array.
copyOfRange(short[] original, int from, int to)
static short[]
Copies the specified range of the specified array into a new array.
copyOfRange(T[] original, int from, int to)
static <T> T[]
Copies the specified range of the specified array into a new array.
copyOfRange(U[] original, int from, int to, Class<? extends
static T[]> newType)
<T,U> T[]
Copies the specified range of the specified array into a new array.
deepEquals(Object[] a1, Object[] a2)
static boolean
Returns true if the two specified arrays are deeply equal to one another.
deepHashCode(Object[] a)
static int
Returns a hash code based on the "deep contents" of the specified array.
deepToString(Object[] a)
static String
Returns a string representation of the "deep contents" of the specified array.
equals(boolean[] a, boolean[] a2)
static boolean
Returns true if the two specified arrays of booleans are equal to one another.
equals(byte[] a, byte[] a2)
static boolean
Returns true if the two specified arrays of bytes are equal to one another.
equals(char[] a, char[] a2)
static boolean
Returns true if the two specified arrays of chars are equal to one another.
static boolean equals(double[] a, double[] a2)

CSE, KSIT, 2019-20 Page 119


Advanced Java & J2EE (17CS553) Study Material

Returns true if the two specified arrays of doubles are equal to one another.
equals(float[] a, float[] a2)
static boolean
Returns true if the two specified arrays of floats are equal to one another.
equals(int[] a, int[] a2)
static boolean
Returns true if the two specified arrays of ints are equal to one another.
equals(long[] a, long[] a2)
static boolean
Returns true if the two specified arrays of longs are equal to one another.
equals(Object[] a, Object[] a2)
static boolean
Returns true if the two specified arrays of Objects are equal to one another.
equals(short[] a, short[] a2)
static boolean
Returns true if the two specified arrays of shorts are equal to one another.
fill(boolean[] a, boolean val)
static void
Assigns the specified boolean value to each element of the specified array of booleans.
fill(boolean[] a, int fromIndex, int toIndex, boolean val)
static void Assigns the specified boolean value to each element of the specified range of the
specified array of booleans.
fill(byte[] a, byte val)
static void
Assigns the specified byte value to each element of the specified array of bytes.
fill(byte[] a, int fromIndex, int toIndex, byte val)
static void Assigns the specified byte value to each element of the specified range of the specified
array of bytes.
fill(char[] a, char val)
static void
Assigns the specified char value to each element of the specified array of chars.
fill(char[] a, int fromIndex, int toIndex, char val)
static void Assigns the specified char value to each element of the specified range of the specified
array of chars.
fill(double[] a, double val)
static void
Assigns the specified double value to each element of the specified array of doubles.
fill(double[] a, int fromIndex, int toIndex, double val)
static void Assigns the specified double value to each element of the specified range of the
specified array of doubles.
fill(float[] a, float val)
static void
Assigns the specified float value to each element of the specified array of floats.
fill(float[] a, int fromIndex, int toIndex, float val)
static void Assigns the specified float value to each element of the specified range of the specified
array of floats.
fill(int[] a, int val)
static void
Assigns the specified int value to each element of the specified array of ints.
fill(int[] a, int fromIndex, int toIndex, int val)
static void Assigns the specified int value to each element of the specified range of the specified
array of ints.
fill(long[] a, int fromIndex, int toIndex, long val)
static void Assigns the specified long value to each element of the specified range of the specified
array of longs.
static void fill(long[] a, long val)

CSE, KSIT, 2019-20 Page 120


Advanced Java & J2EE (17CS553) Study Material

Assigns the specified long value to each element of the specified array of longs.
fill(Object[] a, int fromIndex, int toIndex, Object val)
static void Assigns the specified Object reference to each element of the specified range of the
specified array of Objects.
fill(Object[] a, Object val)
static void
Assigns the specified Object reference to each element of the specified array of Objects.
fill(short[] a, int fromIndex, int toIndex, short val)
static void Assigns the specified short value to each element of the specified range of the specified
array of shorts.
fill(short[] a, short val)
static void
Assigns the specified short value to each element of the specified array of shorts.
hashCode(boolean[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(byte[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(char[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(double[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(float[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(int[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(long[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(Object[] a)
static int
Returns a hash code based on the contents of the specified array.
hashCode(short[] a)
static int
Returns a hash code based on the contents of the specified array.
sort(byte[] a)
static void
Sorts the specified array into ascending numerical order.
sort(byte[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(char[] a)
static void
Sorts the specified array into ascending numerical order.
sort(char[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(double[] a)
static void
Sorts the specified array into ascending numerical order.
sort(double[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(float[] a)
static void
Sorts the specified array into ascending numerical order.
sort(float[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.

CSE, KSIT, 2019-20 Page 121


Advanced Java & J2EE (17CS553) Study Material

sort(int[] a)
static void
Sorts the specified array into ascending numerical order.
sort(int[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(long[] a)
static void
Sorts the specified array into ascending numerical order.
sort(long[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(Object[] a)
static void Sorts the specified array of objects into ascending order, according to the natural
ordering of its elements.
sort(Object[] a, int fromIndex, int toIndex)
static void Sorts the specified range of the specified array of objects into ascending order, according
to the natural ordering of its elements.
sort(short[] a)
static void
Sorts the specified array into ascending numerical order.
sort(short[] a, int fromIndex, int toIndex)
static void
Sorts the specified range of the array into ascending order.
sort(T[] a, Comparator<? super T> c)
static
<T> void
Sorts the specified array of objects according to the order induced by the specified
comparator.
sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)
static
<T> void
Sorts the specified range of the specified array of objects according to the order induced
by the specified comparator.
toString(boolean[] a)
static String
Returns a string representation of the contents of the specified array.
toString(byte[] a)
static String
Returns a string representation of the contents of the specified array.
toString(char[] a)
static String
Returns a string representation of the contents of the specified array.
toString(double[] a)
static String
Returns a string representation of the contents of the specified array.
toString(float[] a)
static String
Returns a string representation of the contents of the specified array.
toString(int[] a)
static String
Returns a string representation of the contents of the specified array.
toString(long[] a)
static String
Returns a string representation of the contents of the specified array.
toString(Object[] a)
static String
Returns a string representation of the contents of the specified array.
toString(short[] a)
static String
Returns a string representation of the contents of the specified array.

CSE, KSIT, 2019-20 Page 122


Advanced Java & J2EE (17CS553) Study Material

Module-3
String and StringBuffer

Class String
java.lang.Object
o java.lang.String

All Implemented Interfaces:


Serializable, CharSequence, Comparable<String>

The general form is:

public final class String


extends Object
implements Serializable, Comparable<String>, CharSequence
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented
as instances of this class.

CSE, KSIT, 2019-20 Page 123


Advanced Java & J2EE (17CS553) Study Material

Strings are constant; their values cannot be changed after they are created. String buffers support
mutable strings. Because String objects are immutable they can be shared. For example:

String str = "abc";

is equivalent to:

char data[] = {'a', 'b', 'c'};


String str = new String(data);

Here are some more examples of how strings can be used:

System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);

The class String includes methods for examining individual characters of the sequence, for
comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string
with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode
Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for
conversion of other objects to strings. String concatenation is implemented through the
StringBuilder(or StringBuffer) class and its append method. String conversions are
implemented through the method toString, defined by Object and inherited by all classes in Java.
For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The
Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a
NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are
represented by surrogate pairs (see the section Unicode Character Representations in the Character
class for more information). Index values refer to char code units, so a supplementary character uses
two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in
addition to those for dealing with Unicode code units (i.e., char values).

Since:
JDK1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

o Field Summary

CSE, KSIT, 2019-20 Page 124


Advanced Java & J2EE (17CS553) Study Material

Fields
Modifier and Type Field and Description
CASE_INSENSITIVE_ORDER
static
Comparator<String>
A Comparator that orders String objects as by
compareToIgnoreCase.

o Constructor Summary

Constructors
Constructor and Description
String()
Initializes a newly created String object so that it represents an empty character sequence.
String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default
charset.
String(byte[] bytes, Charset charset)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(byte[] ascii, int hibyte)
Deprecated.
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred
way to do this is via the String constructors that take a Charset, charset name, or that use
the platform's default charset.
String(byte[] bytes, int offset, int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's
default charset.
String(byte[] bytes, int offset, int length, Charset charset)
Constructs a new String by decoding the specified subarray of bytes using the specified
charset.
String(byte[] ascii, int hibyte, int offset, int count)
Deprecated.
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred
way to do this is via the String constructors that take a Charset, charset name, or that use
the platform's default charset.
String(byte[] bytes, int offset, int length, String charsetName)
Constructs a new String by decoding the specified subarray of bytes using the specified
charset.
String(byte[] bytes, String charsetName)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained in
the character array argument.
String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array
argument.
String(int[] codePoints, int offset, int count)

CSE, KSIT, 2019-20 Page 125


Advanced Java & J2EE (17CS553) Study Material

Allocates a new String that contains characters from a subarray of the Unicode code point
array argument.
String(String original)
Initializes a newly created String object so that it represents the same sequence of characters
as the argument; in other words, the newly created string is a copy of the argument string.
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the
string buffer argument.
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the
string builder argument.

o Method Summary

Methods
Modifier and
Method and Description
Type
charAt(int index)
char
Returns the char value at the specified index.
codePointAt(int index)
int
Returns the character (Unicode code point) at the specified index.
codePointBefore(int index)
int
Returns the character (Unicode code point) before the specified index.
codePointCount(int beginIndex, int endIndex)
int Returns the number of Unicode code points in the specified text range of
this String.
compareTo(String anotherString)
int
Compares two strings lexicographically.
compareToIgnoreCase(String str)
int
Compares two strings lexicographically, ignoring case differences.
concat(String str)
String
Concatenates the specified string to the end of this string.
contains(CharSequence s)
boolean Returns true if and only if this string contains the specified sequence of char
values.
contentEquals(CharSequence cs)
boolean
Compares this string to the specified CharSequence.
contentEquals(StringBuffer sb)
boolean
Compares this string to the specified StringBuffer.
static copyValueOf(char[] data)
String Returns a String that represents the character sequence in the array

CSE, KSIT, 2019-20 Page 126


Advanced Java & J2EE (17CS553) Study Material

specified.
copyValueOf(char[] data, int offset, int count)
static
String
Returns a String that represents the character sequence in the array
specified.
endsWith(String suffix)
boolean
Tests if this string ends with the specified suffix.
equals(Object anObject)
boolean
Compares this string to the specified object.
equalsIgnoreCase(String anotherString)
boolean
Compares this String to another String, ignoring case considerations.
format(Locale l, String format, Object... args)
static
String
Returns a formatted string using the specified locale, format string, and
arguments.
static format(String format, Object... args)
String Returns a formatted string using the specified format string and arguments.
getBytes()
byte[] Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.
getBytes(Charset charset)
byte[] Encodes this String into a sequence of bytes using the given charset,
storing the result into a new byte array.
getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated.
void This method does not properly convert characters into bytes. As of JDK 1.1,
the preferred way to do this is via the getBytes() method, which uses the
platform's default charset.
getBytes(String charsetName)
byte[] Encodes this String into a sequence of bytes using the named charset,
storing the result into a new byte array.
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
void
Copies characters from this string into the destination character array.
hashCode()
int
Returns a hash code for this string.
indexOf(int ch)
int Returns the index within this string of the first occurrence of the specified
character.
indexOf(int ch, int fromIndex)
int Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
indexOf(String str)
int Returns the index within this string of the first occurrence of the specified
substring.
indexOf(String str, int fromIndex)
int Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
String intern()

CSE, KSIT, 2019-20 Page 127


Advanced Java & J2EE (17CS553) Study Material

Returns a canonical representation for the string object.


isEmpty()
boolean
Returns true if, and only if, length() is 0.
lastIndexOf(int ch)
int Returns the index within this string of the last occurrence of the specified
character.
lastIndexOf(int ch, int fromIndex)
int Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.
lastIndexOf(String str)
int Returns the index within this string of the last occurrence of the specified
substring.
lastIndexOf(String str, int fromIndex)
int Returns the index within this string of the last occurrence of the specified
substring, searching backward starting at the specified index.
length()
int
Returns the length of this string.
matches(String regex)
boolean
Tells whether or not this string matches the given regular expression.
offsetByCodePoints(int index, int codePointOffset)
int Returns the index within this String that is offset from the given index by
codePointOffset code points.
regionMatches(boolean ignoreCase, int toffset, String other,
boolean int ooffset, int len)
Tests if two string regions are equal.
regionMatches(int toffset, String other, int ooffset,
boolean int len)
Tests if two string regions are equal.
replace(char oldChar, char newChar)
String Returns a new string resulting from replacing all occurrences of oldChar in
this string with newChar.
replace(CharSequence target, CharSequence replacement)
String Replaces each substring of this string that matches the literal target sequence
with the specified literal replacement sequence.
replaceAll(String regex, String replacement)
String Replaces each substring of this string that matches the given regular
expression with the given replacement.
replaceFirst(String regex, String replacement)
String Replaces the first substring of this string that matches the given regular
expression with the given replacement.
split(String regex)
String[]
Splits this string around matches of the given regular expression.
split(String regex, int limit)
String[]
Splits this string around matches of the given regular expression.
startsWith(String prefix)
boolean
Tests if this string starts with the specified prefix.

CSE, KSIT, 2019-20 Page 128


Advanced Java & J2EE (17CS553) Study Material

startsWith(String prefix, int toffset)


boolean Tests if the substring of this string beginning at the specified index starts
with the specified prefix.
subSequence(int beginIndex, int endIndex)
CharSequence
Returns a new character sequence that is a subsequence of this sequence.
substring(int beginIndex)
String
Returns a new string that is a substring of this string.
substring(int beginIndex, int endIndex)
String
Returns a new string that is a substring of this string.
toCharArray()
char[]
Converts this string to a new character array.
toLowerCase()
String Converts all of the characters in this String to lower case using the rules of
the default locale.
toLowerCase(Locale locale)
String Converts all of the characters in this String to lower case using the rules of
the given Locale.
toString()
String
This object (which is already a string!) is itself returned.
toUpperCase()
String Converts all of the characters in this String to upper case using the rules of
the default locale.
toUpperCase(Locale locale)
String Converts all of the characters in this String to upper case using the rules of
the given Locale.
trim()
String
Returns a copy of the string, with leading and trailing whitespace omitted.
static valueOf(boolean b)
String Returns the string representation of the boolean argument.
static valueOf(char c)
String Returns the string representation of the char argument.
static valueOf(char[] data)
String Returns the string representation of the char array argument.
valueOf(char[] data, int offset, int count)
static
String
Returns the string representation of a specific subarray of the char array
argument.
static valueOf(double d)
String Returns the string representation of the double argument.
static valueOf(float f)
String Returns the string representation of the float argument.
static valueOf(int i)
String Returns the string representation of the int argument.
static valueOf(long l)
String Returns the string representation of the long argument.
static
valueOf(Object obj)
String

CSE, KSIT, 2019-20 Page 129


Advanced Java & J2EE (17CS553) Study Material

Returns the string representation of the Object argument.

 Methods inherited from class java.lang.Object


clone, finalize, getClass, notify, notifyAll, wait, wait, wait

java.lang

Class StringBuffer
java.lang.Object

o java.lang.StringBuffer

All Implemented Interfaces:


Serializable, Appendable, CharSequence

The general form is:

public final class StringBuffer


extends Object
implements Serializable, CharSequence

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
At any point in time it contains some particular sequence of characters, but the length and content of
the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so
that all the operations on any particular instance behave as if they occur in some serial order that is
consistent with the order of the method calls made by each of the individual threads involved.

The principal operations on a StringBuffer are the append and insert methods, which are
overloaded so as to accept data of any type. Each effectively converts a given datum to a string and
then appends or inserts the characters of that string to the string buffer. The append method always
adds these characters at the end of the buffer; the insert method adds the characters at a specified
point.

For example, if z refers to a string buffer object whose current contents are "start", then the method
call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4,
"le") would alter the string buffer to contain "starlet".

In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as
sb.insert(sb.length(), x).

Whenever an operation occurs involving a source sequence (such as appending or inserting from a
source sequence) this class synchronizes only on the string buffer performing the operation, not on
the source.

CSE, KSIT, 2019-20 Page 130


Advanced Java & J2EE (17CS553) Study Material

Every string buffer has a capacity. As long as the length of the character sequence contained in the
string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array.
If the internal buffer overflows, it is automatically made larger. As of release JDK 5, this class has
been supplemented with an equivalent class designed for use by a single thread, StringBuilder.
The StringBuilder class should generally be used in preference to this one, as it supports all of the
same operations but it is faster, as it performs no synchronization.

Since:
JDK1.0
StringBuilder, String, Serialized Form

o Constructor Summary

Constructors
Constructor and Description
StringBuffer()
Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(CharSequence seq)
Constructs a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(int capacity)
Constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)
Constructs a string buffer initialized to the contents of the specified string.

o Method Summary

Methods
Modifier and
Method and Description
Type
append(boolean b)
StringBuffer Appends the string representation of the boolean argument to the
sequence.
append(char c)
StringBuffer
Appends the string representation of the char argument to this sequence.
append(char[] str)
StringBuffer Appends the string representation of the char array argument to this
sequence.
append(char[] str, int offset, int len)
StringBuffer Appends the string representation of a subarray of the char array argument
to this sequence.
append(CharSequence s)
StringBuffer
Appends the specified CharSequence to this sequence.
append(CharSequence s, int start, int end)
StringBuffer
Appends a subsequence of the specified CharSequence to this sequence.

CSE, KSIT, 2019-20 Page 131


Advanced Java & J2EE (17CS553) Study Material

append(double d)
StringBuffer
Appends the string representation of the double argument to this sequence.
append(float f)
StringBuffer
Appends the string representation of the float argument to this sequence.
append(int i)
StringBuffer
Appends the string representation of the int argument to this sequence.
append(long lng)
StringBuffer
Appends the string representation of the long argument to this sequence.
append(Object obj)
StringBuffer
Appends the string representation of the Object argument.
append(String str)
StringBuffer
Appends the specified string to this character sequence.
append(StringBuffer sb)
StringBuffer
Appends the specified StringBuffer to this sequence.
appendCodePoint(int codePoint)
StringBuffer Appends the string representation of the codePoint argument to this
sequence.
capacity()
int
Returns the current capacity.
charAt(int index)
char
Returns the char value in this sequence at the specified index.
codePointAt(int index)
int
Returns the character (Unicode code point) at the specified index.
codePointBefore(int index)
int
Returns the character (Unicode code point) before the specified index.
codePointCount(int beginIndex, int endIndex)
int Returns the number of Unicode code points in the specified text range of
this sequence.
delete(int start, int end)
StringBuffer
Removes the characters in a substring of this sequence.
deleteCharAt(int index)
StringBuffer
Removes the char at the specified position in this sequence.
ensureCapacity(int minimumCapacity)
void
Ensures that the capacity is at least equal to the specified minimum.
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
void Characters are copied from this sequence into the destination character
array dst.
indexOf(String str)
int Returns the index within this string of the first occurrence of the specified
substring.
indexOf(String str, int fromIndex)
int Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
insert(int offset, boolean b)
StringBuffer
Inserts the string representation of the boolean argument into this

CSE, KSIT, 2019-20 Page 132


Advanced Java & J2EE (17CS553) Study Material

sequence.
insert(int offset, char c)
StringBuffer
Inserts the string representation of the char argument into this sequence.
insert(int offset, char[] str)
StringBuffer Inserts the string representation of the char array argument into this
sequence.
insert(int index, char[] str, int offset, int len)
StringBuffer Inserts the string representation of a subarray of the str array argument
into this sequence.
insert(int dstOffset, CharSequence s)
StringBuffer
Inserts the specified CharSequence into this sequence.
insert(int dstOffset, CharSequence s, int start, int end)
StringBuffer
Inserts a subsequence of the specified CharSequence into this sequence.
insert(int offset, double d)
StringBuffer
Inserts the string representation of the double argument into this sequence.
insert(int offset, float f)
StringBuffer
Inserts the string representation of the float argument into this sequence.
insert(int offset, int i)
StringBuffer Inserts the string representation of the second int argument into this
sequence.
insert(int offset, long l)
StringBuffer
Inserts the string representation of the long argument into this sequence.
insert(int offset, Object obj)
StringBuffer Inserts the string representation of the Object argument into this character
sequence.
insert(int offset, String str)
StringBuffer
Inserts the string into this character sequence.
lastIndexOf(String str)
int Returns the index within this string of the rightmost occurrence of the
specified substring.
lastIndexOf(String str, int fromIndex)
int Returns the index within this string of the last occurrence of the specified
substring.
length()
int
Returns the length (character count).
offsetByCodePoints(int index, int codePointOffset)
int Returns the index within this sequence that is offset from the given index
by codePointOffset code points.
replace(int start, int end, String str)
StringBuffer Replaces the characters in a substring of this sequence with characters in
the specified String.
reverse()
StringBuffer Causes this character sequence to be replaced by the reverse of the
sequence.
void setCharAt(int index, char ch)

CSE, KSIT, 2019-20 Page 133


Advanced Java & J2EE (17CS553) Study Material

The character at the specified index is set to ch.


setLength(int newLength)
void
Sets the length of the character sequence.
subSequence(int start, int end)
CharSequence
Returns a new character sequence that is a subsequence of this sequence.
substring(int start)
String Returns a new String that contains a subsequence of characters currently
contained in this character sequence.
substring(int start, int end)
String Returns a new String that contains a subsequence of characters currently
contained in this sequence.
toString()
String
Returns a string representing the data in this sequence.
trimToSize()
void
Attempts to reduce storage used for the character sequence.

 Methods inherited from class java.lang.Object


clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait,
wait, wait

String Constructors:
1. To create empty String, call the default constructor
String()
e.g. String s=new String();
will create an instance of String with no characters in it.

2. To create a String initialized by an array of characters, call


String(char chars[]) constructor
e.g. char chars[]={‗k‘,‘s‘,‘I‘,‘t‘};
String s=new String(chars);
This constructor initializes s with the string ―ksit‖.

3. To create a sub-range of a character array as an initialize, call


String(char chars[], int startIndex, int numChars) constructor, startIndex specifies the index at
which the subrange begins, and numChars specifies the number of characters to use.
e.g. char chars[]={‗k‘,‘s‘,‘I‘,‘t‘};
String s=new String(chars,1,3);
This initializes s with the characters sit.
4. To create a String object that contains the same character sequence as another String object, call
String(String obj) constructor.
e.g.
class MakeString
{

CSE, KSIT, 2019-20 Page 134


Advanced Java & J2EE (17CS553) Study Material

Public static void main(String args[])


{
char chars[]={‗k‘,‘s‘,‘I‘,‘t‘};
String s1=new String(chars);
String s2=new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output of the program is as follows:
ksit
ksit
Both s1 and s2 contains the same string.
5. Though Java‘s char type uses 16 bits to represent the basic Unicode character set, the typical format for strings
on the Internet uses arrays of 8-bit bytes constructed from ASCII character set. The String class provides
constructors that initializes a String when given a byte array. Their forms are:
String(byte asciiChars[])
String(byte asciiChars[], int StartIndex, int numChars)
e.g.
class SubStringCons
{
public static void main(String args[])
{
byte ascii[]={65,66,67,68,69,70};
String s1=new String(ascii);
System.out.println(s1);
String s2=new String(ascii,2,3);
System.out.println(s2);
}
}
The output of the program is shown below:
ABCDEF
CDE

String Length
The length of a string is a number of characters that it contains.
To obtain the length of the string, call the length() method.
The general form:
int length()
e.g. program

char chars[]={‗k‘,‘s‘,‘I‘,‘t‘};
String s1=new String(chars);
System.out.println(s1.length());

Outputs 4

CSE, KSIT, 2019-20 Page 135


Advanced Java & J2EE (17CS553) Study Material

Special String Operations


Automatic creation of new String instances from string literals.
Concatenation of multiple String objects by the use of + operator.
Conversion of other data types to a string representation.

Automatic creation of new String instances from String literals:


Java automatically constructs a String object for each string literal, thus a string literal can be used to
initialize a String object.
e.g. program
char chars[]={‗k‘,‘s‘,‘I‘,‘t‘};
String s1=new String(chars);

String s2=‖ksit‖; // use string literal


// can also call methods on a quoted string as if it were an object reference.
System.out.println(―ksit‖.length());

Concatenation of multiple String objects by the use of + operator:


In general Java does not allow operators to be applied o String objects. The one exception to this rule is the +
operator, which concatenates two strings, producing a String object as the result.
e.g. Program
String age=‖20‖;
String s=‖ksit is‖+age+‖years old.‖;
System.out.println(s);

o/ps: ksit is 20 years old.

Practical use of string concatenation:


when creating a very long string
e.g. program

String longStr=‖This could have been‖+


―a vey long line that could have been‖+
―wrapped around. But string concatenation ―+
―prevented this.‖;

System.out.println(longStr);

Conversion of other data types to a string representation:


Strings can be concatenated with other types of data.
e.g program-1

int age=20;
String s=‖ksit is‖+age+‖years old.‖;
System.out.println(s);

CSE, KSIT, 2019-20 Page 136


Advanced Java & J2EE (17CS553) Study Material

o/ps: ksit is 20 years old.

Here int is automatically converted into its string representation within a String object by the compiler when
the other operand of the + is an String instance.
e.g program-2
String s=‖four: ‖+2+2; //operator precedence and associativity is applied
System.out.println(s);

o/p: four:22

e.g program-3
String s=‖four: ‖+(2+2); //operator precedence and associativity is applied
System.out.println(s);

o/p: four:4

String Conversion and toString()


Java calls valueOf() method defined in String class when data are to be converted into its string
representation during concatenation.
This method is overloaded for all primitive types and for Object.
For primitive type valueOf() returns a string that contains human readable equivalent of the value
with which it was called.
For Objects, valueOf() calls toString() method on the object.

toString() method:
Every class implements toString() because it is defined by the Object.
toString() method can be overridden to provide own string representation.
The general form is:
String toString()

e.g. program
class Box
{
double width;
double height;
double depth;
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}

CSE, KSIT, 2019-20 Page 137


Advanced Java & J2EE (17CS553) Study Material

Public String toString()


{
return ―Dimensions are ―+width+‖ by ―+depth+‖ by ―+height+‖.‖;
}
}

Class toStringDemo
{
Public static void main(String args[])
{
Box b=new Box(10,12,14);
String s=‖Box b: ‖+b; //concatenate Box object
System.out.println(b); //convert Box to string
System.out.println(s);
}
}
o/p:
Dimensions are 10.0 by 14.0 by 12.0.
Box b: Dimensions are 10.0 by 14.0 by 12.0.

Character Extraction
The String class provides a number of ways in which characters can be extracted from a String object.
Methods: charAt(), getChars(), getBytes(), toCharArray()

Method charAt():
This method extracts a single character from a String.
The general form is:
char charAt(int where), where is the index of the character that is to be obtained. The value of
where must be nonnegative and specify a location within the string.
e.g. program

char ch;
ch=‖ksit‖.charAt(2);

assigns the value ―I‖ to ch.

Method getChars():
This method extracts more than one character at a time.
The general form is:
void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, sourceEnd specifies an index that is
one past the end of the desired substring. The array that will receive the characters is specified by target. The
index within the target at which the substring will be copied is passed in targetStart.

CSE, KSIT, 2019-20 Page 138


Advanced Java & J2EE (17CS553) Study Material

e.g. program

class getCharsDemo
{
Public static void main(String args[])
{
String s=‖This is a demo of the getChars method.‖;
Int start=10;
Int end=14;
char buf[]=new char[end-start];
s.getChars(start,end,buf,0);
System.out.println(buf);
}
}

Here is the output of the program:


Demo
Method getBytes()
This is alternate to getChars(), that stores the characters in an array of bytes.
This method uses the default character-to-byte conversion provided by the platform.
The general form is:
byte[] getBytes()

e.g program
class getBytesDemo
{
public static void main(String args[])
{
String s="KSIT";
byte buf[]=new byte[s.length()];
buf=s.getBytes();
for(int i=0;i<buf.length;i++)
System.out.print(buf[i]+" ");
}
}
o/p of the program is shown here
75 83 73 84

Method toCharArray()
This method converts all the characters in a String object into a character array.
The general form is:
char[] toCharArray()

CSE, KSIT, 2019-20 Page 139


Advanced Java & J2EE (17CS553) Study Material

e.g. program

class toCharArrayDemo
{
public static void main(String args[])
{
String s="KSIT";

char buf[]=new char[s.length()];


buf=s.toCharArray();
for(int i=0;i<buf.length;i++)
System.out.print(buf[i]+" ");
}
}
o/p of the program is shown here
KSIT

String Comparison
The String class include several methods that compare strings or substrings within strings.
Methods:
equals() and equalsIgnoreCase()
regionMatches()
startsWith() and endsWith()
equals() versus ==
compareTo()
Method equals() and equalsIgnoreCase():
To compare two strings for equality, use equals(). The general form is:
boolean equals(Object str)
To perform a comparison that ignores case differences, use equalsIgnoreCase(). The general form is:
boolean equalsIgnoreCase(Object str)
e.g. Program
class equalsDemo
{
public static void main(String[] args)
{
String s1="Hello";
String s2="Hello";
String s3="Good-bye";
String s4="HELLO";
System.out.println(s1+" equals "+s2+"-->"+s1.equals(s2));
System.out.println(s1+" equals "+s3+"-->"+s1.equals(s3));
System.out.println(s1+" equals "+s4+"-->"+s1.equals(s4));
System.out.println(s1+" equals "+s4+"-->"+s1.equalsIgnoreCase(s4));

}
}

CSE, KSIT, 2019-20 Page 140


Advanced Java & J2EE (17CS553) Study Material

o/p of the program is shown here


Hello equals Hello-->true
Hello equals Good-bye-->false
Hello equals HELLO-->false
Hello equals HELLO-->true

Method regionMatches():
This method compares a specific region inside a string with another specific region in another string.
The general forms are:
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase,int startIndex, String str2, int str2StartIndex, int
numChars)
e.g. program
class regionMatchesDemo
{
public static void main(String[] args)
{
String s1="Hello";
String s2="Hello";
String s3="Good-bye";
String s4="HELLO";
System.out.println("The specified string of s1 matches with s2‖+
―-->"+s1.regionMatches(1,s2,1,4));
System.out.println("The specified string of s1 matches with s3‖+
―-->"+s1.regionMatches(1,s3,1,4));
System.out.println("The specified string of s1 matches with s4 ignoreCase-false‖+
―-->"+s1.regionMatches(false,1,s4,1,4));
System.out.println("The specified string of s1 matches with s4 ignoreCase-true‖+
―-->"+s1.regionMatches(true,1,s4,1,4));
}
}
o/p of the program is shown here

The specified string of s1 matches with s2-->true


The specified string of s1 matches with s3-->false
The specified string of s1 matches with s4 ignoreCase-false-->false
The specified string of s1 matches with s4 ignoreCase-true-->true

Method startsWith() and endsWith():

These methods are more or less specialized form of regionMatches().


The startsWith() method determines whether a given String begins with a specified string.
The endsWith() method determines whether the String in question ends with a specified string.
The general forms are:
boolean startsWith(String str)
boolean endsWith(String str)

CSE, KSIT, 2019-20 Page 141


Advanced Java & J2EE (17CS553) Study Material

e.g program
class startsAndendsWithDemo
{
public static void main(String[] args)
{
String s1="Hello welcome to ksit";
String s2="Hello welcome to ksit";
String s3="Welcome to Bengaluru";

System.out.println("The specified string of s1 starts within s2-->"+s1.startsWith(s2));


System.out.println("The specified string of s1 starts within s3-->"+s1.startsWith(s3));
System.out.println("The specified string of s1 ends within s2-->"+s1.endsWith(s2));
System.out.println("The specified string of s1 ends within s3-->"+s1.endsWith(s3));

}
}
o/p of the program is shown here
The specified string of s1 starts within s2-->true
The specified string of s1 starts within s3-->false
The specified string of s1 ends within s2-->true
The specified string of s1 ends within s3-->false

equals method versus == operator

Both performs different opertations.


The equals() method compares the characters inside a String object.
The == operator compares two objects references to see whether they refer to the same instance.
e.g. program:

class EqualsNotEqualsTo
{
public static void main(String[] args)
{
String s1="Hello";
String s2=new String(s1);
System.out.println(s1+" equals "+s2+"-->"+s1.equals(s2));
System.out.println(s1+" == "+s2+"-->"+(s1==s2));

}
}

o/p of the program is shown here

Hello equals Hello-->true

CSE, KSIT, 2019-20 Page 142


Advanced Java & J2EE (17CS553) Study Material

Hello == Hello-->false

Method compareTo()

This method helps for sorting applications.


The general form is:
int compareTo(String str)

The following table shows the value returned by this method


Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.

e.g. program

//Bubble sort for strings

class SortStrings
{
static String arr[]={"Welcome","to","ksit","it","is","near","to","metro","station"};
public static void main(String[] args)
{
int i=0,j=0;
for(i=0;i<arr.length-1;i++)
{
for(j=i;j<arr.length-i-1;j++)
{
if(arr[j].compareTo(arr[j+1])>0)
{
String str=arr[j+1];
arr[j+1]=arr[j];
arr[j]=str;
}
}
System.out.println(arr[i]);
}
System.out.println(arr[i]);
}
}
o/p of the program is shown here
Welcome

CSE, KSIT, 2019-20 Page 143


Advanced Java & J2EE (17CS553) Study Material

it
is
ksit
metro
near
station
to
to
Searching Strings
Methods:

indexOf()- Searches for the first occurrence of a character or substring.


lastIndexOf()- Searches for the last occurrence of a character or substring.

o These two methods are overloaded.


o In all cases, the methods return the index at which the character or substring was found, or -1
on failure.
To search for the first occurrence of a character:
int indexOf(int ch)- Searches for the first occurrence of a character.
int lastIndexOf(int ch)- Searches for the last occurrence of a character.
int indexOf(String str)- Searches for the first occurrence of a substring, str specifies a substring.
int lastIndexOf(String str)- Searches for the last occurrence of a substring, str specifies a
substring.
int indexOf(int ch, int startIndex)- startIndex specify a starting point for the search.
int lastIndexOf(ch, int startIndex)- startIndex specify a starting point for the search.
int indexOf(String str, int startIndex)- str specifies a substring and startIndex specify a starting
point for the search.
int lastIndexOf(String str, int startIndex)- str specifies a substring and startIndex specify a
starting point for the search.

Note: For indexOf(), the search runs from startIndex to the end of the string. For lastIndexOf(), the
search runs from startIndex to zero.

Example program:

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

String s="Now is the time for all good men "+


"to come to the aid of their country.";
System.out.println(s);

CSE, KSIT, 2019-20 Page 144


Advanced Java & J2EE (17CS553) Study Material

System.out.println("indexOf(t): "+s.indexOf('t'));
System.out.println("lastIndexOf(t): "+s.lastIndexOf('t'));
System.out.println("indexOf(the): "+s.indexOf("the"));
System.out.println("lastIndexOf(the): "+s.lastIndexOf("the"));
System.out.println("indexOf(t,10): "+s.indexOf('t',10));
System.out.println("lastIndexOf(t,60): "+s.lastIndexOf('t',60));
System.out.println("indexOf(the,10): "+s.indexOf("the",10));
System.out.println("lastIndexOf(the,60): "+s.lastIndexOf("the",60));
}
}

The output of the program is shown here:


Now is the time for all good men to come to the aid of their country.
indexOf(t): 7
lastIndexOf(t): 65
indexOf(the): 7
lastIndexOf(the): 55
indexOf(t,10): 11
lastIndexOf(t,60): 55
indexOf(the,10): 44
lastIndexOf(the,60): 55

Modifying a String
Because String objects are immutable and whenever if it need to be modified, then it must be copied
into either a StringBuffer or StrinBuilder, or use one of the following methods, which will construct
a new copy of the string with the complete modifications.
Methods: substring(), concat(), replace(), trim().

substring() method:

A substring can be extracted by using this method. It has two forms as shown below
String substring(int startIndex)- startIndex specifies the index at which the substring will begin. This
form returns a copy of the substring that begins at startIndex and runs to the end of the invoking
string.
String substring(int startIndex, int endIndex)-startIndex specifies the beginning index, and endIndex
specifies the stopping point. The string returned contains all characters from the beginning index,
upto, but not including, the ending index.
Program Example:

class SubStringDemo
{
public static void main(String[] args)
{
String org="This is a test. This is, too.";
String search="is";
String sub="was";
String result="";
int i;

CSE, KSIT, 2019-20 Page 145


Advanced Java & J2EE (17CS553) Study Material

do
{
System.out.println(org);
i=org.indexOf(search);
if(i!=-1)
{
result=org.substring(0,i);
result+=sub;
result+=org.substring(i+search.length());
org=result;
}
}
while (i!=-1);
}
}

The output of the program is shown here:


This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.

concat() method

Two strings can be concatenated.


The general form is
o String concat(String str).
o This method creates a new object that contains the invoking string with the contents od str
appended to the end.
o concat() performs the same function of + operator.
Example Program:

String s1=‖one‖;
String s2=s1.concat(―two‖);// puts the string ―onetwo‖ into s2.

replace() method
This method has two forms:
o String replace(char original, char replacement)- here, original specifies the character to be
replaced by the character specified by replacement. The resulting string is returned.
 E.g. String s=‖Hello‖.replace(‗l‘,‘w‘); puts the string ―Hewwo‖ into s.
o String replace(CharSequence original, CharSequence replacement)- replaces one character
sequence with another.
Example Program:
class ReplaceDemo
{
public static void main(String[] args)
{
String s1="abcdabcd";
System.out.println("Original String: "+s1);

CSE, KSIT, 2019-20 Page 146


Advanced Java & J2EE (17CS553) Study Material

String s2=s1.replace('a','e');
System.out.println("After replacing a with e: "+s2);
s2=s2.replace("cd","a");
System.out.println("After replacing cd with a:"+s2);
}
}

The output of the program is shown here:


Original String: abcdabcd
After replacing a with e: ebcdebcd
After replacing cd with a: ebaeba

trim() method

This method returns a copy of the invoking string from which any leading and trailing whitespace
has been removed.
The general form is:
o String trim()
 E.g String s=‖ Hello World ―.trim(); puts the string ―Hello World‖ into s.

Data Conversion using valueOf()


This method converts data from its internal format into a human-readable form.
Few forms of this method:
o static String valueOf(double num)
o static String valueOf(long num)
o static String valueOf(Object obj)
o static String valueOf(char chars[])
o static String valueOf(char chars[], int startIndex, int numChars)

Example Program

class valueOfDemo
{
public static void main(String[] args)
{
int a[]={1,2,3};
char c[]={'k','s','i','t'};
System.out.println(String.valueOf(a));
System.out.println(String.valueOf(c));
System.out.println(String.valueOf(c,1,3));
}
}
The output of the program is shown here:
[I@186d4c1
ksit
sit

Note: In the above output, the first line is a cryptic string, which indicates that it is an array of some type.
CSE, KSIT, 2019-20 Page 147
Advanced Java & J2EE (17CS553) Study Material

Changing the case of Characters within a String


Methods:
String toLowerCase()- converts all the characters in a string from uppercase to lowercase.
e.g. System.out.println(―THIS IS A TEST‖.toLowerCase()); output string is ―this is a test‖

String toUpperCase()-converts all the characters in a string from lowercase to uppercase.


e.g. System.out.println(―this is a test‖.toUpperCase()); output string is ―THIS IS A TEST‖

StringBuffer
Is a peer class of String that provides each functionality of strings.
String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents
growable and writeable character sequences.
StringBuffer may have characters and substrings inserted in the middle or append to the end.
StrinBuffer will automatically grow to make room for such additions and often has more characters
pre-allocated than are actually needed, to allow room for growth.

StringBuffer Constructors

Constructors
Constructor and Description
StringBuffer()
Constructs a string buffer with no characters in it and an initial capacity of 16 characters
without reallocation.
StringBuffer(CharSequence seq)
Constructs a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(int capacity)
Constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)
Constructs a string buffer initialized to the contents of the specified string and reserves room
for 16 more characters without reallocation.

Methods and Programs

length() and capacity():


Their general forms are shown below

CSE, KSIT, 2019-20 Page 148


Advanced Java & J2EE (17CS553) Study Material

length()
int
Returns the length (character count).
capacity()
int
Returns the current capacity/ total allocated capacity
Example Program:

class SBDemo1
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("Hello");
System.out.println("buffer= "+s);
System.out.println("length= "+s.length());
System.out.println("capacity= "+s.capacity());
}
}
The output of the program is shown here:
buffer= Hello
length= 5
capacity= 21

ensureCapacity():
This method allows to pre-allocate room for a certain number of characters after a StringBuffer
has been constructed.
This method will be useful if a large number of small strings will be appending to a StringBuffer.

The general form is shown below

ensureCapacity(int minimumCapacity)
void Ensures that the capacity is at least equal to the specified minimum. minimumCapacity
specifies the size of the buffer.

setLength():
This method set the length of the string within a StringBuffer object.
The general form is shown below:

setLength(int newLength)
void
Sets the length of the character sequence. The value should be nonnegative
When the string size is increased, null characters are added to the end.
If this method is called with a value less than the current value returned by the length(), then the
characters stored beyond the new length will be lost.

charAt() and setCharAt():


The value of a single character can be obtained or set using these methods respectively.
The general form is show below:

CSE, KSIT, 2019-20 Page 149


Advanced Java & J2EE (17CS553) Study Material

charAt(int index)
char
Returns the char value in this sequence at the specified index.
setCharAt(int index, char ch)
void
The character at the specified index is set to ch.

Example Program
class SetCharAtDemo
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("Hello");
System.out.println("buffer before: "+s);
System.out.println("charAt(1) before: "+s.charAt(1));
s.setCharAt(1,'i');
System.out.println("buffer after setCharAt(1): "+s);
s.setLength(2);
System.out.println("buffer after setLength(2): "+s);
System.out.println("CharAt(1): "+s.charAt(1));
}
}
The output of the program is shown here
buffer before: Hello
charAt(1) before: e
buffer after setCharAt(1): Hillo
buffer after setLength(2): Hi
CharAt(1): i

getChars():
This method is used to copy a substring of a StringBuffer into an array.
The general form is shown below:
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
void
Characters are copied from this sequence into the destination character array dst.
append():
This method concatenates the string representation of any other type of data to the end of the
invoking StringBuffer object.
It has several overloaded versions. Following are some of the forms:

append(CharSequence s)
StringBuffer
Appends the specified CharSequence to this sequence.
append(CharSequence s, int start, int end)
StringBuffer
Appends a subsequence of the specified CharSequence to this sequence.
append(double d)
StringBuffer
Appends the string representation of the double argument to this sequence.
append(float f)
StringBuffer
Appends the string representation of the float argument to this sequence.
StringBuffer append(int i)

CSE, KSIT, 2019-20 Page 150


Advanced Java & J2EE (17CS553) Study Material

Appends the string representation of the int argument to this sequence.


append(long lng)
StringBuffer
Appends the string representation of the long argument to this sequence.
append(Object obj)
StringBuffer
Appends the string representation of the Object argument.
append(String str)
StringBuffer
Appends the specified string to this character sequence.
append(StringBuffer sb)
StringBuffer
Appends the specified StringBuffer to this sequence.

String.valueOf() is called (excluding CharacterSequence, String, StringBuffer parameters)for each


parameter to obtain its string representation.
The append() method is most often called when the + operator is used on String objects.
Java automatically changes modifications to a String instance into similar operations on a
StringBuffer instance.
Thus, a concatenation invokes append() on a StringBuffer object.
After the concatenation has been performed, the compiler inserts a call toString() to turn the
modifiable StringBuffer back into a constant String.

insert():
This method inserts one string into another.
It has overloaded methods. Some of the overloaded methods are shown below
insert(int offset, boolean b)
StringBuffer
Inserts the string representation of the boolean argument into this sequence.
insert(int offset, char c)
StringBuffer
Inserts the string representation of the char argument into this sequence.
insert(int offset, char[] str)
StringBuffer
Inserts the string representation of the char array argument into this sequence.
insert(int index, char[] str, int offset, int len)
StringBuffer Inserts the string representation of a subarray of the str array argument into this
sequence.
insert(int dstOffset, CharSequence s)
StringBuffer
Inserts the specified CharSequence into this sequence.
insert(int dstOffset, CharSequence s, int start, int end)
StringBuffer
Inserts a subsequence of the specified CharSequence into this sequence.
insert(int offset, double d)
StringBuffer
Inserts the string representation of the double argument into this sequence.
insert(int offset, float f)
StringBuffer
Inserts the string representation of the float argument into this sequence.
insert(int offset, int i)
StringBuffer
Inserts the string representation of the second int argument into this sequence.
insert(int offset, long l)
StringBuffer
Inserts the string representation of the long argument into this sequence.

CSE, KSIT, 2019-20 Page 151


Advanced Java & J2EE (17CS553) Study Material

insert(int offset, Object obj)


StringBuffer Inserts the string representation of the Object argument into this character
sequence.
insert(int offset, String str)
StringBuffer
Inserts the string into this character sequence.

Example Program:
class InsertDemo
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("God great");
System.out.println("buffer before: "+s);
s.insert(3," is");
System.out.println("buffer after: "+s);
}
}
The output of the program is shown here

buffer before: God great


buffer after: God is great

reverse():
This method reverses the characters within a StringBuffer object.
The general form is shown below:
reverse()
StringBuffer
Causes this character sequence to be replaced by the reverse of the sequence.

Example Program
class ReverseDemo
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("RAMA");
System.out.println("buffer before: "+s);
s.reverse();
System.out.println("buffer after: "+s);
}
}

The output of the program is shown here:


buffer before: RAMA
buffer after: AMAR

delete() and deleteCharAt():

These methods are used to delete characters within a StringBuffer.


The general form are shown below:

CSE, KSIT, 2019-20 Page 152


Advanced Java & J2EE (17CS553) Study Material

delete(int start, int end)


StringBuffer
Removes the characters in a substring of this sequence.
deleteCharAt(int index)
StringBuffer
Removes the char at the specified position in this sequence.

Example Program

class DeleteDemo
{
public static void main(String[] args)
{
String str="motor and hotel";
StringBuffer s=new StringBuffer(str);
s.delete(s.indexOf("tor"),s.indexOf("tel"));
System.out.println("Portmanteau word of motor and hotel is:"+s);
s.deleteCharAt(s.length()-1);
System.out.println(s+" is a small particle.");
}
}

The output of the program is shown here

Portmanteau word of motor and hotel is:motel


mote is a small particle.

replace():

This method replaces one set of characters with another set inside a StringBuffer object.
The general form is shown below:
replace(int start, int end, String str)
StringBuffer Replaces the characters in a substring of this sequence with characters in the
specified String.

Example Program
class SBReplaceDemo
{
public static void main(String[] args)
{

StringBuffer s=new StringBuffer("I eat apple");


System.out.println("buffer before: "+s);
s.replace(2,5,"ate");
System.out.println("buffer after: "+s);
}
}

The output of the program is shown here


buffer before: I eat apple
buffer after: I ate apple
CSE, KSIT, 2019-20 Page 153
Advanced Java & J2EE (17CS553) Study Material

substring():
This method returns a portion of a StringBuffer.
The general forms are:

substring(int start)
String Returns a new String that contains a subsequence of characters currently contained in
this character sequence.
substring(int start, int end)
String Returns a new String that contains a subsequence of characters currently contained in
this sequence.

Example Program
class SBSubStringDemo
{
public static void main(String[] args)
{
String str="Computer";
StringBuffer s=new StringBuffer(str);
String s1=s.substring(3);
System.out.println(s1+" is a slang of the word "+str);
String s2=s.substring(0,4);
System.out.println(s2+" is a command in some OS for comparing 2 files");
}
}

The output of the program is show here

puter is a slang of the word Computer


Comp is a command in some OS for comparing 2 files

CSE, KSIT, 2019-20 Page 154


Advanced Java & J2EE (17CS553) Study Material

Module-4
Java Servlets and Java Server Pages
Java Servlet Technology

Shortly after the Web began to be used for delivering services, service providers recognized the need for
dynamic content. Applets, one of the earliest attempts toward this goal, focused on using the client platform
to deliver dynamic user experiences. At the same time, developers also investigated using the server
platform for the same purpose. Initially, Common Gateway Interface (CGI) server-side scripts were the main
technology used to generate dynamic content. Although widely used, CGI scripting technology had many
shortcomings, including platform dependence and lack of scalability. To address these limitations, Java
Servlet technology was created as a portable way to provide dynamic, user-oriented content.

CSE, KSIT, 2019-20 Page 155


Advanced Java & J2EE (17CS553) Study Material

Java Servlet Technology

Java servlet technology lets you define HTTP-specific servlet classes. A servlet class extends the capabilities
of servers that host applications that are accessed by way of a request-response programming model.
Although servlets can respond to any type of request, they are commonly used to extend the applications
hosted by web servers.

Web server
A web server is server software, or hardware dedicated to running said software, that can satisfy World
Wide Web client requests. A web server can, in general, contain one or more websites. A web server
processes incoming network requests over HTTP and several other related protocols.

The primary function of a web server is to store, process and deliver web pages to clients. The
communication between client and server takes place using the Hypertext Transfer Protocol (HTTP). Pages
delivered are most frequently HTML documents, which may include images, style sheets and scripts in
addition to the text content.

A user agent, commonly a web browser or web crawler, initiates communication by making a request for a
specific resource using HTTP and the server responds with the content of that resource or an error message
if unable to do so. The resource is typically a real file on the server's secondary storage, but this is not
necessarily the case and depends on how the web server is implemented.

While the primary function is to serve content, a full implementation of HTTP also includes ways of
receiving content from clients. This feature is used for submitting web forms, including uploading of files.

Many generic web servers also support server-side scripting using Active Server Pages (ASP), PHP
(Hypertext Preprocessor), or other scripting languages. This means that the behaviour of the web server can
be scripted in separate files, while the actual server software remains unchanged. Usually, this function is
used to generate HTML documents dynamically ("on-the-fly") as opposed to returning static documents.
The former is primarily used for retrieving or modifying information from databases. The latter is typically
much faster and more easily cached but cannot deliver dynamic content.

Web servers can frequently be found embedded in devices such as printers, routers, webcams and serving
only a local network. The web server may then be used as a part of a system for monitoring or administering
the device in question. This usually means that no additional software has to be installed on the client
computer since only a web browser is required (which now is included with most operating systems).

Web container
A web container (also known as a servlet container; and compare "webcontainer") is the component of a
web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of
servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access-
rights.

A web container handles requests to servlets, JavaServer Pages (JSP) files, and other types of files that
include server-side code. The Web container creates servlet instances, loads and unloads servlets, creates
and manages request and response objects, and performs other servlet-management tasks.

CSE, KSIT, 2019-20 Page 156


Advanced Java & J2EE (17CS553) Study Material

A web container implements the web component contract of the Java EE architecture. This architecture
specifies a runtime environment for additional web components, including security, concurrency, lifecycle
management, transaction, deployment, and other services.

List of Servlet containers

he following is a list of applications which implement the Java Servlet specification from Sun Microsystems,
divided depending on whether they are directly sold or not.

Open source Web containers

Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available under the Apache
Software License.
o Apache Tomcat 6 and above are operable as general application container (prior versions were web
containers only)
Apache Geronimo is a full Java EE 6 implementation by Apache Software Foundation.
Enhydra, from Lutris Technologies.
GlassFish from Oracle (an application server, but includes a web container).
Jetty, from the Eclipse Foundation. Also supports SPDY and WebSocket protocols.
Jaminid contains a higher abstraction than servlets.
Payara is another application server, derived from Glassfish.
Winstone supports specification v2.5 as of 0.9, has a focus on minimal configuration and the ability to strip
the container down to only what you need.
Tiny Java Web Server (TJWS) 2.5, small footprint, modular design.
Virgo from Eclipse Foundation provides modular, OSGi based web containers implemented using embedded
Tomcat and Jetty. Virgo is available under the Eclipse Public License.
WildFly (formerly JBoss Application Server) is a full Java EE implementation by Red Hat, division JBoss.

Commercial Web containers

iPlanet Web Server, from Oracle.


JBoss Enterprise Application Platform from Red Hat, division JBoss is subscription-based/open-source Java
EE-based application server.
JRun, from Adobe Systems (formerly developed by Allaire Corporation).
WebLogic Application Server, from Oracle Corporation (formerly developed by BEA Systems).
Orion Application Server, from IronFlare.
Resin Pro, from Caucho Technology.
ServletExec, from New Atlanta Communications.
IBM WebSphere Application Server.
SAP NetWeaver.
tc Server, from SpringSource Inc.

Apache Tomcat

―The Apache Tomcat software is an open source implementation of the Java Servlet, JavaServer Pages, Java
Expression Language and Java WebSocket technologies.

CSE, KSIT, 2019-20 Page 157


Advanced Java & J2EE (17CS553) Study Material

Apache Tomcat software powers numerous large-scale, mission-critical web applications across a diverse range of
industries and organizations.

Apache Tomcat (also referred to as Tomcat Server) implements several Java EE specifications including
Java Servlet, JavaServer Pages (JSP), Java EL, and WebSocket, and provides a "pure Java" HTTP web
server environment in which Java code can run.

Tomcat is developed and maintained by an open community of developers under the auspices of the Apache
Software Foundation, released under the Apache License 2.0 license, and is open-source software.

Components

Tomcat 4.x was released with Catalina (a servlet container), Coyote (an HTTP connector) and Jasper (a JSP engine).

Catalina

Catalina is Tomcat's servlet container. Catalina implements Sun Microsystems's specifications for servlet
and JavaServer Pages (JSP). In Tomcat, a Realm element represents a "database" of usernames, passwords,
and roles (similar to Unix groups) assigned to those users. Different implementations of Realm allow
Catalina to be integrated into environments where such authentication information is already being created
and maintained, and then use that information to implement Container Managed Security as described in the
Servlet Specification.

Coyote

Coyote is a Connector component for Tomcat that supports the HTTP 1.1 protocol as a web server. This
allows Catalina, nominally a Java Servlet or JSP container, to also act as a plain web server that serves local
files as HTTP documents.[3] Coyote listens for incoming connections to the server on a specific TCP port
and forwards the request to the Tomcat Engine to process the request and send back a response to the
requesting client. Another Coyote Connector, Coyote JK, listens similarly but instead forwards its requests
to another web server, such as Apache, using the JK protocol.[4] This usually offers better performance.

Jasper

Jasper is Tomcat's JSP Engine. Jasper parses JSP files to compile them into Java code as servlets (that can
be handled by Catalina). At runtime, Jasper detects changes to JSP files and recompiles them.

As of version 5, Tomcat uses Jasper 2, which is an implementation of the Sun Microsystems's JSP 2.0
specification. From Jasper to Jasper 2, important features were added:

JSP Tag library pooling - Each tag markup in JSP file is handled by a tag handler class. Tag handler class
objects can be pooled and reused in the whole JSP servlet.
Background JSP compilation - While recompiling modified JSP Java code, the older version is still available
for server requests. The older JSP servlet is deleted once the new JSP servlet has finished being recompiled.
Recompile JSP when included page changes - Pages can be inserted and included into a JSP at runtime. The
JSP will not only be recompiled with JSP file changes but also with included page changes.
JDT Java compiler - Jasper 2 can use the Eclipse JDT (Java Development Tools) Java compiler instead of Ant
and javac.
Three new components were added with the release of Tomcat 7:
CSE, KSIT, 2019-20 Page 158
Advanced Java & J2EE (17CS553) Study Material

Cluster
This component has been added to manage large applications. It is used for load balancing that can
be achieved through many techniques. Clustering support currently requires the JDK version 1.5 or
higher.
High availability
A high-availability feature has been added to facilitate the scheduling of system upgrades (e.g. new
releases, change requests) without affecting the live environment. This is done by dispatching live
traffic requests to a temporary server on a different port while the main server is upgraded on the
main port. It is very useful in handling user requests on high-traffic web applications.
Web application
It has also added user- as well as system-based web applications enhancement to add support for
deployment across the variety of environments. It also tries to manage sessions as well as
applications across the network.
Tomcat is building additional components. A number of additional components may be used with
Apache Tomcat. These components may be built by users should they need them or they can be
downloaded from one of the mirrors.

Web Application
In computing, a web application or web app is a client–server computer program which the client (including
the user interface and client-side logic) runs in a web browser. Common web applications include webmail,
online retail sales, and online auction.
Web applications use web documents written in a standard format such as HTML and JavaScript, which are
supported by a variety of web browsers. Web applications can be considered as a specific variant of client–
server software where the client software is downloaded to the client machine when visiting the relevant web
page, using standard procedures such as HTTP. Client web software updates may happen each time the web
page is visited. During the session, the web browser interprets and displays the pages, and acts as the universal
client for any web application.

Java servlet
A Java servlet is a Java software component that extends the capabilities of a server. Although servlets can respond to
many types of requests, they most commonly implement web containers for hosting web applications on web servers
and thus qualify as a server-side servlet web API. Such web servlets are the Java counterpart to other dynamic web
content technologies such as PHP and ASP.NET.

Introduction

A Java servlet processes or stores a Java class in Java EE that conforms to the Java Servlet API,[1] a standard for
implementing Java classes that respond to requests. Servlets could in principle communicate over any client–server
protocol, but they are most often used with the HTTP. Thus "servlet" is often used as shorthand for "HTTP servlet".
Thus, a software developer may use a servlet to add dynamic content to a web server using the Java platform. The
generated content is commonly HTML, but may be other data such as XML and more commonly, JSON. Servlets can
maintain state in session variables across many server transactions by using HTTP cookies, or URL mapping.

o deploy and run a servlet, a web container must be used. A web container (also known as a servlet
container) is essentially the component of a web server that interacts with the servlets. The web container is
responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that
the URL requester has the correct access rights.
CSE, KSIT, 2019-20 Page 159
Advanced Java & J2EE (17CS553) Study Material

The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of the
web container and a servlet.

A Servlet is an object that receives a request and generates a response based on that request. The basic Servlet
package defines Java objects to represent servlet requests and responses, as well as objects to reflect the
servlet's configuration parameters and execution environment. The package javax.servlet.http defines HTTP-
specific subclasses of the generic servlet elements, including session management objects that track multiple
requests and responses between the web server and a client. Servlets may be packaged in a WAR file as a
web application.

Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler. The
difference between servlets and JSP is that servlets typically embed HTML inside Java code, while JSPs
embed Java code in HTML. While the direct usage of servlets to generate HTML has become rare, the
higher level MVC web framework in Java EE (JSF) still explicitly uses the servlet technology for the low
level request/response handling via the FacesServlet. A somewhat older usage is to use servlets in conjunction
with JSPs in a pattern called "Model 2", which is a flavor of the model–view–controller.

The current version of Servlet is 4.0.

Life cycle of a servlet

Three methods are central to the life cycle of a servlet. These are init(), service(), and destroy(). They are
implemented by every servlet and are invoked at specific times by the server.

During initialization stage of the servlet life cycle, the web container initializes the servlet instance
by calling the init() method, passing an object implementing the javax.servlet.ServletConfig interface.
This configuration object allows the servlet to access name-value initialization parameters from the
web application.
After initialization, the servlet instance can service client requests. Each request is serviced in its
own separate thread. The web container calls the service() method of the servlet for every request. The
service() method determines the kind of request being made and dispatches it to an appropriate method
to handle the request. The developer of the servlet must provide an implementation for these
methods. If a request is made for a method that is not implemented by the servlet, the method of the
parent class is called, typically resulting in an error being returned to the requester.
Finally, the web container calls the destroy() method that takes the servlet out of service. The destroy()
method, like init(), is called only once in the lifecycle of a servlet.

The following is a typical user scenario of these methods.

1. Assume that a user requests to visit a URL.


o The browser then generates an HTTP request for this URL.
o This request is then sent to the appropriate server.
2. The HTTP request is received by the web server and forwarded to the servlet container.
o The container maps this request to a particular servlet.
o The servlet is dynamically retrieved and loaded into the address space of the container.
3. The container invokes the init() method of the servlet.
o This method is invoked only when the servlet is first loaded into memory.
o It is possible to pass initialization parameters to the servlet so that it may configure itself.
4. The container invokes the service() method of the servlet.
o This method is called to process the HTTP request.

CSE, KSIT, 2019-20 Page 160


Advanced Java & J2EE (17CS553) Study Material

o The servlet may read data that has been provided in the HTTP request.
o The servlet may also formulate an HTTP response for the client.
5. The servlet remains in the container's address space and is available to process any other HTTP
requests received from clients.
o The service() method is called for each HTTP request.
6. The container may, at some point, decide to unload the servlet from its memory.
o The algorithms by which this decision is made are specific to each container.
7. The container calls the servlet's destroy() method to relinquish any resources such as file handles that
are allocated for the servlet; important data may be saved to a persistent store.
8. The memory allocated for the servlet and its objects can then be garbage collected.

Diagrams

CSE, KSIT, 2019-20 Page 161


Advanced Java & J2EE (17CS553) Study Material

CSE, KSIT, 2019-20 Page 162


Advanced Java & J2EE (17CS553) Study Material

CSE, KSIT, 2019-20 Page 163


Advanced Java & J2EE (17CS553) Study Material

Servlets:
Servlets are small programs that execute on the server side of a web connection.
Just as applets extend the functionality of a web browser, servlets dynamically extends the
functionality of a web server.

Advantages of Servlets in comparison with CGI technology

Performance: It is significantly better. Servlets executes within the address space of a web server. It is not
necessary to create a separate process to handle each client request.

Platform-independent: Java servlets are written in Java.

Server Resource Protection: The Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine.

Java Libraries & Communication: The full functionality of the Java class libraries is available to a servlet;
thereby servlets can communicate with applets, databases, or other software via the sockets and Remote
Method Invocation (RMI) mechanisms.

The Life Cycle of a Servlet


Three methods are central to the life cycle of a servlet. These are:

 init()
 service()
 destroy()

The above methods are implemented by every servlet and are invoked at a specific times by the server.

CSE, KSIT, 2019-20 Page 164


Advanced Java & J2EE (17CS553) Study Material

The following steps illustrates a typical user scenario to understand when these methods are called.

1. First, assume that a user enters a Uniform Resource Locator (URL) to a web browser. The browser
then generates ah HTTP (Hypertext Transfer Protocol) request for this URL. This request is then sent
to the appropriate server.
2. Second, this HTTP request is received by the web server. The server maps this request to a particular
servlet. The servlet is dynamically retrieved and loaded into the address space of the server.
3. Third, the server invokes the init() method of the servlet. This method is invoked only when the
servlet is first loaded into memory. It is possible to pass initialization parameters to the servlets so it
may configure itself.
4. Fourth, the server invokes the service() method of the servlet. This method is called to process the
HTTP request. It is possible for the servlet to read data that has been provided in the HTTP request.
It may also formulate an HTTP response for the client. The servlet remains in the server‘s address
space and is available to process any other HTTP requests received from clients. The service()
method is called for each HTTP request.
5. Finally, the server may decide to unload the servlet from its memory. The algorithms by which this
determination is made are specific to each server. The server calls the destroy() method to relinquish
any resources such as file handles that are allocated for the servlet. Important data may be saved to a
persistent store. The memory allocated for the servlet and its objects can then be garbage collected.

Using Tomcat for Servlet Development


Tomcat is an open source product maintained by the Jakarta Project of the Apache Software Foundation. It
contains the class libraries, documentation, and run time support that is needed to create and test servlet.

The Servlet API


Two packages contains the classes and interfaces that are required to build servlets. These are javax.servlet
and javax.servlet.http. They constitute the servlet API. These packages are not part of the Java core
packages. Instead, they are standard extensions provided by Tomcat.

The javax.servlet Package


The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between a
servlet class and the runtime environment provided for an instance of such a class by a conforming servlet container.

Interface Summary
A filter is an object that performs filtering tasks on either the request to a
Filter resource (a servlet or static content), or on the response from a resource, or
both.

A FilterChain is an object provided by the servlet container to the developer


FilterChain
giving a view into the invocation chain of a filtered request for a resource.

FilterConfig A filter configuration object used by a servlet container to pass information

CSE, KSIT, 2019-20 Page 165


Advanced Java & J2EE (17CS553) Study Material

to a filter during initialization.

Defines an object that receives requests from the client and sends them to
RequestDispatcher
any resource (such as a servlet, HTML file, or JSP file) on the server.

 Servlet Defines methods that all servlets must implement.

A servlet configuration object used by a servlet container to pass


 ServletConfig
information to a servlet during initialization.

Defines a set of methods that a servlet uses to communicate with its servlet
 ServletContext container, for example, to get the MIME type of a file, dispatch requests, or
write to a log file.

Implementations of this interface receive notifications of changes to the


ServletContextAttributeListener
attribute list on the servlet context of a web application.

Implementations of this interface receive notifications about changes to the


ServletContextListener
servlet context of the web application they are part of.

 ServletRequest Defines an object to provide client request information to a servlet.

A ServletRequestAttributeListener can be implemented by the developer


ServletRequestAttributeListener
interested in being notified of request attribute changes.

A ServletRequestListener can be implemented by the developer interested in


ServletRequestListener
being notified of requests coming in and out of scope in a web component.

 ServletResponse Defines an object to assist a servlet in sending a response to the client.

SingleThreadModel Deprecated. As of Java Servlet API 2.4, with no direct replacement.

Class Summary
 GenericServlet Defines a generic, protocol-independent servlet.

This is the event class for notifications about changes to the attributes of the
ServletContextAttributeEvent
servlet context of a web application.

This is the event class for notifications about changes to the servlet context of a
ServletContextEvent
web application.

CSE, KSIT, 2019-20 Page 166


Advanced Java & J2EE (17CS553) Study Material

Provides an input stream for reading binary data from a client request, including
 ServletInputStream
an efficient readLine method for reading data one line at a time.

 ServletOutputStream Provides an output stream for sending binary data to the client.

This is the event class for notifications of changes to the attributes of the servlet
ServletRequestAttributeEvent
request in an application.

ServletRequestEvent Events of this kind indicate lifecycle events for a ServletRequest.

Provides a convenient implementation of the ServletRequest interface that can be


ServletRequestWrapper
subclassed by developers wishing to adapt the request to a Servlet.

Provides a convenient implementation of the ServletResponse interface that can


ServletResponseWrapper
be subclassed by developers wishing to adapt the response from a Servlet.

Exception Summary
 ServletException Defines a general exception a servlet can throw when it encounters difficulty.

Defines an exception that a servlet or filter throws to indicate that it is


 UnavailableException
permanently or temporarily unavailable.

Package javax.servlet Description

The javax.servlet package contains a number of classes and interfaces that describe and define the contracts
between a servlet class and the runtime environment provided for an instance of such a class by a
conforming servlet container.

javax.servlet
Interface Servlet
All Known Implementing Classes:

GenericServlet, HttpServlet

General form

public interface Servlet

Defines methods that all servlets must implement.

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests
from Web clients, usually across HTTP, the HyperText Transfer Protocol.

CSE, KSIT, 2019-20 Page 167


Advanced Java & J2EE (17CS553) Study Material

To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP
servlet that extends javax.servlet.http.HttpServlet.

This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the
server. These are known as life-cycle methods and are called in the following sequence:

1. The servlet is constructed, then initialized with the init method.


2. Any calls from clients to the service method are handled.
3. The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and
finalized.

In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can
use to get any startup information, and the getServletInfo method, which allows the servlet to return basic
information about itself, such as author, version, and copyright.

Method Summary
 void destroy()
Called by the servlet container to indicate to a servlet that the servlet is being taken out of
service.

ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup parameters for this
servlet.

java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and copyright.

 void init(ServletConfig config)


Called by the servlet container to indicate to a servlet that the servlet is being placed into
service.

 void service(ServletRequest req, ServletResponse res)


Called by the servlet container to allow the servlet to respond to a request.

javax.servlet
Interface ServletConfig
All Known Implementing Classes:

GenericServlet, HttpServlet

General Form:

public interface ServletConfig

A servlet configuration object used by a servlet container to pass information to a servlet during
initialization.

CSE, KSIT, 2019-20 Page 168


Advanced Java & J2EE (17CS553) Study Material

Method Summary
java.lang.String getInitParameter(java.lang.String name)
Returns a String containing the value of the named initialization parameter, or null if the
parameter does not exist.

java.util.Enumeration getInitParameterNames()
Returns the names of the servlet's initialization parameters as an Enumeration of String
objects, or an empty Enumeration if the servlet has no initialization parameters.

ServletContext getServletContext()
Returns a reference to the ServletContext in which the caller is executing.

java.lang.String getServletName()
Returns the name of this servlet instance.

javax.servlet
Interface ServletContext
public interface ServletContext

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the
MIME type of a file, dispatch requests, or write to a log file.

There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of
servlets and content installed under a specific subset of the server's URL namespace such as /catalog and
possibly installed via a .war file.)

In the case of a web application marked "distributed" in its deployment descriptor, there will be one context
instance for each virtual machine. In this situation, the context cannot be used as a location to share global
information (because the information won't be truly global). Use an external resource like a database instead.

The ServletContext object is contained within the ServletConfig object, which the Web server provides the
servlet when the servlet is initialized.

Method Summary
 java.lang.Object getAttribute(java.lang.String name)
Returns the servlet container attribute with the given name, or null if there is no
attribute by that name.

java.util.Enumeration getAttributeNames()
Returns an Enumeration containing the attribute names available within this servlet
context.

CSE, KSIT, 2019-20 Page 169


Advanced Java & J2EE (17CS553) Study Material

ServletContext getContext(java.lang.String uripath)


Returns a ServletContext object that corresponds to a specified URL on the server.

java.lang.String getContextPath()
Returns the context path of the web application.

java.lang.String getInitParameter(java.lang.String name)


Returns a String containing the value of the named context-wide initialization
parameter, or null if the parameter does not exist.

java.util.Enumeration getInitParameterNames()
Returns the names of the context's initialization parameters as an Enumeration of
String objects, or an empty Enumeration if the context has no initialization parameters.

int getMajorVersion()
Returns the major version of the Java Servlet API that this servlet container
supports.

 java.lang.String getMimeType(java.lang.String file)


Returns the MIME type of the specified file, or null if the MIME type is not known.

int getMinorVersion()
Returns the minor version of the Servlet API that this servlet container supports.

RequestDispatcher getNamedDispatcher(java.lang.String name)


Returns a RequestDispatcher object that acts as a wrapper for the named servlet.

 java.lang.String getRealPath(java.lang.String path)


Returns a String containing the real path for a given virtual path.

RequestDispatcher getRequestDispatcher(java.lang.String path)


Returns a RequestDispatcher object that acts as a wrapper for the resource located at
the given path.

java.net.URL getResource(java.lang.String path)


Returns a URL to the resource that is mapped to a specified path.

java.io.InputStream getResourceAsStream(java.lang.String path)


Returns the resource located at the named path as an InputStream object.

java.util.Set getResourcePaths(java.lang.String path)


Returns a directory-like listing of all the paths to resources within the web
application whose longest sub-path matches the supplied path argument.

 java.lang.String getServerInfo()
Returns the name and version of the servlet container on which the servlet is

CSE, KSIT, 2019-20 Page 170


Advanced Java & J2EE (17CS553) Study Material

running.

Servlet getServlet(java.lang.String name)


Deprecated. As of Java Servlet API 2.1, with no direct replacement.

This method was originally defined to retrieve a servlet from a ServletContext.


In this version, this method always returns null and remains only to preserve
binary compatibility. This method will be permanently removed in a future version
of the Java Servlet API.

In lieu of this method, servlets can share information using the ServletContext
class and can perform shared business logic by invoking methods on common
non-servlet classes.
java.lang.String getServletContextName()
Returns the name of this web application corresponding to this ServletContext as
specified in the deployment descriptor for this web application by the display-name
element.

java.util.Enumeration getServletNames()
Deprecated. As of Java Servlet API 2.1, with no replacement.

This method was originally defined to return an Enumeration of all the servlet
names known to this context. In this version, this method always returns an empty
Enumeration and remains only to preserve binary compatibility. This method will
be permanently removed in a future version of the Java Servlet API.
java.util.Enumeration getServlets()
Deprecated. As of Java Servlet API 2.0, with no replacement.

This method was originally defined to return an Enumeration of all the servlets
known to this servlet context. In this version, this method always returns an empty
enumeration and remains only to preserve binary compatibility. This method will
be permanently removed in a future version of the Java Servlet API.
 void log(java.lang.Exception exception, java.lang.String msg)
Deprecated. As of Java Servlet API 2.1, use log(String message, Throwable throwable)
instead.

This method was originally defined to write an exception's stack trace and an
explanatory error message to the servlet log file.
 void log(java.lang.String msg)
Writes the specified message to a servlet log file, usually an event log.

 void log(java.lang.String message, java.lang.Throwable throwable)


Writes an explanatory message and a stack trace for a given Throwable exception to
the servlet log file.

 void removeAttribute(java.lang.String name)

CSE, KSIT, 2019-20 Page 171


Advanced Java & J2EE (17CS553) Study Material

Removes the attribute with the given name from the servlet context.

 void setAttribute(java.lang.String name, java.lang.Object object)


Binds an object to a given attribute name in this servlet context.

javax.servlet
Interface ServletRequest
All Known Subinterfaces:

HttpServletRequest

All Known Implementing Classes:

HttpServletRequestWrapper, ServletRequestWrapper

public interface ServletRequest

Defines an object to provide client request information to a servlet. The servlet container creates a
ServletRequest object and passes it as an argument to the servlet's service method.

A ServletRequest object provides data including parameter name and values, attributes, and an input
stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example,
HTTP data is provided by HttpServletRequest.

Method Summary
 java.lang.Object getAttribute(java.lang.String name)
Returns the value of the named attribute as an Object, or null if no attribute of
the given name exists.

java.util.Enumeration getAttributeNames()
Returns an Enumeration containing the names of the attributes available to this
request.

 java.lang.String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request.

 int getContentLength()
Returns the length, in bytes, of the request body and made available by the
input stream, or -1 if the length is not known.

 java.lang.String getContentType()
Returns the MIME type of the body of the request, or null if the type is not
known.

CSE, KSIT, 2019-20 Page 172


Advanced Java & J2EE (17CS553) Study Material

 ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a ServletInputStream.

java.lang.String getLocalAddr()
Returns the Internet Protocol (IP) address of the interface on which the
request was received.

java.util.Locale getLocale()
Returns the preferred Locale that the client will accept content in, based on
the Accept-Language header.

java.util.Enumeration getLocales()
Returns an Enumeration of Locale objects indicating, in decreasing order
starting with the preferred locale, the locales that are acceptable to the client based
on the Accept-Language header.

java.lang.String getLocalName()
Returns the host name of the Internet Protocol (IP) interface on which the
request was received.

int getLocalPort()
Returns the Internet Protocol (IP) port number of the interface on which the
request was received.

 java.lang.String getParameter(java.lang.String name)


Returns the value of a request parameter as a String, or null if the parameter
does not exist.

java.util.Map getParameterMap()
Returns a java.util.Map of the parameters of this request.

 java.util.Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the
parameters contained in this request.

 java.lang.String[] getParameterValues(java.lang.String name)


Returns an array of String objects containing all of the values the given
request parameter has, or null if the parameter does not exist.

 java.lang.String getProtocol()
Returns the name and version of the protocol the request uses in the form
protocol/majorVersion.minorVersion, for example, HTTP/1.1.

 java.io.BufferedReader getReader()
Retrieves the body of the request as character data using a BufferedReader.

CSE, KSIT, 2019-20 Page 173


Advanced Java & J2EE (17CS553) Study Material

java.lang.String getRealPath(java.lang.String path)


Deprecated. As of Version 2.1 of the Java Servlet API, use
ServletContext.getRealPath(java.lang.String) instead.

 java.lang.String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client or last proxy that sent
the request.

 java.lang.String getRemoteHost()
Returns the fully qualified name of the client or the last proxy that sent the
request.

 int getRemotePort()
Returns the Internet Protocol (IP) source port of the client or last proxy that
sent the request.

RequestDispatcher getRequestDispatcher(java.lang.String path)


Returns a RequestDispatcher object that acts as a wrapper for the resource
located at the given path.

 java.lang.String getScheme()
Returns the name of the scheme used to make this request, for example, http,
https, or ftp.

 java.lang.String getServerName()
Returns the host name of the server to which the request was sent.

 int getServerPort()
Returns the port number to which the request was sent.

boolean isSecure()
Returns a boolean indicating whether this request was made using a secure
channel, such as HTTPS.

void removeAttribute(java.lang.String name)


Removes an attribute from this request.

void setAttribute(java.lang.String name, java.lang.Object o)


Stores an attribute in this request.

void setCharacterEncoding(java.lang.String env)


Overrides the name of the character encoding used in the body of this
request.

CSE, KSIT, 2019-20 Page 174


Advanced Java & J2EE (17CS553) Study Material

javax.servlet
Interface ServletResponse
All Known Subinterfaces:

HttpServletResponse

All Known Implementing Classes:

HttpServletResponseWrapper, ServletResponseWrapper

public interface ServletResponse

Defines an object to assist a servlet in sending a response to the client. The servlet container creates a
ServletResponse object and passes it as an argument to the servlet's service method.

To send binary data in a MIME body response, use the ServletOutputStream returned by
getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To
mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and
manage the character sections manually.

The charset for the MIME body response can be specified explicitly using the
setCharacterEncoding(java.lang.String) and setContentType(java.lang.String) methods, or
implicitly using the setLocale(java.util.Locale) method. Explicit specifications take precedence over
implicit specifications. If no charset is specified, ISO-8859-1 will be used. The setCharacterEncoding,
setContentType, or setLocale method must be called before getWriter and before committing the
response for the character encoding to be used.

Method Summary
void flushBuffer()
Forces any content in the buffer to be written to the client.

int getBufferSize()
Returns the actual buffer size used for the response.

 java.lang.String getCharacterEncoding()
Returns the name of the character encoding (MIME charset) used
for the body sent in this response.

 java.lang.String getContentType()
Returns the content type used for the MIME body sent in this
response.

java.util.Locale getLocale()
Returns the locale specified for this response using the
setLocale(java.util.Locale) method.

CSE, KSIT, 2019-20 Page 175


Advanced Java & J2EE (17CS553) Study Material

 ServletOutputStream getOutputStream()
Returns a ServletOutputStream suitable for writing binary data in
the response.

 java.io.PrintWriter getWriter()
Returns a PrintWriter object that can send character text to the
client.

boolean isCommitted()
Returns a boolean indicating if the response has been committed.

void reset()
Clears any data that exists in the buffer as well as the status code
and headers.

void resetBuffer()
Clears the content of the underlying buffer in the response
without clearing headers or status code.

void setBufferSize(int size)


Sets the preferred buffer size for the body of the response.

void setCharacterEncoding(java.lang.String charset)


Sets the character encoding (MIME charset) of the response
being sent to the client, for example, to UTF-8.

 void setContentLength(int len)


Sets the length of the content body in the response In HTTP
servlets, this method sets the HTTP Content-Length header.

 void setContentType(java.lang.String type)


Sets the content type of the response being sent to the client, if
the response has not been committed yet.

void setLocale(java.util.Locale loc)


Sets the locale of the response, if the response has not been
committed yet.

javax.servlet
Class GenericServlet
java.lang.Object

javax.servlet.GenericServlet
All Implemented Interfaces:

java.io.Serializable, Servlet, ServletConfig

CSE, KSIT, 2019-20 Page 176


Advanced Java & J2EE (17CS553) Study Material

Direct Known Subclasses:

HttpServlet

public abstract class GenericServlet


extends java.lang.Object
implements Servlet, ServletConfig, java.io.Serializable

Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend
HttpServlet instead.

GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be


directly extended by a servlet, although it's more common to extend a protocol-specific subclass such as
HttpServlet.

GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init
and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log
method, declared in the ServletContext interface.

To write a generic servlet, you need only override the abstract service method.

Constructor Summary
GenericServlet()
Does nothing.

Method Summary
 void destroy()
Called by the servlet container to indicate to a servlet that the servlet is
being taken out of service.

java.lang.String getInitParameter(java.lang.String name)


Returns a String containing the value of the named initialization parameter,
or null if the parameter does not exist.

java.util.Enumeration getInitParameterNames()
Returns the names of the servlet's initialization parameters as an
Enumeration of String objects, or an empty Enumeration if the servlet has no
initialization parameters.

ServletConfig getServletConfig()
Returns this servlet's ServletConfig object.

ServletContext
getServletContext()

CSE, KSIT, 2019-20 Page 177


Advanced Java & J2EE (17CS553) Study Material

Returns a reference to the ServletContext in which this servlet is running.

java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and
copyright.

java.lang.String getServletName()
Returns the name of this servlet instance.

 void init()
A convenience method which can be overridden so that there's no need to
call super.init(config).

 void init(ServletConfig config)


Called by the servlet container to indicate to a servlet that the servlet is
being placed into service.

 void log(java.lang.String msg)


Writes the specified message to a servlet log file, prepended by the servlet's
name.

 void log(java.lang.String message, java.lang.Throwable t)


Writes an explanatory message and a stack trace for a given Throwable
exception to the servlet log file, prepended by the servlet's name.

 abstract void service(ServletRequest req, ServletResponse res)


Called by the servlet container to allow the servlet to respond to a request.

avax.servlet
Class ServletInputStream
java.lang.Object

java.io.InputStream

javax.servlet.ServletInputStream
All Implemented Interfaces:
java.io.Closeable

public abstract class ServletInputStream


extends java.io.InputStream

Provides an input stream for reading binary data from a client request, including an efficient readLine method
for reading data one line at a time. With some protocols, such as HTTP POST and PUT, a ServletInputStream
object can be used to read data sent from the client.

A ServletInputStream object is normally retrieved via the ServletRequest.getInputStream() method.

CSE, KSIT, 2019-20 Page 178


Advanced Java & J2EE (17CS553) Study Material

This is an abstract class that a servlet container implements. Subclasses of this class must implement the
java.io.InputStream.read() method.

Constructor Summary
protected ServletInputStream()
Does nothing, because this is an abstract class.

Method Summary
int readLine(byte[] b, int off, int len)
Reads the input stream, one line at a time.

javax.servlet
Class ServletOutputStream
java.lang.Object

java.io.OutputStream

javax.servlet.ServletOutputStream
All Implemented Interfaces:
java.io.Closeable, java.io.Flushable

public abstract class ServletOutputStream


extends java.io.OutputStream

Provides an output stream for sending binary data to the client. A ServletOutputStream object is normally
retrieved via the ServletResponse.getOutputStream() method.

This is an abstract class that the servlet container implements. Subclasses of this class must implement the
java.io.OutputStream.write(int) method.

Constructor Summary
protected ServletOutputStream()
Does nothing, because this is an abstract class.

Method Summary

CSE, KSIT, 2019-20 Page 179


Advanced Java & J2EE (17CS553) Study Material

void print(boolean b)
Writes a boolean value to the client, with no carriage return-line feed (CRLF) character at the end.

void print(char c)
Writes a character to the client, with no carriage return-line feed (CRLF) at the end.

void print(double d)
Writes a double value to the client, with no carriage return-line feed (CRLF) at the end.

void print(float f)
Writes a float value to the client, with no carriage return-line feed (CRLF) at the end.

void print(int i)
Writes an int to the client, with no carriage return-line feed (CRLF) at the end.

void print(long l)
Writes a long value to the client, with no carriage return-line feed (CRLF) at the end.

void print(java.lang.String s)
Writes a String to the client, without a carriage return-line feed (CRLF) character at the end.

void println()
Writes a carriage return-line feed (CRLF) to the client.

void println(boolean b)
Writes a boolean value to the client, followed by a carriage return-line feed (CRLF).

void println(char c)
Writes a character to the client, followed by a carriage return-line feed (CRLF).

void println(double d)
Writes a double value to the client, followed by a carriage return-line feed (CRLF).

void println(float f)
Writes a float value to the client, followed by a carriage return-line feed (CRLF).

void println(int i)
Writes an int to the client, followed by a carriage return-line feed (CRLF) character.

void println(long l)
Writes a long value to the client, followed by a carriage return-line feed (CRLF).

void println(java.lang.String s)
Writes a String to the client, followed by a carriage return-line feed (CRLF).

CSE, KSIT, 2019-20 Page 180


Advanced Java & J2EE (17CS553) Study Material

javax.servlet
Class ServletException
java.lang.Object

java.lang.Throwable

java.lang.Exception

javax.servlet.ServletException
All Implemented Interfaces:

java.io.Serializable

Direct Known Subclasses:

UnavailableException

public class ServletException


extends java.lang.Exception

Defines a general exception a servlet can throw when it encounters difficulty.

Constructor Summary
ServletException()
Constructs a new servlet exception.

ServletException(java.lang.String message)
Constructs a new servlet exception with the specified message.

ServletException(java.lang.String message, java.lang.Throwable rootCause)


Constructs a new servlet exception when the servlet needs to throw an exception and include a message about
the "root cause" exception that interfered with its normal operation, including a description message.

ServletException(java.lang.Throwable rootCause)
Constructs a new servlet exception when the servlet needs to throw an exception and include a message about
the "root cause" exception that interfered with its normal operation.

Method Summary
java.lang.Throwable getRootCause()
Returns the exception that caused this servlet exception.

CSE, KSIT, 2019-20 Page 181


Advanced Java & J2EE (17CS553) Study Material

javax.servlet
Class UnavailableException
java.lang.Object

java.lang.Throwable

java.lang.Exception

javax.servlet.ServletException

javax.servlet.UnavailableException
All Implemented Interfaces:

java.io.Serializable

public class UnavailableException


extends ServletException

Defines an exception that a servlet or filter throws to indicate that it is permanently or temporarily
unavailable.

When a servlet or filter is permanently unavailable, something is wrong with it, and it cannot handle
requests until some action is taken. For example, a servlet might be configured incorrectly, or a filter's state
may be corrupted. The component should log both the error and the corrective action that is needed.

A servlet or filter is temporarily unavailable if it cannot handle requests momentarily due to some system-
wide problem. For example, a third-tier server might not be accessible, or there may be insufficient memory
or disk storage to handle requests. A system administrator may need to take corrective action.

Servlet containers can safely treat both types of unavailable exceptions in the same way. However, treating
temporary unavailability effectively makes the servlet container more robust. Specifically, the servlet
container might block requests to the servlet or filter for a period of time suggested by the exception, rather
than rejecting them until the servlet container restarts.

Constructor Summary
UnavailableException(int seconds, Servlet servlet, java.lang.String msg)
Deprecated. As of Java Servlet API 2.2, use UnavailableException(String, int) instead.

UnavailableException(Servlet servlet, java.lang.String msg)


Deprecated. As of Java Servlet API 2.2, use UnavailableException(String) instead.

UnavailableException(java.lang.String msg)

CSE, KSIT, 2019-20 Page 182


Advanced Java & J2EE (17CS553) Study Material

Constructs a new exception with a descriptive message indicating that the servlet is permanently unavailable.

UnavailableException(java.lang.String msg, int seconds)


Constructs a new exception with a descriptive message indicating that the servlet is temporarily unavailable
and giving an estimate of how long it will be unavailable.

Method Summary
Servlet getServlet()
Deprecated. As of Java Servlet API 2.2, with no replacement. Returns the servlet that is reporting
its unavailability.

int getUnavailableSeconds()
Returns the number of seconds the servlet expects to be temporarily unavailable.

boolean isPermanent()
Returns a boolean indicating whether the servlet is permanently unavailable.

Package javax.servlet.http
The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts
between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of
such a class by a conforming servlet container.

Interface Summary
Extends the ServletRequest interface to provide request information
 HttpServletRequest
for HTTP servlets.

Extends the ServletResponse interface to provide HTTP-specific


 HttpServletResponse
functionality in sending a response.

Provides a way to identify a user across more than one page request
 HttpSession
or visit to a Web site and to store information about that user.

Objects that are bound to a session may listen to container events


HttpSessionActivationListener notifying them that sessions will be passivated and that session will
be activated.

This listener interface can be implemented in order to get


HttpSessionAttributeListener notifications of changes to the attribute lists of sessions within this
web application.

CSE, KSIT, 2019-20 Page 183


Advanced Java & J2EE (17CS553) Study Material

Causes an object to be notified when it is bound to or unbound from


 HttpSessionBindingListener
a session.

Deprecated. As of Java(tm) Servlet API 2.1 for security reasons,


HttpSessionContext
with no replacement.

Implementations of this interface are notified of changes to the list


HttpSessionListener
of active sessions in a web application.

Class Summary
Creates a cookie, a small amount of information sent by a servlet to a Web
 Cookie
browser, saved by the browser, and later sent back to the server.

Provides an abstract class to be subclassed to create an HTTP servlet suitable


 HttpServlet
for a Web site.

Provides a convenient implementation of the HttpServletRequest interface


HttpServletRequestWrapper that can be subclassed by developers wishing to adapt the request to a
Servlet.

Provides a convenient implementation of the HttpServletResponse interface


HttpServletResponseWrapper that can be subclassed by developers wishing to adapt the response from a
Servlet.

Events of this type are either sent to an object that implements


HttpSessionBindingListener when it is bound or unbound from a session, or to a
 HttpSessionBindingEvent
HttpSessionAttributeListener that has been configured in the deployment
descriptor when any attribute is bound, unbound or replaced in a session.

This is the class representing event notifications for changes to sessions


 HttpSessionEvent
within a web application.

HttpUtils Deprecated. As of Java(tm) Servlet API 2.3.

Package javax.servlet.http Description

The javax.servlet.http package contains a number of classes and interfaces that describe and define the
contracts between a servlet class running under the HTTP protocol and the runtime environment provided
for an instance of such a class by a conforming servlet container.

CSE, KSIT, 2019-20 Page 184


Advanced Java & J2EE (17CS553) Study Material

javax.servlet.http
Interface HttpServletRequest
All Superinterfaces:

ServletRequest

All Known Implementing Classes:

HttpServletRequestWrapper

public interface HttpServletRequest


extends ServletRequest

Extends the ServletRequest interface to provide request information for HTTP servlets.

The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's
service methods (doGet, doPost, etc).

Field Summary
static java.lang.String BASIC_AUTH
String identifier for Basic authentication.

static java.lang.String CLIENT_CERT_AUTH


String identifier for Client Certificate authentication.

static java.lang.String DIGEST_AUTH


String identifier for Digest authentication.

static java.lang.String FORM_AUTH


String identifier for Form authentication.

Method Summary
 java.lang.String getAuthType()
Returns the name of the authentication scheme used to protect the servlet.

java.lang.String getContextPath()
Returns the portion of the request URI that indicates the context of the
request.

 Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with this

CSE, KSIT, 2019-20 Page 185


Advanced Java & J2EE (17CS553) Study Material

request.

 long getDateHeader(java.lang.String name)


Returns the value of the specified request header as a long value that
represents a Date object.

 java.lang.String getHeader(java.lang.String name)


Returns the value of the specified request header as a String.

 java.util.Enumeration getHeaderNames()
Returns an enumeration of all the header names this request contains.

java.util.Enumeration getHeaders(java.lang.String name)


Returns all the values of the specified request header as an Enumeration of
String objects.

 int getIntHeader(java.lang.String name)


Returns the value of the specified request header as an int.

 java.lang.String getMethod()
Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT.

 java.lang.String getPathInfo()
Returns any extra path information associated with the URL the client sent
when it made this request.

 java.lang.String getPathTranslated()
Returns any extra path information after the servlet name but before the query
string, and translates it to a real path.

 java.lang.String getQueryString()
Returns the query string that is contained in the request URL after the path.

 java.lang.String getRemoteUser()
Returns the login of the user making this request, if the user has been
authenticated, or null if the user has not been authenticated.

 java.lang.String getRequestedSessionId()
Returns the session ID specified by the client.

 java.lang.String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query
string in the first line of the HTTP request.

 java.lang.StringBuffer getRequestURL()

CSE, KSIT, 2019-20 Page 186


Advanced Java & J2EE (17CS553) Study Material

Reconstructs the URL the client used to make the request.

 java.lang.String getServletPath()
Returns the part of this request's URL that calls the servlet.

 HttpSession getSession()
Returns the current session associated with this request, or if the request does
not have a session, creates one.

 HttpSession getSession(boolean create)


Returns the current HttpSession associated with this request or, if there is no
current session and create is true, returns a new session.

java.security.Principal getUserPrincipal()
Returns a java.security.Principal object containing the name of the current
authenticated user.

 boolean isRequestedSessionIdFromCookie()
Checks whether the requested session ID came in as a cookie.

boolean isRequestedSessionIdFromUrl()
Deprecated. As of
Version 2.1 of the Java Servlet API, use
isRequestedSessionIdFromURL() instead.

 boolean isRequestedSessionIdFromURL()
Checks whether the requested session ID came in as part of the request URL.

 boolean isRequestedSessionIdValid()
Checks whether the requested session ID is still valid.

boolean isUserInRole(java.lang.String role)


Returns a boolean indicating whether the authenticated user is included in the
specified logical "role".

javax.servlet.http
Interface HttpServletResponse
All Superinterfaces:

ServletResponse

All Known Implementing Classes:

HttpServletResponseWrapper

CSE, KSIT, 2019-20 Page 187


Advanced Java & J2EE (17CS553) Study Material

public interface HttpServletResponse


extends ServletResponse

Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For
example, it has methods to access HTTP headers and cookies.

The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's
service methods (doGet, doPost, etc).

Field Summary
static int SC_ACCEPTED
Status code (202) indicating that a request was accepted for processing, but was not
completed.

static int SC_BAD_GATEWAY


Status code (502) indicating that the HTTP server received an invalid response from a
server it consulted when acting as a proxy or gateway.

static int SC_BAD_REQUEST


Status code (400) indicating the request sent by the client was syntactically incorrect.

static int SC_CONFLICT


Status code (409) indicating that the request could not be completed due to a conflict with
the current state of the resource.

static int SC_CONTINUE


Status code (100) indicating the client can continue.

static int SC_CREATED


Status code (201) indicating the request succeeded and created a new resource on the
server.

static int SC_EXPECTATION_FAILED


Status code (417) indicating that the server could not meet the expectation given in the
Expect request header.

static int SC_FORBIDDEN


Status code (403) indicating the server understood the request but refused to fulfill it.

static int SC_FOUND


Status code (302) indicating that the resource reside temporarily under a different URI.

static int SC_GATEWAY_TIMEOUT


Status code (504) indicating that the server did not receive a timely response from the

CSE, KSIT, 2019-20 Page 188


Advanced Java & J2EE (17CS553) Study Material

upstream server while acting as a gateway or proxy.

static int SC_GONE


Status code (410) indicating that the resource is no longer available at the server and no
forwarding address is known.

static int SC_HTTP_VERSION_NOT_SUPPORTED


Status code (505) indicating that the server does not support or refuses to support the
HTTP protocol version that was used in the request message.

static int SC_INTERNAL_SERVER_ERROR


Status code (500) indicating an error inside the HTTP server which prevented it from
fulfilling the request.

static int SC_LENGTH_REQUIRED


Status code (411) indicating that the request cannot be handled without a defined Content-
Length.

static int SC_METHOD_NOT_ALLOWED


Status code (405) indicating that the method specified in the Request-Line is not allowed for
the resource identified by the Request-URI.

static int SC_MOVED_PERMANENTLY


Status code (301) indicating that the resource has permanently moved to a new location,
and that future references should use a new URI with their requests.

static int SC_MOVED_TEMPORARILY


Status code (302) indicating that the resource has temporarily moved to another location,
but that future references should still use the original URI to access the resource.

static int SC_MULTIPLE_CHOICES


Status code (300) indicating that the requested resource corresponds to any one of a set of
representations, each with its own specific location.

static int SC_NO_CONTENT


Status code (204) indicating that the request succeeded but that there was no new
information to return.

static int SC_NON_AUTHORITATIVE_INFORMATION


Status code (203) indicating that the meta information presented by the client did not
originate from the server.

static int SC_NOT_ACCEPTABLE


Status code (406) indicating that the resource identified by the request is only capable of
generating response entities which have content characteristics not acceptable according to the
accept headers sent in the request.

CSE, KSIT, 2019-20 Page 189


Advanced Java & J2EE (17CS553) Study Material

 static int SC_NOT_FOUND


Status code (404) indicating that the requested resource is not available.

static int SC_NOT_IMPLEMENTED


Status code (501) indicating the HTTP server does not support the functionality needed to
fulfill the request.

static int SC_NOT_MODIFIED


Status code (304) indicating that a conditional GET operation found that the resource was
available and not modified.

 static int SC_OK


Status code (200) indicating the request succeeded normally.

static int SC_PARTIAL_CONTENT


Status code (206) indicating that the server has fulfilled the partial GET request for the
resource.

static int SC_PAYMENT_REQUIRED


Status code (402) reserved for future use.

static int SC_PRECONDITION_FAILED


Status code (412) indicating that the precondition given in one or more of the request-
header fields evaluated to false when it was tested on the server.

static int SC_PROXY_AUTHENTICATION_REQUIRED


Status code (407) indicating that the client MUST first authenticate itself with the proxy.

static int SC_REQUEST_ENTITY_TOO_LARGE


Status code (413) indicating that the server is refusing to process the request because the
request entity is larger than the server is willing or able to process.

static int SC_REQUEST_TIMEOUT


Status code (408) indicating that the client did not produce a request within the time that
the server was prepared to wait.

static int SC_REQUEST_URI_TOO_LONG


Status code (414) indicating that the server is refusing to service the request because the
Request-URI is longer than the server is willing to interpret.

static int SC_REQUESTED_RANGE_NOT_SATISFIABLE


Status code (416) indicating that the server cannot serve the requested byte range.

static int SC_RESET_CONTENT


Status code (205) indicating that the agent SHOULD reset the document view which
caused the request to be sent.

CSE, KSIT, 2019-20 Page 190


Advanced Java & J2EE (17CS553) Study Material

static int SC_SEE_OTHER


Status code (303) indicating that the response to the request can be found under a different
URI.

static int SC_SERVICE_UNAVAILABLE


Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to
handle the request.

static int SC_SWITCHING_PROTOCOLS


Status code (101) indicating the server is switching protocols according to Upgrade
header.

static int SC_TEMPORARY_REDIRECT


Status code (307) indicating that the requested resource resides temporarily under a
different URI.

static int SC_UNAUTHORIZED


Status code (401) indicating that the request requires HTTP authentication.

static int SC_UNSUPPORTED_MEDIA_TYPE


Status code (415) indicating that the server is refusing to service the request because the
entity of the request is in a format not supported by the requested resource for the requested
method.

static int SC_USE_PROXY


Status code (305) indicating that the requested resource MUST be accessed through the
proxy given by the Location field.

Method Summary
 void addCookie(Cookie cookie)
Adds the specified cookie to the response.

void addDateHeader(java.lang.String name, long date)


Adds a response header with the given name and date-value.

void addHeader(java.lang.String name, java.lang.String value)


Adds a response header with the given name and value.

void addIntHeader(java.lang.String name, int value)


Adds a response header with the given name and integer value.

 boolean containsHeader(java.lang.String name)


Returns a boolean indicating whether the named response header has

CSE, KSIT, 2019-20 Page 191


Advanced Java & J2EE (17CS553) Study Material

already been set.

java.lang.String encodeRedirectUrl(java.lang.String url)


Deprecated. As of version 2.1, use encodeRedirectURL(String url)
instead

 java.lang.String encodeRedirectURL(java.lang.String url)


Encodes the specified URL for use in the sendRedirect method or, if
encoding is not needed, returns the URL unchanged.

java.lang.String encodeUrl(java.lang.String url)


Deprecated. As of version 2.1, use encodeURL(String url) instead

 java.lang.String encodeURL(java.lang.String url)


Encodes the specified URL by including the session ID in it, or, if
encoding is not needed, returns the URL unchanged.

 void sendError(int sc)


Sends an error response to the client using the specified status code and
clearing the buffer.

 void sendError(int sc, java.lang.String msg)


Sends an error response to the client using the specified status.

 void sendRedirect(java.lang.String location)


Sends a temporary redirect response to the client using the specified
redirect location URL.

 void setDateHeader(java.lang.String name, long date)


Sets a response header with the given name and date-value.

 void setHeader(java.lang.String name, java.lang.String value)


Sets a response header with the given name and value.

 void setIntHeader(java.lang.String name, int value)


Sets a response header with the given name and integer value.

 void setStatus(int sc)


Sets the status code for this response.

void setStatus(int sc, java.lang.String sm)


Deprecated. As of version 2.1, due to ambiguous meaning of the
message parameter. To set a status code use setStatus(int), to send an error
with a description use sendError(int, String). Sets the status code and message
for this response.

CSE, KSIT, 2019-20 Page 192


Advanced Java & J2EE (17CS553) Study Material
javax.servlet.http
Interface HttpSession
public interface HttpSession

Provides a way to identify a user across more than one page request or visit to a Web site and to store
information about that user.

The servlet container uses this interface to create a session between an HTTP client and an HTTP server.
The session persists for a specified time period, across more than one connection or page request from the
user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a
session in many ways such as using cookies or rewriting URLs.

This interface allows servlets to

View and manipulate information about a session, such as the session identifier, creation time, and
last accessed time
Bind objects to sessions, allowing user information to persist across multiple user connections

When an application stores an object in or removes an object from a session, the session checks whether the
object implements HttpSessionBindingListener. If it does, the servlet notifies the object that it has been bound to
or unbound from the session. Notifications are sent after the binding methods complete. For session that are
invalidated or expire, notifications are sent after the session has been invalidated or expired.

When container migrates a session between VMs in a distributed container setting, all session attributes
implementing the HttpSessionActivationListener interface are notified.

A servlet should be able to handle cases in which the client does not choose to join a session, such as when
cookies are intentionally turned off. Until the client joins the session, isNew returns true. If the client chooses
not to join the session, getSession will return a different session on each request, and isNew will always return
true.

Session information is scoped only to the current web application (ServletContext), so information stored in
one context will not be directly visible in another.

Method Summary
 java.lang.Object getAttribute(java.lang.String name)
Returns the object bound with the specified name in this
session, or null if no object is bound under the name.

 java.util.Enumeration getAttributeNames()
Returns an Enumeration of String objects containing the names
of all the objects bound to this session.

 long getCreationTime()
Returns the time when this session was created, measured in

CSE, KSIT, 2019-20 Page 193


Advanced Java & J2EE (17CS553) Study Material

milliseconds since midnight January 1, 1970 GMT.

 java.lang.String getId()
Returns a string containing the unique identifier assigned to
this session.

 long getLastAccessedTime()
Returns the last time the client sent a request associated with
this session, as the number of milliseconds since midnight January 1,
1970 GMT, and marked by the time the container received the
request.

int getMaxInactiveInterval()
Returns the maximum time interval, in seconds, that the servlet
container will keep this session open between client accesses.

ServletContext getServletContext()
Returns the ServletContext to which this session belongs.

HttpSessionContext getSessionContext()
Deprecated. As of Version 2.1, this method is deprecated and
has no replacement. It will be removed in a future version of the Java
Servlet API.

java.lang.Object getValue(java.lang.String name)


Deprecated. As of Version 2.2, this method is replaced by
getAttribute(java.lang.String).

java.lang.String[] getValueNames()
Deprecated. As of Version 2.2, this method is replaced by
getAttributeNames()

 void invalidate()
Invalidates this session then unbinds any objects bound to it.

 boolean isNew()
Returns true if the client does not yet know about the session or
if the client chooses not to join the session.

void putValue(java.lang.String name, java.lang.Object value)


Deprecated. As of Version 2.2, this method is replaced by
setAttribute(java.lang.String, java.lang.Object)

 void removeAttribute(java.lang.String name)


Removes the object bound with the specified name from this
session.

CSE, KSIT, 2019-20 Page 194


Advanced Java & J2EE (17CS553) Study Material

void removeValue(java.lang.String name)


Deprecated. As of Version 2.2, this method is replaced by
removeAttribute(java.lang.String)

 void setAttribute(java.lang.String name, java.lang.Object value)


Binds an object to this session, using the name specified.

void setMaxInactiveInterval(int interval)


Specifies the time, in seconds, between client requests before
the servlet container will invalidate this session.

javax.servlet.http
Interface HttpSessionBindingListener
All Superinterfaces:
java.util.EventListener

public interface HttpSessionBindingListener


extends java.util.EventListener

Causes an object to be notified when it is bound to or unbound from a session. The object is notified by an
HttpSessionBindingEvent object. This may be as a result of a servlet programmer explicitly unbinding an
attribute from a session, due to a session being invalidated, or due to a session timing out.

Method Summary
void valueBound(HttpSessionBindingEvent event)
Notifies the object that it is being bound to a session and identifies the session.

void valueUnbound(HttpSessionBindingEvent event)


Notifies the object that it is being unbound from a session and identifies the session.

javax.servlet.http
Class Cookie
java.lang.Object

javax.servlet.http.Cookie
All Implemented Interfaces:

java.lang.Cloneable

public class Cookie


extends java.lang.Object
implements java.lang.Cloneable

CSE, KSIT, 2019-20 Page 195


Advanced Java & J2EE (17CS553) Study Material

Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser,
and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly
used for session management.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers,
a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional
attributes, so use them sparingly to improve the interoperability of your servlets.

The servlet sends cookies to the browser by using the


HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP
response headers to send cookies to the browser, one at a time. The browser is expected to support 20
cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be
retrieved from a request by using the HttpServletRequest.getCookies() method. Several cookies might
have the same name but different path attributes.

Cookies affect the caching of the Web pages that use them. HTTP 1.0 does not cache pages that use cookies
created with this class. This class does not support the cache control defined with HTTP 1.1.

This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By
default, cookies are created using Version 0 to ensure the best interoperability.

Constructor Summary
Cookie(java.lang.String name, java.lang.String value)
Constructs a cookie with a specified name and value.

Method Summary
 java.lang.Object clone()
Overrides the standard java.lang.Object.clone method to return a copy of
this cookie.

 java.lang.String getComment()
Returns the comment describing the purpose of this cookie, or null if
the cookie has no comment.

 java.lang.String getDomain()
Returns the domain name set for this cookie.

 int getMaxAge()
Returns the maximum age of the cookie, specified in seconds, By

CSE, KSIT, 2019-20 Page 196


Advanced Java & J2EE (17CS553) Study Material

default, -1 indicating the cookie will persist until browser shutdown.

 java.lang.String getName()
Returns the name of the cookie.

 java.lang.String getPath()
Returns the path on the server to which the browser returns this cookie.

 boolean getSecure()
Returns true if the browser is sending cookies only over a secure
protocol, or false if the browser can send cookies using any protocol.

 java.lang.String getValue()
Returns the value of the cookie.

 int getVersion()
Returns the version of the protocol this cookie complies with.

 void setComment(java.lang.String purpose)


Specifies a comment that describes a cookie's purpose.

 void setDomain(java.lang.String pattern)


Specifies the domain within which this cookie should be presented.

 void setMaxAge(int expiry)


Sets the maximum age of the cookie in seconds.

 void setPath(java.lang.String uri)


Specifies a path for the cookie to which the client should return the
cookie.

 void setSecure(boolean flag)


Indicates to the browser whether the cookie should only be sent using a
secure protocol, such as HTTPS or SSL.

 void setValue(java.lang.String newValue)


Assigns a new value to a cookie after the cookie is created.

 void setVersion(int v)
Sets the version of the cookie protocol this cookie complies with.

javax.servlet.http
Class HttpServlet
java.lang.Object

javax.servlet.GenericServlet

CSE, KSIT, 2019-20 Page 197


Advanced Java & J2EE (17CS553) Study Material

javax.servlet.http.HttpServlet
All Implemented Interfaces:

java.io.Serializable, Servlet, ServletConfig

public abstract class HttpServlet


extends GenericServlet
implements java.io.Serializable

Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of
HttpServlet must override at least one method, usually one of these:

doGet, if the servlet supports HTTP GET requests


doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
init and destroy, to manage resources that are held for the life of the servlet
getServletInfo, which the servlet uses to provide information about itself

There's almost no reason to override the service method. service handles standard HTTP requests by
dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).

Likewise, there's almost no reason to override the doOptions and doTrace methods.

Servlets typically run on multithreaded servers, so be aware that a servlet must handle concurrent requests
and be careful to synchronize access to shared resources. Shared resources include in-memory data such as
instance or class variables and external objects such as files, database connections, and network connections.
See the Java Tutorial on Multithreaded Programming for more information on handling multiple threads in a
Java program.

Constructor Summary
HttpServlet()
Does nothing, because this is an abstract class.

Method Summary
 protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a
DELETE request.

 protected void doGet(HttpServletRequest req, HttpServletResponse resp)

CSE, KSIT, 2019-20 Page 198


Advanced Java & J2EE (17CS553) Study Material

Called by the server (via the service method) to allow a servlet to handle a GET
request.

 protected void doHead(HttpServletRequest req, HttpServletResponse resp)


Receives an HTTP HEAD request from the protected service method and handles
the request.

 protected void doOptions(HttpServletRequest req, HttpServletResponse resp)


Called by the server (via the service method) to allow a servlet to handle a
OPTIONS request.

 protected void doPost(HttpServletRequest req, HttpServletResponse resp)


Called by the server (via the service method) to allow a servlet to handle a POST
request.

 protected void doPut(HttpServletRequest req, HttpServletResponse resp)


Called by the server (via the service method) to allow a servlet to handle a PUT
request.

 protected void doTrace(HttpServletRequest req, HttpServletResponse resp)


Called by the server (via the service method) to allow a servlet to handle a TRACE
request.

 protected long getLastModified(HttpServletRequest req)


Returns the time the HttpServletRequest object was last modified, in milliseconds
since midnight January 1, 1970 GMT.

 protected void service(HttpServletRequest req, HttpServletResponse resp)


Receives standard HTTP requests from the public service method and dispatches
them to the doXXX methods defined in this class.

void service(ServletRequest req, ServletResponse res)


Dispatches client requests to the protected service method.

javax.servlet.http
Class HttpSessionBindingEvent
java.lang.Object

java.util.EventObject

javax.servlet.http.HttpSessionEvent

javax.servlet.http.HttpSessionBindingEvent
All Implemented Interfaces:

java.io.Serializable

CSE, KSIT, 2019-20 Page 199


Advanced Java & J2EE (17CS553) Study Material
public class HttpSessionBindingEvent
extends HttpSessionEvent

Events of this type are either sent to an object that implements HttpSessionBindingListener when it is
bound or unbound from a session, or to a HttpSessionAttributeListener that has been configured in the
deployment descriptor when any attribute is bound, unbound or replaced in a session.

The session binds the object by a call to HttpSession.setAttribute and unbinds the object by a call to
HttpSession.removeAttribute.

Constructor Summary
HttpSessionBindingEvent(HttpSession session, java.lang.String name)
Constructs an event that notifies an object that it has been bound to or unbound from a session.

HttpSessionBindingEvent(HttpSession session, java.lang.String name, java.lang.Object value)


Constructs an event that notifies an object that it has been bound to or unbound from a session.

Method Summary
java.lang.String getName()
Returns the name with which the attribute is bound to or unbound from the session.

HttpSession getSession()
Return the session that changed.

java.lang.Object getValue()
Returns the value of the attribute that has been added, removed or replaced.

javax.servlet.http
Class HttpSessionEvent
java.lang.Object

java.util.EventObject

javax.servlet.http.HttpSessionEvent
All Implemented Interfaces:

java.io.Serializable

Direct Known Subclasses:

HttpSessionBindingEvent

public class HttpSessionEvent


extends java.util.EventObject

CSE, KSIT, 2019-20 Page 200


Advanced Java & J2EE (17CS553) Study Material

Constructor Summary
HttpSessionEvent(HttpSession source)
Construct a session event from the given source.

Method Summary
HttpSession getSession()
Return the session that changed.

JAVA SERVER PAGES (JSP)

Introduction

JavaServer Pages Technology


• JavaServer Pages (JSP) technology allows you to easily create web content that has both static and
dynamic components.
• JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides
a more natural approach to creating static content.

• JSP is a server-side program that is similar in design and functionality to a Java Servlet.

• A JSP is called by a client to provide a web service, the nature of which depends on the J2EE
application.

• A JSP processes the request by using logic built into JSP or by calling other web components built
using Java Servlet technology or EJB or by created using other technologies.

• Once the request is processed, the JSP responds by sending the results to the client.

• JSP differs from a Java servlet in the way in which the JSP is written:

• Java servlet is written using the Java programming language and responses are encoded as an
output String object that is passed to println() method. The output object is formatted in
HTML, XML, or whatever formats required by the client.

• In contrast JSP is written in HTML, XML, or in the client‘s format that is interspersed with
Scripting Elements, Directives, and actions comprised of Java Programming Language
and JSP syntax.
• JSP can be used middle-level program between clients and web services.

What Is a JSP Page?

A JSP page is a text document that contains two types of text:


CSE, KSIT, 2019-20 Page 201
Advanced Java & J2EE (17CS553) Study Material

– static data, which can be expressed in any text-based format (such as HTML, SVG, WML,
and XML ),
– JSP elements, which construct dynamic content.
– The recommended file extension for the source file of a JSP page is .jsp.

What is JavaServer Pages?

JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content
which helps developers insert java code in HTML pages by making use of special JSP tags, most of
which start with <% and end with %>.

What is JavaServer Pages?

(From Wikipedia)

• JavaServer Pages (JSP) is a collection of technologies that helps software developers create
dynamically generated web pages based on HTML, XML, SOAP, or other document types.
Released in 1999 by Sun Microsystems,[1] JSP is similar to PHP and ASP, but it uses the Java
programming language.
• To deploy and run JavaServer Pages, a compatible web server with a servlet container, such as
Apache Tomcat or Jetty, is required.

JSP Life Cycle:

The following figure shows the JSP life cycle

CSE, KSIT, 2019-20 Page 202


Advanced Java & J2EE (17CS553) Study Material

There are three methods that are automatically called when a JSP is requested and when the JSP terminates
normally. These are

• jspInt() method: This method is called first when the JSP is requested and is used to nitialize
objects and variables that are used throughout the life cycle of the JSP.
• jspDestroy() method: This method is automatically called when the JSP terminates normally.
This method is used for cleanup where resources used during the execution of the JSP are
released, such as disconnecting from a database.
• service() method: This method is called automatically and retrieves a connection to HTTP.

JSP Tags
• A JSP program consists of a combination of HTML tags and JSP tags.
• JSP tags define Java code that is to be executed before the output of the JSP program is sent
to the browser.
• A JSP tag begins with a <%, which is followed by Java code, and ends with %>.
• JSP tags are embedded into the HTML component of a JSP program and are processed by a
JSP virtual engine such as Tomcat.
• Tomcat reads the JSP program whenever the program is called by a browser and resolves JSP
tags, then sends the HTML tags and related information to the browser.
• Java code associated with JSP tags in the JSP program is executed when encountered by
Tomcat, and the result of that process is sent to the browser.
• The browser knows how to display the result because the JSP tag is enclosed within an open
and closed HTML tag.

Types of JSP tags


There are five types as shown below:

1. Comment Tag

• Opens with <%-- and closes with --%>

2. Declaration statement tags

• Opens with <%! and is followed by a Java declaration statements that define variables, objects,
and methods that are available to other components of the JSP program, and ends with %>

3. Directive tags

• Opens with <%@ and commands the JSP virtual engine to perform a specific task, such as
importing a Java package required by objects and methods used in declaration statement. The
directive tag closes with %>.

• There are 3 commonly used directives:


CSE, KSIT, 2019-20 Page 203
Advanced Java & J2EE (17CS553) Study Material

– import: This directive is used to import Java packages into JSP program.

e.g. <%@ page import=― import java.sql.*‖; %>

– include: This directive inserts a specified file into the JSP program replacing the include
tag.

e.g. <%@ include file=―CS\HJR.html‖ %>

– taglib: This directive specifies a file that contains a tag library.

e.g. <%@ taglib uri=―myTags.tld‖ %>

4. Expression tags

An expression tag opens with <%= and is used for an expression statement whose result
replaces the expression tag when the JSP virtual engine resolves JSP tags. An expression tag closes
with %>.

e.g. <%! int age=20; %>


<%=age%>, here =age is replaced with 20.

5. Scriptlet tags

A scriptlet tag opens with <% and contains commonly used Java control statements and
loops. A scriptlet tag closes with %>.

e.g. <%! int grade=70; %>


<% if(grade>69){%>
<p> You have passed</p>
<% } %>
<% else {%>
<p>Better luck next time</p>
<% } %>

Variables and Objects

To declare variables and create objects use declaration statement tag <%! %> with expression tag.

JSP code for declaring variable

<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<%! int age=20; %>
<p>KSIT age is: <%=age%></p>
</body>
</html>
CSE, KSIT, 2019-20 Page 204
Advanced Java & J2EE (17CS553) Study Material

The output of the program is shown here

Age is: 20

JSP code for declaring variables

<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<%! int age=20;
float salary=999.99f;
int empid=9;
%>
<p>Age is: <%=age%><br />
Salary is: <%=salary%><br />
Emp ID is: <%=empid%><br />
</p>
</body>
</html>

The output of the program is shown here

Age is: 20
Salary is: 999.99
Emp ID is: 9

JSP code for creating objects

<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<%! String Name;
String[] Telephone={―080-1234567‖,‖+91-0123456789‖};
Vector assignments=new Vector();
%>
</body>
</html>

Methods

JSP code for defining and calling method

<html>

CSE, KSIT, 2019-20 Page 205


Advanced Java & J2EE (17CS553) Study Material

<head><title></title></head>
<body>
<%! int curve(int grade)
{
return 10+grade;
}
int curve(int grade,int curveValue)
{
return curveValue+grade;
}
%>
<p>Curve grade is: <%=curve(10,80)%></p>
<p>Curve grade is: <%=curve(70)%></p>
</body>
<html>

The output of the program is shown here

Curve grade is: 90

Curve grade is: 80

Control Statements:

if and switch statements


Both changes the flow of a JSP program

JSP code for using control statements

<html>
<head><title></title></head>
<body>
<%! int grade=70;%>
<% if(grade > 69){%>
<p>Pass</p>
<% }else {%>
<p>Better luck next time</p>
<%}%>
<% switch(grade){
case 90 : %>
<p>Your final grade is a A</p>
<% break;
case 80 : %>
<p>Your final grade is a B</p>
<% break;
case 70 : %>
<p>Your final grade is a C</p>
<% break;

CSE, KSIT, 2019-20 Page 206


Advanced Java & J2EE (17CS553) Study Material

case 60 : %>
<p>Your final grade is a F</p>
<% break;
}
%>
</body>
</html>

The output of the program is shown here

Pass

Your final grade is a C

Loops

• Three kinds of loop are commonly used in JSP program, these are

The for loop, the while loop, and the do…while loop.

• Loops play important role in JSP database programs because loops are used to populate
HTML tables with data in the result set.

JSP code using loops

<html>
<head><title></title></head>
<body>
<%! int[] grade={100,82,93};
int x=0;
%>
<p>
<table border="1">
<caption>Using for loop</caption>
<tr>
<td>First</td>
<td>Second</td>
<td>Third</td>
</tr>
<tr>
<% for(int i=0;i<3;i++){%>
<td><%=grade[i]%></td>
<%}%>
</tr>
</table>
</p>
<p>
<table border="1">

CSE, KSIT, 2019-20 Page 207


Advanced Java & J2EE (17CS553) Study Material

<caption>Using while loop</caption>


<tr>
<td>First</td>
<td>Second</td>
<td>Third</td>
</tr>
<tr>
<% while(x<3){%>
<td><%=grade[x]%></td>
<% x++;
}
%>
</tr>
</table>
</p>
<p>
<table border="1">
<caption>Using do-while loop</caption>
<tr>
<td>First</td>
<td>Second</td>
<td>Third</td>
</tr>
<tr>
<% x=0; do{%>
<td><%=grade[x]%></td>
<% x++;
}while(x<3);
%>
</tr>
</table>
</p>
</body>
<html>

The output of the program is shown here

Using for loop


First Second Third
100 82 93
Using while loop
First Second Third
100 82 93
Using do-while loop
First Second Third
100 82 93

CSE, KSIT, 2019-20 Page 208


Advanced Java & J2EE (17CS553) Study Material

JSP Implicit Objects:


• JSP supports nine automatically defined variables, which are also called implicit objects. These
variables are:

• request: This is the HttpServletRequest object associated with the request.

• response: This is the HttpServletResponse object associated with the response to the client.

• out: This is the PrintWriter object used to send output to the client.

• session: This is the HttpSession object associated with the request.

• application: This is the ServletContext object associated with application context.

• config: This is the ServletConfig object associated with the page.

• pageContext: This encapsulates use of server-specific features like higher performance JspWriters.

• page: This is simply a synonym for this, and is used to call the methods defined by the translated
servlet class.

• Exception: The Exception object allows the exception data to be accessed by designated JSP.

Request String
The browser generates a user request string whenever the submit button is selected. The user request string
consists of URL and the query string, the following shows a typical query string:

http://localhost:8080/fivea/ColorDemoM?colors=green

http://localhost:8080/fivea/BigOfThree?first=10&second=20&third=30

a) HTML code: Name.html

<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<form method="get" action="http://localhost:8080/fivea/Name.jsp">
Enter name: <input type="text" name="name" /> <br />
<input type="submit" value="OK" />
<input type="reset" value="Cancel" />
</form>
</body>

CSE, KSIT, 2019-20 Page 209


Advanced Java & J2EE (17CS553) Study Material

</html>
b) JSP code: Name.jsp

<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<% String n=request.getParameter("name");%>
<p>Hello your name is <%=n%></p>
</body>
</html>

Input

Query String: http://localhost:8080/fivea/Name.jsp?name=HJH

Output: Hello your name is HJH

Cookies
a) HTML code : JSPCookie.html

CSE, KSIT, 2019-20 Page 210


Advanced Java & J2EE (17CS553) Study Material

<html>
<head>
<title> New Document </title>
</head>
<body>
<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<form method="get" action="http://localhost:8080/fivea/JSPCookie.jsp">
Enter name: <input type="text" name="name" /> <br />
<input type="submit" value="OK" />
<input type="reset" value="Cancel" />
</form>
</body>
</html>
</body>
</html>

b) JSP Code for setting Cookie: JSPCookie.jsp


<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<% String MyCookieValue=request.getParameter("name");
String MyCookieName="ksit";
Cookie c=new Cookie(MyCookieName,MyCookieValue);
response.addCookie(c);
%>
<p>Cookie is set to <%=MyCookieValue%></p>

</body>
</html>

c) JSP Code for retrieving Cookie: GetJSPCookie.jsp

<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<% String MyCookieValue="";
String MyCookieName="ksit";
String CName, CValue;
int found=0;
Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++){
CName=cookies[i].getName();

CSE, KSIT, 2019-20 Page 211


Advanced Java & J2EE (17CS553) Study Material

CValue=cookies[i].getValue();
if(MyCookieName.equals(CName))
{

found=1;
MyCookieValue=CValue;
}
}
%>
<% if(found==1){%>

<p>Cookie name: <%=MyCookieName%></p>


<p>Cookie value: <%=MyCookieValue%></p>
<%}%>
</body>
</html>
The output of the program is shown here:

a)

b)

CSE, KSIT, 2019-20 Page 212


Advanced Java & J2EE (17CS553) Study Material

c)

CSE, KSIT, 2019-20 Page 213


Advanced Java & J2EE (17CS553) Study Material

Session Objects
A JSP database system is able to share information among JSP programs within a session by using a
session object.
Each time a session is created, a unique ID is assigned to the session and stored as a cookie.
The unique ID enables JSP programs to track multiple sessions simultaneously while maintain data
integrity of each session.
The session ID is used to prevent the intermingling of information from clients.
In addition to the session ID, a session object is also used to store other types of information, called
attributes.
An attribute can be login information, preferences, or even purchases placed in an electronic
shopping cart.

JSP Code for creating session

<%@ page import="java.io.*"%>


<%@ page import="java.util.*"%>
<%
Date createTime=new Date(session.getCreationTime());

CSE, KSIT, 2019-20 Page 214


Advanced Java & J2EE (17CS553) Study Material

Date lastAccessedTime=new Date(session.getLastAccessedTime());

String title="Welcome back to my Website";

Integer visitCount=new Integer(0);


String visitCountKey="Visitor";

String userIDKey=new String("KSIT");


String userID=new String("HJH");

if(session.isNew())
{
title="Welcome to my Website";
session.setAttribute(visitCountKey,visitCount);
session.setAttribute(userIDKey,userID);
}

visitCount=(Integer)session.getAttribute(visitCountKey);
visitCount+=1;
userID=(String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey,visitCount);
%>
<html>
<head><title>Session Tracking</title> </head>
<body>
<center>Session Tracking</center>
<table border=1>
<tr>
<th>Session Info</th>
<th>Value</th>
</tr>
<tr>
<th>ID</th>
<td><% out.print(session.getId()); %></td>
</tr>
<tr>
<th>Creation Time</th>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<th>Last Visited Time</th>
<td><% out.print(lastAccessedTime); %></td>
</tr>
<tr>
<th>User ID</th>
<td><% out.print(userID); %></td>
</tr>
<tr>
<th>Number of Visits</th>

CSE, KSIT, 2019-20 Page 215


Advanced Java & J2EE (17CS553) Study Material

<td><% out.print(visitCount); %></td>


</tr>
</table>
</body>
</html>

The output of the program is shown here:

TOMCAT CONFIGURATION AND SERVLET PROGRAMMING

1.SET VARIABLES

a)CATALINA_HOME b)JAVA_HOME c)JRE_HOME d)CLASSPATH

AS FOLLOWS

CATALINA_HOME=F:\Tomcat7\apache-tomcat-7.0.64

JAVA_HOME=C:\Program Files\Java\jdk1.7.0_25

CSE, KSIT, 2019-20 Page 216


Advanced Java & J2EE (17CS553) Study Material

JRE_HOME=C:\Program Files\Java\jdk1.7.0_25\jre

CLASSPATH=.;F:\Tomcat7\apache-tomcat-7.0.64\lib\servlet-api.jar;

2.Start Tomcat Server

F:\>%CATALINA_HOME%\bin\startup

3. Create folders, sub-folders and xml file as follows:

3a.Create sub-folder fivea in webapps folder

3b.Create sub-folder WEB-INF folder in fivea folder

3c. Create web.xml file and sub-folder classes in WEB-INF folder

Folder Tree Structure

F:\>tree tomcat7

Folder PATH listing

Volume serial number is 7A41-B90B

F:\TOMCAT7

└───apache-tomcat-7.0.64

├───bin

├───conf

│ └───Catalina

CSE, KSIT, 2019-20 Page 217


Advanced Java & J2EE (17CS553) Study Material

│ └───localhost

├───lib

├───logs

├───temp

├───webapps

│ ├───docs

│ │ ├───api

│ │ ├───appdev

│ │ │ └───sample

│ │ │ ├───docs

│ │ │ ├───src

│ │ │ │ └───mypackage

│ │ │ └───web

│ │ │ ├───images

│ │ │ └───WEB-INF

│ │ ├───architecture

│ │ │ ├───requestProcess

│ │ │ └───startup

│ │ ├───config

│ │ ├───elapi

│ │ ├───funcspecs

│ │ ├───images

│ │ ├───jspapi

│ │ ├───servletapi

│ │ ├───tribes

CSE, KSIT, 2019-20 Page 218


Advanced Java & J2EE (17CS553) Study Material

│ │ ├───WEB-INF

│ │ └───websocketapi

│ ├───examples

│ │ ├───jsp

│ │ │ ├───async

│ │ │ ├───cal

│ │ │ ├───checkbox

│ │ │ ├───colors

│ │ │ ├───dates

│ │ │ ├───error

│ │ │ ├───forward

│ │ │ ├───images

│ │ │ ├───include

│ │ │ ├───jsp2

│ │ │ │ ├───el

│ │ │ │ ├───jspattribute

│ │ │ │ ├───jspx

│ │ │ │ ├───misc

│ │ │ │ ├───simpletag

│ │ │ │ └───tagfiles

│ │ │ ├───jsptoserv

│ │ │ ├───num

│ │ │ ├───plugin

│ │ │ │ └───applet

│ │ │ ├───security

CSE, KSIT, 2019-20 Page 219


Advanced Java & J2EE (17CS553) Study Material

│ │ │ │ └───protected

│ │ │ ├───sessions

│ │ │ ├───simpletag

│ │ │ ├───snp

│ │ │ ├───tagplugin

│ │ │ └───xml

│ │ ├───servlets

│ │ │ ├───chat

│ │ │ └───images

│ │ ├───WEB-INF

│ │ │ ├───classes

│ │ │ │ ├───async

│ │ │ │ ├───cal

│ │ │ │ ├───chat

│ │ │ │ ├───checkbox

│ │ │ │ ├───colors

│ │ │ │ ├───compressionFilt

│ │ │ │ ├───dates

│ │ │ │ ├───error

│ │ │ │ ├───examples

│ │ │ │ ├───filters

│ │ │ │ ├───jsp2

│ │ │ │ │ └───examples

│ │ │ │ │ ├───el

│ │ │ │ │ └───simplet

CSE, KSIT, 2019-20 Page 220


Advanced Java & J2EE (17CS553) Study Material

│ │ │ │ ├───listeners

│ │ │ │ ├───num

│ │ │ │ ├───sessions

│ │ │ │ ├───util

│ │ │ │ ├───validators

│ │ │ │ └───websocket

│ │ │ │ ├───chat

│ │ │ │ ├───drawboard

│ │ │ │ │ └───wsmessa

│ │ │ │ ├───echo

│ │ │ │ ├───snake

│ │ │ │ └───tc7

│ │ │ │ ├───chat

│ │ │ │ ├───echo

│ │ │ │ └───snake

│ │ │ ├───jsp

│ │ │ │ └───applet

│ │ │ ├───jsp2

│ │ │ ├───lib

│ │ │ └───tags

│ │ ├───websocket

│ │ └───websocket-deprecated

│ ├───fivea

│ │ └───WEB-INF

│ │ └───classes

CSE, KSIT, 2019-20 Page 221


Advanced Java & J2EE (17CS553) Study Material

│ ├───fiveb

│ │ └───WEB-INF

│ │ └───classes

│ ├───harsha

│ │ └───WEB-INF

│ │ └───classes

│ ├───hjr

│ │ └───WEB-INF

│ │ └───classes

│ ├───host-manager

│ │ ├───images

│ │ ├───META-INF

│ │ └───WEB-INF

│ │ └───jsp

│ ├───manager

│ │ ├───images

│ │ ├───META-INF

│ │ └───WEB-INF

│ │ └───jsp

│ ├───ROOT

│ │ └───WEB-INF

│ ├───sevena

│ │ └───WEB-INF

│ │ ├───classes

│ │ └───lib

CSE, KSIT, 2019-20 Page 222


Advanced Java & J2EE (17CS553) Study Material

│ └───sevenb

│ └───WEB-INF

│ └───classes

└───work

└───Catalina

└───localhost

├───docs

├───examples

├───fivea

├───fiveb

├───harsha

│ └───org

│ └───apache

│ └───jsp

├───hjr

│ └───org

│ └───apache

│ └───jsp

├───host-manager

├───manager

├───sevena

│ └───org

│ └───apache

│ └───jsp

├───sevenb

CSE, KSIT, 2019-20 Page 223


Advanced Java & J2EE (17CS553) Study Material

└───_

└───org

└───apache

└───jsp

4.Create & Store Java and HTML files in the directory path shown below

F:\tomcat7\apache-tomcat-7.0.64\webapps\fivea

09/30/2019 03:11 PM <DIR> .

09/30/2019 03:11 PM <DIR> ..

09/30/2019 10:42 AM 661 Color.html

09/30/2019 10:41 AM 520 ColorDemo.java

09/30/2019 10:47 AM 397 ColorDemoM.java

09/30/2019 09:14 AM 433 HelloServlet.java

09/30/2019 09:23 AM 459 HelloServletM.java

09/30/2019 09:23 AM 460 HelloServletMM.java

09/30/2019 12:56 PM 601 Sort.html

09/30/2019 12:51 PM 699 SortDemo.java

09/30/2019 01:22 PM 668 SortDemoM.java

09/30/2019 09:06 AM <DIR> WEB-INF

Java Source files contents

CSE, KSIT, 2019-20 Page 224


Advanced Java & J2EE (17CS553) Study Material

import java.io.*;

import javax.servlet.*;

public class ColorDemo extends GenericServlet

public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException

res.setContentType("text/html");

PrintWriter pw=res.getWriter();

String c=req.getParameter("colors");

pw.println("<p style=color:c>"+c.toUpperCase()+" COLOR</p>");

import java.io.*;

import javax.servlet.*;

public class ColorDemoM extends GenericServlet

public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException

res.setContentType("text/html");

PrintWriter pw=res.getWriter();

String c=req.getParameter("colors");

CSE, KSIT, 2019-20 Page 225


Advanced Java & J2EE (17CS553) Study Material

pw.println("<p style=color:"+c+">"+c.toUpperCase()+" COLOR</p>");

import java.util.*;

import java.io.*;

import javax.servlet.*;

public class HelloServlet extends GenericServlet

Date d=new Date();

public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException

res.setContentType("text/html");

PrintWriter pw=res.getWriter();

pw.println("<b>Hello Welcome to Servlet</b>");

import java.util.*;

import java.io.*;

import javax.servlet.*;

public class HelloServletM extends GenericServlet

Date d=new Date();

public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException

CSE, KSIT, 2019-20 Page 226


Advanced Java & J2EE (17CS553) Study Material

res.setContentType("text/html");

PrintWriter pw=res.getWriter();

pw.println("<b>Hello Welcome to Servlet</b>"+

"<p>Today's date:"+d);

import java.util.*;

import java.io.*;

import javax.servlet.*;

public class HelloServletMM extends GenericServlet

Date d=new Date();

public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException

res.setContentType("text/html");

PrintWriter pw=res.getWriter();

pw.println("<b>Hello Welcome to Servlet</b>"+

"<p>Today's date:"+d);

import java.io.*;

import java.util.*;

import javax.servlet.*;

CSE, KSIT, 2019-20 Page 227


Advanced Java & J2EE (17CS553) Study Material

public class SortDemo extends GenericServlet

public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException

res.setContentType("text/html");

PrintWriter pw=res.getWriter();

String s=req.getParameter("nums");

String n[]=s.split(" ");

System.out.println("hello");

int i[]=new int[n.length] ;

for(int j=0;j<i.length;j++)

i[j]=(Integer.valueOf(n[j])).intValue();

Arrays.sort(i);

String s1="";

for(int j=0;j<i.length;j++)

s1+=(i[j]+" ");

pw.println("The unsorted array is :"+s);

pw.println("</br>");

pw.println("The sorted array is :"+s1);

import java.io.*;

import java.util.*;

import javax.servlet.*;

public class SortDemoM extends GenericServlet

CSE, KSIT, 2019-20 Page 228


Advanced Java & J2EE (17CS553) Study Material

public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException

res.setContentType("text/html");

PrintWriter pw=res.getWriter();

String s=req.getParameter("nums");

String n[]=s.split(" ");

int i[]=new int[n.length] ;

for(int j=0;j<i.length;j++)

i[j]=(Integer.valueOf(n[j])).intValue();

Arrays.sort(i);

String s1="";

for(int j=0;j<i.length;j++)

s1+=(i[j]+" ");

pw.println("The unsorted array is :"+s);

pw.println("</br>");

pw.println("The sorted array is :"+s1);

HTML Files Content

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title> New Document </title>

CSE, KSIT, 2019-20 Page 229


Advanced Java & J2EE (17CS553) Study Material

<meta name="Generator" content="EditPlus">

<meta name="Author" content="">

<meta name="Keywords" content="">

<meta name="Description" content="">

</head>

<body>

<form method="post" action="http://localhost:8080/fivea/ColorDemoM">

<label>Select Color</label>

<select name="colors">

<option value="red">RED</option>

<option value="orange">ORANGE</option>

<option value="green">GREEN</option>

</select>

<input type="submit" value="OK" />

</form>

</body>

</html>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title> New Document </title>

<meta name="Generator" content="EditPlus">

<meta name="Author" content="">

CSE, KSIT, 2019-20 Page 230


Advanced Java & J2EE (17CS553) Study Material

<meta name="Keywords" content="">

<meta name="Description" content="">

</head>

<body>

<form method="post" action="http://localhost:8080/fivea/SortDemo">

<label>Enter numbers separated by a space</label>

<input type="text" name="nums" />

<input type="submit" value="OK" />

<input type="reset" value="Clear" />

</form>

</body>

</html>

5. Compile and Store Java class files in the folder shown below

F:\tomcat7\apache-tomcat-7.0.64\webapps\fivea\web-inf\classes

09/30/2019 12:45 PM <DIR> .

09/30/2019 12:45 PM <DIR> ..

09/30/2019 10:41 AM 1,015 ColorDemo.class

09/30/2019 10:42 AM 1,032 ColorDemoM.class

09/30/2019 09:16 AM 892 HelloServlet.class

09/30/2019 09:21 AM 1,133 HelloServletM.class

CSE, KSIT, 2019-20 Page 231


Advanced Java & J2EE (17CS553) Study Material

09/30/2019 09:23 AM 1,135 HelloServletMM.class

09/30/2019 12:57 PM 1,692 SortDemo.class

6. Create web.xml in the folder shown below

F:\tomcat7\apache-tomcat-7.0.64\webapps\fivea\web-inf

09/30/2019 03:12 PM <DIR> .

09/30/2019 03:12 PM <DIR> ..

09/30/2019 12:45 PM <DIR> classes

09/30/2019 01:23 PM 1,630 web.xml

The contents (sample) of web.xml is shown below

<web-app>

<servlet>

<servlet-name>SortDemoM</servlet-name>

<servlet-class>SortDemoM</servlet-class>

</servlet>

<servlet>

<servlet-name>SortDemo</servlet-name>

<servlet-class>SortDemo</servlet-class>

</servlet>

<servlet>

CSE, KSIT, 2019-20 Page 232


Advanced Java & J2EE (17CS553) Study Material

<servlet-name>ColorDemoM</servlet-name>

<servlet-class>ColorDemoM</servlet-class>

</servlet>

<servlet>

<servlet-name>ColorDemo</servlet-name>

<servlet-class>ColorDemo</servlet-class>

</servlet>

<servlet>

<servlet-name>HelloServlet</servlet-name>

<servlet-class>HelloServlet</servlet-class>

</servlet>

<servlet>

<servlet-name>HelloServletM</servlet-name>

<servlet-class>HelloServletM</servlet-class>

</servlet>

<servlet>

<servlet-name>HelloServletMM</servlet-name>

<servlet-class>HelloServletMM</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloServlet</servlet-name>

<url-pattern>/HelloServlet</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>HelloServletM</servlet-name>

CSE, KSIT, 2019-20 Page 233


Advanced Java & J2EE (17CS553) Study Material

<url-pattern>/HelloServletM</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>HelloServletMM</servlet-name>

<url-pattern>/HelloServletMM</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>ColorDemo</servlet-name>

<url-pattern>/ColorDemo</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>ColorDemoM</servlet-name>

<url-pattern>/ColorDemoM</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>SortDemo</servlet-name>

<url-pattern>/SortDemo</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>SortDemoM</servlet-name>

<url-pattern>/SortDemoM</url-pattern>

</servlet-mapping>

</web-app>

7a. Enter in the browser address bar as follow

CSE, KSIT, 2019-20 Page 234


Advanced Java & J2EE (17CS553) Study Material

http://localhost:8080/fivea/HelloServlet

output on the browser window is as follows:

Hello Welcome to Servlet

7b. Enter in the browser address bar as follow

http://localhost:8080/fivea/Color.html

output on the browser window is as follows:

Select Option from drop-down list and click OK


CSE, KSIT, 2019-20 Page 235
Advanced Java & J2EE (17CS553) Study Material

The output on the browser window is as follow

7c. Enter in the browser address bar as follow

http://localhost:8080/fivea/Sort.html

Enter the numbers with one space between in the text box as shown below

CSE, KSIT, 2019-20 Page 236


Advanced Java & J2EE (17CS553) Study Material

output on the browser window is as follows:

CSE, KSIT, 2019-20 Page 237


Advanced Java & J2EE (17CS553) Study Material

CSE, KSIT, 2019-20 Page 238


Advanced Java & J2EE (17CS553) Study Material

Module-5
The Java Database Connectivity and Transactions

The Java Database Connectivity (JDBC)

The Java Database Connectivity (JDBC) API is the industry standard for database-independent connectivity
between the Java programming language and a wide range of databases SQL databases and other tabular
data sources, such as spreadsheets or flat files. The JDBC API provides a call-level API for SQL-based
database access.

JDBC technology allows you to use the Java programming language to exploit "Write Once, Run
Anywhere" capabilities for applications that require access to enterprise data. With a JDBC technology-
enabled driver, you can connect all corporate data even in a heterogeneous environment.

Java JDBC API


The Java Database Connectivity (JDBC) API provides universal data access from the Java programming
language. Using the JDBC API, you can access virtually any data source, from relational databases to
spreadsheets and flat files. JDBC technology also provides a common base on which tools and alternate
interfaces can be built.

The JDBC API is comprised of two packages:

java.sql
javax.sql

You automatically get both packages when you download the Java Platform Standard Edition (Java SE) 8.

To use the JDBC API with a particular database management system, you need a JDBC technology-based
driver to mediate between JDBC technology and the database. Depending on various factors, a driver might
be written purely in the Java programming language or in a mixture of the Java programming language and
Java Native Interface (JNI) native methods. To obtain a JDBC driver for a particular database management
system.

Java Database Connectivity (JDBC) Technology

The concept of JDBC

• JDBC driver: A translator that convert low-level proprietary DBMS messages to low level
messages understood by JDBC API, and vice-versa.
• JDBC API defines Java data objects which can be used by programmers to write routines that
interact with DBMS.

CSE, KSIT, 2019-20 Page 239


Advanced Java & J2EE (17CS553) Study Material

JDBC drivers created by DBMS manufacturers have to:

Open a connection between the DBMS and the J2EE component.


Translate low-level equivalents of SQL statements sent by the J2EE component into messages that
can be processed by the DBMS.
Return data that conforms to the JDBC specification to the JDBC driver.
Return information such as error messages that conforms to the JDBC specification to the JDBC
driver.
Provide transaction management routines that conform to the JDBC specification.
Close the connection between the DBMS and the J2EE component.

JDBC Driver Types

JDBC driver specification classifie JDBC drivers into four group. Each grou[ is referred to as a JDBC driver
type and addresses a specific need for communicating with various DBMSs. The JDBC driver types are as
follows:

– Type 1: JDBC-TO-ODBC Driver


– Type 2: Java/Native code Driver
– Type 3: JDBC Driver
– Type 4: JDBC Driver

Type 1 JDBC-to ODBC Driver

• Open Database Connection (ODBC) was created by Microsoft.


• Both JDBC and ODBC have similar driver specification and an API.
• Also called JDBC/ODBC bridge, is used to translate DBMS calls b/w the JDBC and ODBC
specifications.
• The JDBC-to-ODBC driver receives messages from a J2EE component that conforms to JDBC
specifications.
• Those messages are translated by JDBC-to-ODBC driver into ODBC message format which is
understood by the DBMS.

Disadvantage:

• Extra translation time might negatively impact performance in a mission critical applications.

Type 2 Java/ Native Code Driver

• Uses Java classes to generate Platform specific code that is understood by a specific DBMS.
• The manufacturer of DBMS provides both the Java/ Native code driver and API classes so the J2EE
component can generate the platform specific code.

Disadvantage:

• Loss of some portability of code.


• The API classes for the Java/ Native code driver probably won‘t work with another
manufacturer‘s DBMS.

Type 3 JDBC Driver


CSE, KSIT, 2019-20 Page 240
Advanced Java & J2EE (17CS553) Study Material

• Also referred to as the Java protocol, is the mostly used JDBC driver.
• Type 3 JDBC driver converts SQL queries into JDBC formatted statements.
• The JDBC formatted statements are translated into format required by the DBMS.

Type 4 JDBC Driver

• Also known as Type 4 database protocol, is similar to Type 3 JDBC driver except SQL queries are
translated into format required by the DBMS.
• SQL queries do not need to be converted to JDBC formatted systems.
• This is the fastest way to communicate SQL queries to the DBMS.

JDBC Packages

• The JDBC API is contained in two packages:


• Java.sql, contains core Java data objects of the JDBC API, provide basics for
connecting to the DBMS and interacting with data stored in DBMS. This package is
part of J2SE.
• Javax.sql, extends java.sql and is in J2EE. Java objects interact with JNDI (Java
Naming and Directory Interface), manage connection pooling.

A brief overview of the JDBC Process

• This process is divided into FIVE routines:


1. Loading the JDBC driver
2. Connecting to the DBMS
3. Creating and executing a statement
4. Processing data returned by the DBMS
5. Terminating the connection with the DBMS

1. Loading the JDBC driver

The JDBC driver must be loaded before the J2EE component can connect to the DBMS. The
Class.forName() method is used to load the JDBC driver. The following code snippet shows loading mysql
driver so a J2EE component can interact with MySql DBMS.

Code Snippet

import java.sql.*;

try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);
}

CSE, KSIT, 2019-20 Page 241


Advanced Java & J2EE (17CS553) Study Material

2. Connecting to the DBMS


Once the driver is loaded , the J2EE component must connect to the DBMS using the
DriverManager.getConnection() method. The java.sql.DriverManager is responsible for managing
driver information.
The DriverManager.getConnection() method is passed the URL of the database, the user ID and the
password if required by the DBMS. The general formof getConnection() method:

static Connection getConnection(String url, String user, String password) , where,

url is a String object that contains the driver name and the name of the database that is being
accessed by the J2EE component. This method returns a Connection interface.

The Connection interface manages the communication between driver and the J2EE component.
The Connection interface sends statements to the DBMS for processing.
Following is the code snippet:

Code Snippet

import java.sql.*;
Connection con=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System.err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);
}
try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");
}
catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);

3. Creating and executing a statement


The next step, after the JDBC driver is loaded and connection is successfully made with a particular
database managed by the DBMS, is to send a SQL query to the DBMS for processing.
A SQL query consists of a series of SQL commands that direct the DBMS to do something such as
to return rows of data to J2EE component.

CSE, KSIT, 2019-20 Page 242


Advanced Java & J2EE (17CS553) Study Material

The createStatement() of Connection interface is used to create a Statement object. The Statement
object is then used to execute a query and returns a ResultSet object that contains the response from
the DBMS, which is usually one or more rows of information requested by the J2EE component.
The following shows the code snippet:

CodeSnippet

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);

}
try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");
}

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);

}
try
{
stmt=con.createStatement();
rs=stmt.executeQuery("select * from student");
stmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception: "+e.getMessage());
System.exit(3);

CSE, KSIT, 2019-20 Page 243


Advanced Java & J2EE (17CS553) Study Material

4. Processing data returned by the DBMS


The java.sql.ResultSet object is assigned the results received from the DBMS after the query is
processed.
The java.sql.ResultSet object consists of methods (e.g getXXX(), where XXX is Java data type) used
to interact with data that is returned by the DBMS to the J2EE component.
The following shows the code snippet:

Code Snippet

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");
}

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);

}
try{
stmt=con.createStatement();
rs=stmt.executeQuery("select * from student");
stmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
try

CSE, KSIT, 2019-20 Page 244


Advanced Java & J2EE (17CS553) Study Material

{
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
}

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

5. Terminating the connection with the DBMS


The connection to the DBMS is terminated by using the close() method of the Connection object
once the J2EE component is finished accessing the DBMS.

Code Snippet

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);
}

try{
stmt=con.createStatement();
rs=stmt.executeQuery("select * from student");

CSE, KSIT, 2019-20 Page 245


Advanced Java & J2EE (17CS553) Study Material

stmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
try
{
while(rs.next())
System. out.println(rs.getString(1)+" "+rs.getString(2));
}

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

}
try
{
res.close();
con.close();
}
catch (SQLException e)
{
System. err.println ("Connection Close Exception "+e.getMessage());
System.exit(5);

Classes in java.sql package

Class Description

DriverManager The basic service for managing a set of


JDBC drivers.
Timestamp A thin wrapper around java.util.Date that
allows the JDBC API to identify this as an
SQL TIMESTAMP value.

Interface Description

CSE, KSIT, 2019-20


Interfaces in java.sql Page 246
package
Advanced Java & J2EE (17CS553) Study Material

CallableStatement The interface used to execute SQL stored procedures.

Connection A connection (session) with a specific database.

Driver The interface that every driver class must implement.


State
ment
PreparedStatement An object that represents a precompiled SQL statement. obje
cts
ResultSet A table of data representing a database result set, which is usually
generated by executing a statement that queries the database. –
tatem
Statement The object used for executing a static SQL statement and returning the ent :
results it produces.
used
to
execute query
– PreparedStatement : used to execute a compiled query
– CallableStatement : used to execute store procedures

Statement Object

• Statement object: used to execute query immediately.


• Methods:
– executeQuery(): SQL query is passed as an argument, the query is then transmitted to the
DBMS for processing.
• This method returns one ResultSet object that contains rows, columns, and metadata
that represent data requested by query.
– execute(): is used when there may be multiple results returned.
– executeUpdate() : is used to execute queries that contain INSERT, UPDATE,DELETE and
DDL SQL statements.
• This method returns an integer indicating the number of rows that were updated by
the query.

Code Snippet (using the statement object to execute a query)

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());

CSE, KSIT, 2019-20 Page 247


Advanced Java & J2EE (17CS553) Study Material

System.exit(1);
}

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");
}

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);
}

try{
stmt=con.createStatement();
rs=stmt.executeQuery("select * from student");
stmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
try
{
while(rs.next())
System. out.println(rs.getString(1)+" "+rs.getString(2));
}

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

}
try
{
Res.close();
con.close();
}
catch (SQLException e)
{
System. err.println ("Connection Close Exception "+e.getMessage());
System.exit(5);

CSE, KSIT, 2019-20 Page 248


Advanced Java & J2EE (17CS553) Study Material

Code Snippet (using the executeUpdate() method)

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);
}

try{
stmt=con.createStatement();
rs=stmt.executeUpdate("update stud set PAID=’Y’ WHERE
BALANCE=’0’");
stmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
try
{
while(rs.next())
System. out.println(rs.getString(1)+" "+rs.getString(2));
}

CSE, KSIT, 2019-20 Page 249


Advanced Java & J2EE (17CS553) Study Material

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

}
try
{
res.close();
con.close();
}
catch (SQLException e)
{
System. err.println ("Connection Close Exception "+e.getMessage());
System.exit(5);

PreparedStatement object

• A SQL must be compiled before DBMS process the query.


• Disadvantage: can become an expensive overhead if the query is executed several times by the same
instance of the J2EE component during the same session.
• Methods:
– setXXX(), e.g setString(), setInteger() etc.
– The above method requires TWO arguments, the first an integer that identifies the position of
the placeholder and the second parameter a value that will be replace at the position specified
in the first argument.
– executeQuery(): doesn‘t require an argument unlike that of Statement object.
– execute() and executeUpdate() methods similar to Statement object‘s methods.

Code Snippet (using the executeUpdate() method of PreparedStatement)

import java.sql.*;
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{

CSE, KSIT, 2019-20 Page 250


Advanced Java & J2EE (17CS553) Study Material

System. err.println ("Unable to load MySQL Driver."+e.getMessage());


System.exit(1);

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);
}

try{
query=‖SELECT * FROM STUD WHERE USN=?‖;
pstmt=con.preparedStatement(query);
pstmt.setString(1,”123”);
rs=stmt.executeQuery();
pstmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
try
{
while(rs.next())
System. out.println(rs.getString(1)+" "+rs.getString(2));
}

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

}
try
{
res.close();
con.close();
}
catch (SQLException e)
{
CSE, KSIT, 2019-20 Page 251
Advanced Java & J2EE (17CS553) Study Material

System. err.println ("Connection Close Exception "+e.getMessage());


System.exit(5);

CallableStatement object

• Is used to call a stored procedure from within a J2EE object.


• A stored procedure a block of code and is identified by a unique name. It is executed by invoking the
name.
• Parameters/ Arguments used when calling a stored procedure
– IN, OUT, INOUT
• The IN parameter/ argument contains any data that needs to be passed to the stored procedure and
whose value is assigned using the setXXX() methods.
• The OUT parameter/ argument contains the value returned by the stored procedure, if any.
– The OUT parameter/ argument must be registered using the registerOutParameter(arg1,arg2)
method and is retrieved by J2EE component using getXXX().
• The INOUT is a single parameter/ argument that is used to both pass to and retrieve values from a
stored procedure.
• E.g. registerOutParameter(1, Types.VARCHAR);
– Here first argument 1 specifies that number of arguments to stored procedure is 1.
– The second argument is the data type of the value returned by the stored procedure.
• Methods
– execute() with no argument.
– Code snippet

Connection db=null;
String lastOrderNum;
try
{
String query=―{CALL LastOrderNumber(?)}‖;
CallableStatement cstmt=db.prepareCall(query);
cstmt.registerOutParameter(1,Types.VARCHAR);
cstmt.execute();
lastOrderNum=cstmt.getString();
cstmt.close();
}
Catch(..){}

ResultSet object
• ResultSet object contains methods that are used to copy data from the ResultSet into a Java
collection object or variable for further processing.
• Data in ResultSet object is logically organized into a virtual table consisting of rows and columns.
• In addition to table/ data this object also contains metadata such as names, size and data type of
column.

CSE, KSIT, 2019-20 Page 252


Advanced Java & J2EE (17CS553) Study Material

• Virtual cursor: point to a row of virtual table. A J2EE component moves the virtual cursor to each
row and then uses other methods of ResultSet object to interact with the data.
• next() method moves virtual cursor to next row in virtual table. This method returns true a boolean
value if the row contains data; otherwise false.
• getXXX() method is used to copy data from the row to a collection or variable or object.
• E.g. getString(―SNAME‖), getInt(―AGE‖)
• Note: Virtual cursor can be moved in only one direction.

Reading the ResultSet

Methods to read values from a Resultset into variables that can be later further processed by the J2EE
components are:

getString(), getDate(), getInt(), getLong()

Code Snippet for reading the results

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);
}

try{
query=‖SELECT * FROM STUD ―;
stmt=con.createStatement();
rs=stmt.executeQuery(query);
CSE, KSIT, 2019-20 Page 253
Advanced Java & J2EE (17CS553) Study Material

stmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
try
{
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
}

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

}
try
{
res.close();
con.close();
}
catch (SQLException e)
{
System. err.println ("Connection Close Exception "+e.getMessage());
System.exit(5);

Scrollable ResultSet

• Virtual cursor can be moved backwards or even positioned at a specific row.


• Six methods in addition to next() method to position cursor are
– first(), last(), previous(), absolute(), relative(), and getRow().
• The Statement object that is created using the createStatement() method of the Connection object
must be set up to handle a scrollable ResultSet by passing the createStatement() method one of the
three constants shown below:

Constant Description
TYPE_FORWARD_ONLY This constant restricts the virtual cursor to
downward movement, which is default setting.
TYPE_SCROLL_INSENSITIVE This constant permits virtual cursor to move in

CSE, KSIT, 2019-20 Page 254


Advanced Java & J2EE (17CS553) Study Material

both directions.

This constant makes the ResultSet insensitive to


changes made by another J2EE component to
data in the table whose rows are reflected in the
ResultSet.
TYPE_SCROLL_SENSITIVE This constant permits virtual cursor to move in
both directions.

This constant makes the ResultSet sensitive to


changes made by another J2EE component to
data in the table whose rows are reflected in the
ResultSet.

Code Snippet for reading using Scrollable ResultSet

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);
}

try{
query=‖SELECT * FROM STUD ―;
stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE);
rs=stmt.executeQuery(query);
stmt.close();

CSE, KSIT, 2019-20 Page 255


Advanced Java & J2EE (17CS553) Study Material

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
try
{
while(rs.next())
rs.first();
rs.last();
rs.previous();
rs.absolute(10);
rs.relative(-2);
rs.relative(2);
System. out..println(rs.getString(1)+" "+rs.getString(2));
}

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

}
try
{
res.close();
con.close();
}
catch (SQLException e)
{
System. err.println ("Connection Close Exception "+e.getMessage());
System.exit(5);

Updateable ResultSet

Update ResultSet
Delete row in the ResultSet
Insert row in the ResultSet

Update ResultSet

CSE, KSIT, 2019-20 Page 256


Advanced Java & J2EE (17CS553) Study Material

Rows contained in the ResultSet can be updatable similar to how rows in a table can be updated. This is
made possible by passing constants to the createStatement() of the Connection object as shown below:

• Constants to be passed to createStatement() method:


– CONCUR_UPDATABLE
– CONCUR_READ_ONLY, this constant prevent the ResultSet from being updated.
• Once the executeQuery() method of the Statement object returns a ResultSet, the following methods
can be used for updating:
– updateXXX(), change the value of a column in the current row of the Resultset object. E.g.
updateString(―lastname‖,‖hjr‖); (XXX is replaced with the data type of the column that is to
be updated)
– updateRow(), this method changes values in the columns of the current row of the ResultSet
object based on the values of the updateXXX() methods.
– updateNull(), A value in a column of the ResultSet can be replaced with a NULL value by
passing the column number to this method in the current row of the ResultSet.

Code Snippet for reading using Scrollable ResultSet

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);
}

try{
query=‖SELECT * FROM STUD WHERE USN=1KS17CS999―;
stmt=con.createStatement(ResultSet.CONCUR_UPDATABLE);
CSE, KSIT, 2019-20 Page 257
Advanced Java & J2EE (17CS553) Study Material

rs=stmt.executeQuery(query);
stmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
boolean records=rs.next();
if(!records)
{
System.out.println(―No data returned‖);
System.exit(9);
}
try
{
rs.updateString(―USN‖,‖1KS17CS099‖);
rs.updateRow();
rs.close();
}

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

}
try
{
con.close();
}
catch (SQLException e)
{
System. err.println ("Connection Close Exception "+e.getMessage());
System.exit(5);

Delete Row in the ResultSet

• The method deleteRow() is used to remove a row from a ResultSet. This also deletes row from the
underlying DB.
• The general form:
– void deleteRow(int rownumber);

CSE, KSIT, 2019-20 Page 258


Advanced Java & J2EE (17CS553) Study Material

Code Snippet for reading Deleting row

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);
}

try{
query=‖SELECT * FROM STUD WHERE USN=1KS17CS999―;
stmt=con.createStatement();
rs=stmt.executeQuery(query);
stmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
boolean records=rs.next();
if(!records)
{
System.out.println(―No data returned‖);
System.exit(9);
}

CSE, KSIT, 2019-20 Page 259


Advanced Java & J2EE (17CS553) Study Material

try
{
rs.deleteRow(0);// deletes the current row
rs.close();
}

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

}
try
{
con.close();
}
catch (SQLException e)
{
System. err.println ("Connection Close Exception "+e.getMessage());
System.exit(5);

Insert Row in the ResultSet

• Method updateXXX(arg1,arg2) is used to specify the column and the value that will be placed into
the columns of the ResultSet object.
• Next insertRow() method is called to insert the row into ResultSet object.
• This also updates the underlying database.

Code Snippet for reading Inserting row

import java.sql.*;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean records;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
System.exit(1);

CSE, KSIT, 2019-20 Page 260


Advanced Java & J2EE (17CS553) Study Material

try
{
con=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage());
System.exit(2);
}

try{
query=‖SELECT * FROM STUD WHERE USN=1KS17CS999―;
stmt=con.createStatement();
rs=stmt.executeQuery(query);
stmt.close();
}

catch (SQLException e)
{
System. err.println ("Statement Exception"+e.getMessage());
System.exit(3);

}
boolean records=rs.next();
if(!records)
{
System.out.println(―No data returned‖);
System.exit(9);
}
try
{
rs.updateString(1,”1KS17CS001”);
rs.updateString(2,”HJH”);
rs.insertRow();
rs.close();
}

catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);

}
try
{
con.close();
CSE, KSIT, 2019-20 Page 261
Advanced Java & J2EE (17CS553) Study Material

}
catch (SQLException e)
{
System. err.println ("Connection Close Exception "+e.getMessage());
System.exit(5);

Transaction Processing

• A transaction may involve many tasks.


• A transaction is incomplete even if one task fails; otherwise transaction is successful.
• A database transaction consists of a set of SQL statements, each of must be successfully completed
for the transaction to be completed.
• Until the J2EE components calls the commit() method of Connection object, the transaction is
incomplete.
• Some of the methods used in Transaction Processing:

Table: Transaction Processing

Method Description
void commit() Makes all changes made since the previous
commit/rollback permanent and releases any database
locks currently held by this Connection object.
void Sets this connection's auto-commit mode to the given
setAutoCommit(boolean autoCommit) state.

void rollback() Undoes all changes made in the current transaction


and releases any database locks currently held by this
Connection object.
void rollback(Savepoint savepoint) Undoes all changes made after the given Savepoint
object was set.

Savepoint setSavepoint(String name) Creates a savepoint with the given name in the current
transaction and returns the new Savepoint object
that represents it.
void Removes the specified Savepoint and subsequent
releaseSavepoint(Savepoint savepoint) Savepoint objects from the current transaction.

void addBatch(String sql) Adds the given SQL command to the current list of
commands for this Statement object.

CSE, KSIT, 2019-20 Page 262


Advanced Java & J2EE (17CS553) Study Material

Int[] executeBatch() Submits a batch of commands to the database for


execution and if all commands execute successfully,
returns an array of update counts.
void clearBatch() Empties this Statement object's current list of SQL
commands.

Code snippet for processing a transaction (using commit() and rollback() methods)

import java.sql.*;
Connection Database=null;
Statement DataRequest1=null, DataRequest2=null;
String query1, query2;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
}

try
{
Database=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");
}

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage())
}
try
{
Database.setAutoCommit(false);
query1=‖UPDATE stud SET Street=‘ 2nd Cross‘ WHERE Name=‘HJH‘‖;
query2=‖UPDATE stud SET Street=‘ 9th Cross‘ WHERE Name=‘Ganavi‘‖;
DataRequest1=Database.createStatement();
DataRequest2=Database.createStatement();
DataRequest1.executeUpdate(query1);
DataRequest2.executeUpdate(query2);
Database.commit();
DataRequest1.close();
DataRequest2.close();
Database.close();
}
catch(SQLException e)
{
System.err.println(―SQL Exception: ―+e.getMessage());
}

CSE, KSIT, 2019-20 Page 263


Advanced Java & J2EE (17CS553) Study Material

If(con != null)
{
try
{
Sytem.err.printl(―Transaction is being rolled back.‖);
Database.rollback();
}
catch(SQLException e)
{
System.err.println(―SQL Exception: ―+e.getMessage());
}
}
(h2) Savepoint

Code snippet for how to create a savepoint (set & release save points)

The J2EE component can control the number of tasks that are rolled back by using savepoints.
There can be many savepoints used in a transaction. Each savepoint is identified by a unique name.
Methods used to set and releasesave points: setSavePoint(),releaseSavePoint()
The syntax of setSavePoint() and releaseSavePoint() methods are shown in the table Transaction
Processing.

import java.sql.*;
Connection Database=null;
Statement DataRequest1=null, DataReuest2=null;
String query1, query2;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
}

try
{
Database=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");
}

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage()) ;
}
try
{
Database.setAutoCommit(false);
query1=‖UPDATE stud SET Street=‘ 2nd Cross‘ WHERE Name=‘HJH‘‖;
query2=‖UPDATE stud SET Street=‘ 9th Cross‘ WHERE Name=‘Ganavi‘‖;
DataRequest1=Database.createStatement();

CSE, KSIT, 2019-20 Page 264


Advanced Java & J2EE (17CS553) Study Material

Savepoint s1=Database.setSavePoint(“sp1”);
DataRequest2=Database.createStatement();
DataRequest1.executeUpdate(query1);
DataRequest2.executeUpdate(query2);
Database.commit();
DataRequest1.close();
DataRequest2.close();
Database.releaseSavePoint(“sp1”);
Database.close();
}
catch(SQLException e)
{
try{
Database.rollback(“sp1”);
}
catch (SQLException e1)
{
System. err.println ("roll back error"+e1.getMessage());
System.exit(3);
}
System. err.println ("SQL error"+e.getMessage());
System.exit(4);

(h2) Batch Statements

Code snippet for - how to batch SQL statements

A way to combine SQL statements into a transaction is to batch together these statements into a
single transaction and then execute the entire transaction.
Method to add SQL statements in to batch: addBatch().
Method to execute batch: executeBatch().
Method to clear batch: clearBatch()
The syntax of these methods are shown in the table: Transaction Processing

import java.sql.*;
Connection Database=null;
Statement DataRequest=null; String query1, query2;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System. err.println ("Unable to load MySQL Driver."+e.getMessage());
}

CSE, KSIT, 2019-20 Page 265


Advanced Java & J2EE (17CS553) Study Material

try
{
Database=DriverManager.getConnection(jdbc:mysql://localhost:3306/ksit_stud","root","Ksit123");
}

catch (SQLException e)
{
System. err.println ("Cannot connect to the database."+e.getMessage())
}
try
{
Database.setAutoCommit(false);
query1=‖UPDATE stud SET Street=‘ 2nd Cross‘ WHERE Name=‘HJH‘‖;
query2=‖UPDATE stud SET Street=‘ 9th Cross‘ WHERE Name=‘Ganavi‘‖;
DataRequest=Database.createStatement();
DataRequest.addBatch(query1);
DataRequest.addBatch(query2);
Int[] updated=Datarequest.executeBatch();
Database.commit();

DataRequest.close();
Database.close();
}
catch(BatchUpdateException error)
{
System.err.println(―Batch Error‖);
System.err.println(―SQL State: ‖+ error.getSQLState());
System.err.println(―Message: ‖+ error.getSQLState());
System.err.println(―Vendor: ―+error.getErrorCode());
int count=updated.length();
for(int i=0;i<count;i++)
System.out.println(updated[i]);

SQLException sql= error;


while(sql != null)
{
System.err.println(―SQL error: ‖+sql);
sql=sql.genNextException();
}
try{
DataRequest.clearBatch();
}
catch(BatchUpdateException error1)
{
System.err.println(―Unable to clear the batch: ‖+error1.getMessage());

}
}
}

CSE, KSIT, 2019-20 Page 266


Advanced Java & J2EE (17CS553) Study Material

ResultSet Holdability

• Whenever commit() method is called, all ResultSet objects that were created for the transactions are
closed.
• Sometimes J2EE components require to keep the ResultSet open even after the commit() method is
called.
• Call commit() method by passing one of two constants to the createStatement() method:
• HOLD_CURSORS_OVER_COMMIT : keeps ResultSet objects open
• CLOSE_CURSORS_AT_COMMIT : closes ResultSet objects

RowSet object

• The JDBC RowSet object is used to encapsulate a ResultSet fo use with EJB.
• A RowSet object contains rows of data from a table(s) that can be used in a disconnected operation.

Connection object’s methods

• createStatement()
• preparedStatement()
• preparedCall()
• 3 constants viz.,
• TYPE_FORWARD_ONLY
• TYPE_SCROLL_INSENSITIVE
• TYPE_SCROLL_SENSITIVE

TYPE_FORWARD_ONLY

• TYPE_FORWARD_ONLY: The result set cannot be scrolled; its cursor moves forward only, from
before the first row to after the last row. The rows contained in the result set depend on how the
underlying database generates the results. That is, it contains the rows that satisfy the query at either
the time the query is executed or as the rows are retrieved.

TYPE_SCROLL_INSENSITIVE

• TYPE_SCROLL_INSENSITIVE: The result can be scrolled; its cursor can move both forward and
backward relative to the current position, and it can move to an absolute position. The result set is
insensitive to changes made to the underlying data source while it is open. It contains the rows that
satisfy the query at either the time the query is executed or as the rows are retrieved.

TYPE_SCROLL_SENSITIVE

• TYPE_SCROLL_SENSITIVE: The result can be scrolled; its cursor can move both forward and
backward relative to the current position, and it can move to an absolute position. The result set
reflects changes made to the underlying data source while the result set remains open.

Auto-Generated Keys
It is common for a DBMS to automatically generate unique keys for a table a rows are inserted into
the table.

CSE, KSIT, 2019-20 Page 267


Advanced Java & J2EE (17CS553) Study Material

The getGeneratedKeys() method of the Statement object is called to return keys generated by the
DBMS.
The getGeneratedKeys() returns a ResultSet object.
Use ResultSet.getMetaData() method to retrieve metadata relating to the automatically generated
key, such as the type and properties of the automatically generated key.

Metadata
Metadata is data about data.
A J2EE componenet can access metadata by using the DatabaseMetaData interface.
The DatabaseMetaData interface is used to retrieve information about databases, tables, columns,
and indexes among other information about the DBMS.
A J2EE component retrieves metadata about the database by calling getMetaData() method of the
Connection object. The getMetaData() method returns a DatabaseMetaData object that contains
information about the database and its components.
Once the DatabaseMetaData object is obtained, an assortment of methods contained in the
DatabaseMetaData object are called to retrieve a specific metadata. Here are some of the more
commonly used DatabaseMetaData object methods:

Method Description
getDatabaseProductName() Returns the product name of the database.
getUserName() Returns the user name.
getURL() Returns the URL of the database.
getSchemas() Return all the schema names available in this
database.
getPrimaryKeys() Returns primary key.
getProcedures() Returns the stored procedure names.
getTables() Returns names of tables in the database.

Resultset Metadata
There are two types of metadata that can be retrieved from the DBMS namely:

Metadata - that describes the database.


Resultset Metadata – that describes the ResultSet.

Metadata that describes the ResultSet is retrieved by calling the getMetaData() method of the ResultSet
object. This returns a ResultSetMetaData object, as is shown in the following code statement:

ResultSetMetaData rm=Result.getMetaData()

Once the ResultSet metadata is retrieved, the J2EE component can call methods of the ResultSetMetaData
object to retrieve specific kinds of metadata. The more commonly called methods are as follows:

Method Description
CSE, KSIT, 2019-20 Page 268
Advanced Java & J2EE (17CS553) Study Material

getColumnCount() Returns the number of columns contained in the ResultSet.


getColumnName(int Returns the name of the column specified by the column number.
col_num)
getColumnType(int Returns the data type of the column specified by the column number.
col_num)

Data Types
The setxxx() and getxxx() methods are used to set/ get a value of a specific data type. Replace xxx with one
of Java types listed below.

The following table contains a list of data types and their Java equivalents:

SQL Type Java Type


CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC Java.math.BigDecimal
DECIMAL Java.math.BigDecimal
BIT Boolean
TINYINT Byte
SMALLINT Short
INTEGER Integer
BIGINT Long
REAL Float
FLOAT Float
DOUBLE Double
BINARY Byte[]
VARBINARY Byte[]
LONGVARBINARY Byte[]
BLOB Java.sql.Blob
CLOB Java.sql.Clob
ARRAY Java.sql.Array
STRUCT Java.sql.Struct
REF Java.sql.Ref
DATALINK Java.sql.Types
DATE Java.sql.Date
TIME Java.sql.Time
TIMESTAMP Java.sql.Timestamp

Exceptions
There are three kinds of exceptions that are thrown by JDBC methods. The following table shows the exceptions:

Exception Description
SQLException Commonly reflect a SQL syntax error in the
query and are thrown by many methods in the
java.sql package. The getNextException()
method of the SQLException object is used to
CSE, KSIT, 2019-20 Page 269
Advanced Java & J2EE (17CS553) Study Material

return details about the SQL error or a null if the


last exception was retrieved. The getErrorCode()
method of the SQLException object is used to
retrieve vendor-specific error code.

SQLWarning Throws warnings received by the Connection from the


DBMS.
SQLWarning getWarnings()
Retrieves the first warning reported by calls on this
Connection object.

DataTruncation Whenever data is lost due to truncation of the data


value, a DataTruncation exception is thrown.

Others

BatchUpdateException
SQLClientInfoException
SQLDataException
SQLFeatureNotSupportedException
SQLIntegrityConstraintViolationException
SQLInvalidAuthorizationSpecException
SQLNonTransientConnectionException
SQLNonTransientException
SQLRecoverableException
SQLSyntaxErrorException
SQLTimeoutException
SQLTransactionRollbackException
SQLTransientConnectionException
SQLTransientException

Note: Code snippets are to be tested.

CSE, KSIT, 2019-20 Page 270


Advanced Java & J2EE (17CS553) Study Material

JDBC Interfaces and Classes Quick Reference Guide

java.sql

Interface DatabaseMetaData
public interface DatabaseMetaData
extends Wrapper

This interface is implemented by driver vendors to let users know the capabilities of a Database
Management System (DBMS) in combination with the driver based on JDBCTM technology ("JDBC driver")
that is used with it. Different relational DBMSs often support different features, implement features in
different ways, and use different data types. In addition, a driver may implement a feature on top of what the
DBMS offers. Information returned by methods in this interface applies to the capabilities of a particular
driver and a particular DBMS working together. Note that as used in this documentation, the term
"database" is used generically to refer to both the driver and DBMS.

A user for this interface is commonly a tool that needs to discover how to deal with the underlying DBMS.
This is especially true for applications that are intended to be used with more than one DBMS. For example,
a tool might use the method getTypeInfo to find out what data types can be used in a CREATE TABLE
statement. Or a user might call the method supportsCorrelatedSubqueries to see if it is possible to use a
correlated subquery or supportsBatchUpdates to see if it is possible to use batch updates.

Some DatabaseMetaData methods return lists of information in the form of ResultSet objects. Regular
ResultSet methods, such as getString and getInt, can be used to retrieve the data from these ResultSet
objects. If a given form of metadata is not available, an empty ResultSet will be returned. Additional
columns beyond the columns defined to be returned by the ResultSet object for a given method can be
defined by the JDBC driver vendor and must be accessed by their column label.

Some DatabaseMetaData methods take arguments that are String patterns. These arguments all have names
such as fooPattern. Within a pattern String, "%" means match any substring of 0 or more characters, and "_"
means match any one character. Only metadata entries matching the search pattern are returned. If a search
pattern argument is set to null, that argument's criterion will be dropped from the search.
CSE, KSIT, 2019-20 Page 271
Advanced Java & J2EE (17CS553) Study Material

Method Summary
Methods

Modifier and
Method and Description
Type

allProceduresAreCallable()

boolean Retrieves whether the current user can call all the procedures returned by the method
getProcedures.

allTablesAreSelectable()

boolean Retrieves whether the current user can use all the tables returned by the method getTables in a
SELECT statement.

autoCommitFailureClosesAllResultSets()

boolean Retrieves whether a SQLException while autoCommit is true inidcates that all open ResultSets
are closed, even ones that are holdable.

dataDefinitionCausesTransactionCommit()

boolean Retrieves whether a data definition statement within a transaction forces the transaction to
commit.

dataDefinitionIgnoredInTransactions()
boolean
Retrieves whether this database ignores a data definition statement within a transaction.

deletesAreDetected(int type)

boolean Retrieves whether or not a visible row delete can be detected by calling the method
ResultSet.rowDeleted.

doesMaxRowSizeIncludeBlobs()

boolean Retrieves whether the return value for the method getMaxRowSize includes the SQL data types
LONGVARCHAR and LONGVARBINARY.

generatedKeyAlwaysReturned()

boolean Retrieves whether a generated key will always be returned if the column name(s) or index(es)
specified for the auto generated key column(s) are valid and the statement succeeds.

getAttributes(String catalog, String schemaPattern,


ResultSet String typeNamePattern, String attributeNamePattern)

Retrieves a description of the given attribute of the given type for a user-defined type (UDT) that

CSE, KSIT, 2019-20 Page 272


Advanced Java & J2EE (17CS553) Study Material

is available in the given schema and catalog.

getBestRowIdentifier(String catalog, String schema, String table,


int scope, boolean nullable)
ResultSet
Retrieves a description of a table's optimal set of columns that uniquely identifies a row.

getCatalogs()
ResultSet
Retrieves the catalog names available in this database.

getCatalogSeparator()
String
Retrieves the String that this database uses as the separator between a catalog and table name.

getCatalogTerm()
String
Retrieves the database vendor's preferred term for "catalog".

getClientInfoProperties()
ResultSet
Retrieves a list of the client info properties that the driver supports.

getColumnPrivileges(String catalog, String schema, String table,


String columnNamePattern)
ResultSet
Retrieves a description of the access rights for a table's columns.

getColumns(String catalog, String schemaPattern, String tableNamePattern,


String columnNamePattern)
ResultSet
Retrieves a description of table columns available in the specified catalog.

getConnection()
Connection
Retrieves the connection that produced this metadata object.

getCrossReference(String parentCatalog, String parentSchema,


String parentTable, String foreignCatalog, String foreignSchema,
String foreignTable)
ResultSet
Retrieves a description of the foreign key columns in the given foreign key table that reference
the primary key or the columns representing a unique constraint of the parent table (could be the
same or a different table).

getDatabaseMajorVersion()
int
Retrieves the major version number of the underlying database.

int getDatabaseMinorVersion()

CSE, KSIT, 2019-20 Page 273


Advanced Java & J2EE (17CS553) Study Material

Retrieves the minor version number of the underlying database.

getDatabaseProductName()
String
Retrieves the name of this database product.

getDatabaseProductVersion()
String
Retrieves the version number of this database product.

getDefaultTransactionIsolation()
int
Retrieves this database's default transaction isolation level.

getDriverMajorVersion()
int
Retrieves this JDBC driver's major version number.

getDriverMinorVersion()
int
Retrieves this JDBC driver's minor version number.

getDriverName()
String
Retrieves the name of this JDBC driver.

getDriverVersion()
String
Retrieves the version number of this JDBC driver as a String.

getExportedKeys(String catalog, String schema, String table)

ResultSet Retrieves a description of the foreign key columns that reference the given table's primary key
columns (the foreign keys exported by a table).

getExtraNameCharacters()

String Retrieves all the "extra" characters that can be used in unquoted identifier names (those beyond
a-z, A-Z, 0-9 and _).

getFunctionColumns(String catalog, String schemaPattern,


String functionNamePattern, String columnNamePattern)
ResultSet
Retrieves a description of the given catalog's system or user function parameters and return type.

getFunctions(String catalog, String schemaPattern,


String functionNamePattern)
ResultSet
Retrieves a description of the system and user functions available in the given catalog.

CSE, KSIT, 2019-20 Page 274


Advanced Java & J2EE (17CS553) Study Material

getIdentifierQuoteString()
String
Retrieves the string used to quote SQL identifiers.

getImportedKeys(String catalog, String schema, String table)

ResultSet Retrieves a description of the primary key columns that are referenced by the given table's
foreign key columns (the primary keys imported by a table).

getIndexInfo(String catalog, String schema, String table, boolean unique,


boolean approximate)
ResultSet
Retrieves a description of the given table's indices and statistics.

getJDBCMajorVersion()
int
Retrieves the major JDBC version number for this driver.

getJDBCMinorVersion()
int
Retrieves the minor JDBC version number for this driver.

getMaxBinaryLiteralLength()
int
Retrieves the maximum number of hex characters this database allows in an inline binary literal.

getMaxCatalogNameLength()
int
Retrieves the maximum number of characters that this database allows in a catalog name.

getMaxCharLiteralLength()
int
Retrieves the maximum number of characters this database allows for a character literal.

getMaxColumnNameLength()
int
Retrieves the maximum number of characters this database allows for a column name.

getMaxColumnsInGroupBy()
int
Retrieves the maximum number of columns this database allows in a GROUP BY clause.

getMaxColumnsInIndex()
int
Retrieves the maximum number of columns this database allows in an index.

getMaxColumnsInOrderBy()
int
Retrieves the maximum number of columns this database allows in an ORDER BY clause.

CSE, KSIT, 2019-20 Page 275


Advanced Java & J2EE (17CS553) Study Material

getMaxColumnsInSelect()
int
Retrieves the maximum number of columns this database allows in a SELECT list.

getMaxColumnsInTable()
int
Retrieves the maximum number of columns this database allows in a table.

getMaxConnections()
int
Retrieves the maximum number of concurrent connections to this database that are possible.

getMaxCursorNameLength()
int
Retrieves the maximum number of characters that this database allows in a cursor name.

getMaxIndexLength()

int Retrieves the maximum number of bytes this database allows for an index, including all of the
parts of the index.

getMaxProcedureNameLength()
int
Retrieves the maximum number of characters that this database allows in a procedure name.

getMaxRowSize()
int
Retrieves the maximum number of bytes this database allows in a single row.

getMaxSchemaNameLength()
int
Retrieves the maximum number of characters that this database allows in a schema name.

getMaxStatementLength()
int
Retrieves the maximum number of characters this database allows in an SQL statement.

getMaxStatements()

int Retrieves the maximum number of active statements to this database that can be open at the
same time.

getMaxTableNameLength()
int
Retrieves the maximum number of characters this database allows in a table name.

getMaxTablesInSelect()
int
Retrieves the maximum number of tables this database allows in a SELECT statement.

CSE, KSIT, 2019-20 Page 276


Advanced Java & J2EE (17CS553) Study Material

getMaxUserNameLength()
int
Retrieves the maximum number of characters this database allows in a user name.

getNumericFunctions()
String
Retrieves a comma-separated list of math functions available with this database.

getPrimaryKeys(String catalog, String schema, String table)


ResultSet
Retrieves a description of the given table's primary key columns.

getProcedureColumns(String catalog, String schemaPattern,


String procedureNamePattern, String columnNamePattern)
ResultSet
Retrieves a description of the given catalog's stored procedure parameter and result columns.

getProcedures(String catalog, String schemaPattern,


String procedureNamePattern)
ResultSet
Retrieves a description of the stored procedures available in the given catalog.

getProcedureTerm()
String
Retrieves the database vendor's preferred term for "procedure".

getPseudoColumns(String catalog, String schemaPattern,


String tableNamePattern, String columnNamePattern)
ResultSet
Retrieves a description of the pseudo or hidden columns available in a given table within the
specified catalog and schema.

getResultSetHoldability()
int
Retrieves this database's default holdability for ResultSet objects.

getRowIdLifetime()

RowIdLifetime Indicates whether or not this data source supports the SQL ROWID type, and if so the lifetime for
which a RowId object remains valid.

getSchemas()
ResultSet
Retrieves the schema names available in this database.

getSchemas(String catalog, String schemaPattern)


ResultSet
Retrieves the schema names available in this database.

String getSchemaTerm()

CSE, KSIT, 2019-20 Page 277


Advanced Java & J2EE (17CS553) Study Material

Retrieves the database vendor's preferred term for "schema".

getSearchStringEscape()
String
Retrieves the string that can be used to escape wildcard characters.

getSQLKeywords()

String Retrieves a comma-separated list of all of this database's SQL keywords that are NOT also
SQL:2003 keywords.

getSQLStateType()

int Indicates whether the SQLSTATE returned by SQLException.getSQLState is X/Open (now


known as Open Group) SQL CLI or SQL:2003.

getStringFunctions()
String
Retrieves a comma-separated list of string functions available with this database.

getSuperTables(String catalog, String schemaPattern,


String tableNamePattern)
ResultSet
Retrieves a description of the table hierarchies defined in a particular schema in this database.

getSuperTypes(String catalog, String schemaPattern,


String typeNamePattern)
ResultSet
Retrieves a description of the user-defined type (UDT) hierarchies defined in a particular schema
in this database.

getSystemFunctions()
String
Retrieves a comma-separated list of system functions available with this database.

getTablePrivileges(String catalog, String schemaPattern,


String tableNamePattern)
ResultSet
Retrieves a description of the access rights for each table available in a catalog.

getTables(String catalog, String schemaPattern, String tableNamePattern,


String[] types)
ResultSet
Retrieves a description of the tables available in the given catalog.

getTableTypes()
ResultSet
Retrieves the table types available in this database.

String getTimeDateFunctions()

CSE, KSIT, 2019-20 Page 278


Advanced Java & J2EE (17CS553) Study Material

Retrieves a comma-separated list of the time and date functions available with this database.

getTypeInfo()
ResultSet
Retrieves a description of all the data types supported by this database.

getUDTs(String catalog, String schemaPattern, String typeNamePattern,


int[] types)
ResultSet
Retrieves a description of the user-defined types (UDTs) defined in a particular schema.

getURL()
String
Retrieves the URL for this DBMS.

getUserName()
String
Retrieves the user name as known to this database.

getVersionColumns(String catalog, String schema, String table)

ResultSet Retrieves a description of a table's columns that are automatically updated when any value in a
row is updated.

insertsAreDetected(int type)

boolean Retrieves whether or not a visible row insert can be detected by calling the method
ResultSet.rowInserted.

isCatalogAtStart()
boolean
Retrieves whether a catalog appears at the start of a fully qualified table name.

isReadOnly()
boolean
Retrieves whether this database is in read-only mode.

locatorsUpdateCopy()
boolean
Indicates whether updates made to a LOB are made on a copy or directly to the LOB.

nullPlusNonNullIsNull()

boolean Retrieves whether this database supports concatenations between NULL and non-NULL values
being NULL.

nullsAreSortedAtEnd()
boolean
Retrieves whether NULL values are sorted at the end regardless of sort order.

CSE, KSIT, 2019-20 Page 279


Advanced Java & J2EE (17CS553) Study Material

nullsAreSortedAtStart()
boolean
Retrieves whether NULL values are sorted at the start regardless of sort order.

nullsAreSortedHigh()
boolean
Retrieves whether NULL values are sorted high.

nullsAreSortedLow()
boolean
Retrieves whether NULL values are sorted low.

othersDeletesAreVisible(int type)
boolean
Retrieves whether deletes made by others are visible.

othersInsertsAreVisible(int type)
boolean
Retrieves whether inserts made by others are visible.

othersUpdatesAreVisible(int type)
boolean
Retrieves whether updates made by others are visible.

ownDeletesAreVisible(int type)
boolean
Retrieves whether a result set's own deletes are visible.

ownInsertsAreVisible(int type)
boolean
Retrieves whether a result set's own inserts are visible.

ownUpdatesAreVisible(int type)

boolean Retrieves whether for the given type of ResultSet object, the result set's own updates are
visible.

storesLowerCaseIdentifiers()

boolean Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive
and stores them in lower case.

storesLowerCaseQuotedIdentifiers()

boolean Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and
stores them in lower case.

storesMixedCaseIdentifiers()
boolean
Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive

CSE, KSIT, 2019-20 Page 280


Advanced Java & J2EE (17CS553) Study Material

and stores them in mixed case.

storesMixedCaseQuotedIdentifiers()

boolean Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and
stores them in mixed case.

storesUpperCaseIdentifiers()

boolean Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive
and stores them in upper case.

storesUpperCaseQuotedIdentifiers()

boolean Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and
stores them in upper case.

supportsAlterTableWithAddColumn()
boolean
Retrieves whether this database supports ALTER TABLE with add column.

supportsAlterTableWithDropColumn()
boolean
Retrieves whether this database supports ALTER TABLE with drop column.

supportsANSI92EntryLevelSQL()
boolean
Retrieves whether this database supports the ANSI92 entry level SQL grammar.

supportsANSI92FullSQL()
boolean
Retrieves whether this database supports the ANSI92 full SQL grammar supported.

supportsANSI92IntermediateSQL()
boolean
Retrieves whether this database supports the ANSI92 intermediate SQL grammar supported.

supportsBatchUpdates()
boolean
Retrieves whether this database supports batch updates.

supportsCatalogsInDataManipulation()
boolean
Retrieves whether a catalog name can be used in a data manipulation statement.

supportsCatalogsInIndexDefinitions()
boolean
Retrieves whether a catalog name can be used in an index definition statement.

CSE, KSIT, 2019-20 Page 281


Advanced Java & J2EE (17CS553) Study Material

supportsCatalogsInPrivilegeDefinitions()
boolean
Retrieves whether a catalog name can be used in a privilege definition statement.

supportsCatalogsInProcedureCalls()
boolean
Retrieves whether a catalog name can be used in a procedure call statement.

supportsCatalogsInTableDefinitions()
boolean
Retrieves whether a catalog name can be used in a table definition statement.

supportsColumnAliasing()
boolean
Retrieves whether this database supports column aliasing.

supportsConvert()

boolean Retrieves whether this database supports the JDBC scalar function CONVERT for the conversion of
one JDBC type to another.

supportsConvert(int fromType, int toType)

boolean Retrieves whether this database supports the JDBC scalar function CONVERT for conversions
between the JDBC types fromType and toType.

supportsCoreSQLGrammar()
boolean
Retrieves whether this database supports the ODBC Core SQL grammar.

supportsCorrelatedSubqueries()
boolean
Retrieves whether this database supports correlated subqueries.

supportsDataDefinitionAndDataManipulationTransactions()

boolean Retrieves whether this database supports both data definition and data manipulation statements
within a transaction.

supportsDataManipulationTransactionsOnly()

boolean Retrieves whether this database supports only data manipulation statements within a
transaction.

supportsDifferentTableCorrelationNames()

boolean Retrieves whether, when table correlation names are supported, they are restricted to being
different from the names of the tables.

CSE, KSIT, 2019-20 Page 282


Advanced Java & J2EE (17CS553) Study Material

supportsExpressionsInOrderBy()
boolean
Retrieves whether this database supports expressions in ORDER BY lists.

supportsExtendedSQLGrammar()
boolean
Retrieves whether this database supports the ODBC Extended SQL grammar.

supportsFullOuterJoins()
boolean
Retrieves whether this database supports full nested outer joins.

supportsGetGeneratedKeys()
boolean
Retrieves whether auto-generated keys can be retrieved after a statement has been executed

supportsGroupBy()
boolean
Retrieves whether this database supports some form of GROUP BY clause.

supportsGroupByBeyondSelect()

boolean Retrieves whether this database supports using columns not included in the SELECT statement in
a GROUP BY clause provided that all of the columns in the SELECT statement are included in the
GROUP BY clause.

supportsGroupByUnrelated()

boolean Retrieves whether this database supports using a column that is not in the SELECT statement in a
GROUP BY clause.

supportsIntegrityEnhancementFacility()
boolean
Retrieves whether this database supports the SQL Integrity Enhancement Facility.

supportsLikeEscapeClause()
boolean
Retrieves whether this database supports specifying a LIKE escape clause.

supportsLimitedOuterJoins()
boolean
Retrieves whether this database provides limited support for outer joins.

supportsMinimumSQLGrammar()
boolean
Retrieves whether this database supports the ODBC Minimum SQL grammar.

supportsMixedCaseIdentifiers()
boolean
Retrieves whether this database treats mixed case unquoted SQL identifiers as case sensitive and

CSE, KSIT, 2019-20 Page 283


Advanced Java & J2EE (17CS553) Study Material

as a result stores them in mixed case.

supportsMixedCaseQuotedIdentifiers()

boolean Retrieves whether this database treats mixed case quoted SQL identifiers as case sensitive and as
a result stores them in mixed case.

supportsMultipleOpenResults()

boolean Retrieves whether it is possible to have multiple ResultSet objects returned from a
CallableStatement object simultaneously.

supportsMultipleResultSets()

boolean Retrieves whether this database supports getting multiple ResultSet objects from a single call
to the method execute.

supportsMultipleTransactions()

boolean Retrieves whether this database allows having multiple transactions open at once (on different
connections).

supportsNamedParameters()
boolean
Retrieves whether this database supports named parameters to callable statements.

supportsNonNullableColumns()
boolean
Retrieves whether columns in this database may be defined as non-nullable.

supportsOpenCursorsAcrossCommit()
boolean
Retrieves whether this database supports keeping cursors open across commits.

supportsOpenCursorsAcrossRollback()
boolean
Retrieves whether this database supports keeping cursors open across rollbacks.

supportsOpenStatementsAcrossCommit()
boolean
Retrieves whether this database supports keeping statements open across commits.

supportsOpenStatementsAcrossRollback()
boolean
Retrieves whether this database supports keeping statements open across rollbacks.

supportsOrderByUnrelated()
boolean
Retrieves whether this database supports using a column that is not in the SELECT statement in

CSE, KSIT, 2019-20 Page 284


Advanced Java & J2EE (17CS553) Study Material

an ORDER BY clause.

supportsOuterJoins()
boolean
Retrieves whether this database supports some form of outer join.

supportsPositionedDelete()
boolean
Retrieves whether this database supports positioned DELETE statements.

supportsPositionedUpdate()
boolean
Retrieves whether this database supports positioned UPDATE statements.

supportsResultSetConcurrency(int type, int concurrency)

boolean Retrieves whether this database supports the given concurrency type in combination with the
given result set type.

supportsResultSetHoldability(int holdability)
boolean
Retrieves whether this database supports the given result set holdability.

supportsResultSetType(int type)
boolean
Retrieves whether this database supports the given result set type.

supportsSavepoints()
boolean
Retrieves whether this database supports savepoints.

supportsSchemasInDataManipulation()
boolean
Retrieves whether a schema name can be used in a data manipulation statement.

supportsSchemasInIndexDefinitions()
boolean
Retrieves whether a schema name can be used in an index definition statement.

supportsSchemasInPrivilegeDefinitions()
boolean
Retrieves whether a schema name can be used in a privilege definition statement.

supportsSchemasInProcedureCalls()
boolean
Retrieves whether a schema name can be used in a procedure call statement.

supportsSchemasInTableDefinitions()
boolean
Retrieves whether a schema name can be used in a table definition statement.

CSE, KSIT, 2019-20 Page 285


Advanced Java & J2EE (17CS553) Study Material

supportsSelectForUpdate()
boolean
Retrieves whether this database supports SELECT FOR UPDATE statements.

supportsStatementPooling()
boolean
Retrieves whether this database supports statement pooling.

supportsStoredFunctionsUsingCallSyntax()

boolean Retrieves whether this database supports invoking user-defined or vendor functions using the
stored procedure escape syntax.

supportsStoredProcedures()

boolean Retrieves whether this database supports stored procedure calls that use the stored procedure
escape syntax.

supportsSubqueriesInComparisons()
boolean
Retrieves whether this database supports subqueries in comparison expressions.

supportsSubqueriesInExists()
boolean
Retrieves whether this database supports subqueries in EXISTS expressions.

supportsSubqueriesInIns()
boolean
Retrieves whether this database supports subqueries in IN expressions.

supportsSubqueriesInQuantifieds()
boolean
Retrieves whether this database supports subqueries in quantified expressions.

supportsTableCorrelationNames()
boolean
Retrieves whether this database supports table correlation names.

supportsTransactionIsolationLevel(int level)
boolean
Retrieves whether this database supports the given transaction isolation level.

supportsTransactions()
boolean
Retrieves whether this database supports transactions.

supportsUnion()
boolean
Retrieves whether this database supports SQL UNION.

CSE, KSIT, 2019-20 Page 286


Advanced Java & J2EE (17CS553) Study Material

supportsUnionAll()
boolean
Retrieves whether this database supports SQL UNION ALL.

updatesAreDetected(int type)

boolean Retrieves whether or not a visible row update can be detected by calling the method
ResultSet.rowUpdated.

usesLocalFilePerTable()
boolean
Retrieves whether this database uses a file for each table.

usesLocalFiles()
boolean
Retrieves whether this database stores tables in a local file.

java.sql

• Interface CallableStatement

public interface CallableStatement


extends PreparedStatement

The interface used to execute SQL stored procedures. The JDBC API provides a stored procedure SQL
escape syntax that allows stored procedures to be called in a standard way for all RDBMSs. This escape
syntax has one form that includes a result parameter and one that does not. If used, the result parameter
must be registered as an OUT parameter. The other parameters can be used for input, output or both.
Parameters are referred to sequentially, by number, with the first parameter being 1.

{?= call <procedure-name>[(<arg1>,<arg2>, ...)]}


{call <procedure-name>[(<arg1>,<arg2>, ...)]}

IN parameter values are set using the set methods inherited from PreparedStatement. The type of
all OUT parameters must be registered prior to executing the stored procedure; their values are retrieved
after execution via the get methods provided here.

A CallableStatement can return one ResultSet object or multiple ResultSet objects.


Multiple ResultSet objects are handled using operations inherited from Statement.

For maximum portability, a call's ResultSet objects and update counts should be processed prior to
getting the values of output parameters.

CSE, KSIT, 2019-20 Page 287


Advanced Java & J2EE (17CS553) Study Material

Method Summary
Methods

Modifier and
Method and Description
Type

getArray(int parameterIndex)
Array Retrieves the value of the designated JDBC ARRAY parameter as an Array object in the
Java programming language.

getArray(String parameterName)
Array Retrieves the value of a JDBC ARRAY parameter as an Array object in the Java
programming language.

getBigDecimal(int parameterIndex)

BigDecimal Retrieves the value of the designated JDBC NUMERIC parameter as a


java.math.BigDecimal object with as many digits to the right of the decimal point as
the value contains.

getBigDecimal(int parameterIndex, int scale)

Deprecated.
BigDecimal
use getBigDecimal(int parameterIndex) or getBigDecimal(String
parameterName)

getBigDecimal(String parameterName)
BigDecimal Retrieves the value of a JDBC NUMERIC parameter as a java.math.BigDecimal
object with as many digits to the right of the decimal point as the value contains.

getBlob(int parameterIndex)
Blob Retrieves the value of the designated JDBC BLOB parameter as a Blob object in the Java
programming language.

getBlob(String parameterName)
Blob Retrieves the value of a JDBC BLOB parameter as a Blob object in the Java programming
language.

boolean getBoolean(int parameterIndex)

CSE, KSIT, 2019-20 Page 288


Advanced Java & J2EE (17CS553) Study Material

Retrieves the value of the designated JDBC BIT or BOOLEAN parameter as a boolean in
the Java programming language.

getBoolean(String parameterName)
boolean
Retrieves the value of a JDBC BIT or BOOLEAN parameter as a boolean in the Java
programming language.

getByte(int parameterIndex)
byte
Retrieves the value of the designated JDBC TINYINT parameter as a byte in the Java
programming language.

getByte(String parameterName)
byte
Retrieves the value of a JDBC TINYINT parameter as a byte in the Java programming
language.

getBytes(int parameterIndex)
byte[] Retrieves the value of the designated JDBC BINARY or VARBINARY parameter as an array
of byte values in the Java programming language.

getBytes(String parameterName)
byte[]
Retrieves the value of a JDBC BINARY or VARBINARY parameter as an array of byte
values in the Java programming language.

getCharacterStream(int parameterIndex)
Reader Retrieves the value of the designated parameter as a java.io.Reader object in the Java
programming language.

getCharacterStream(String parameterName)
Reader Retrieves the value of the designated parameter as a java.io.Reader object in the Java
programming language.

getClob(int parameterIndex)
Clob Retrieves the value of the designated JDBC CLOB parameter as a java.sql.Clob object
in the Java programming language.

Clob getClob(String parameterName)

CSE, KSIT, 2019-20 Page 289


Advanced Java & J2EE (17CS553) Study Material

Retrieves the value of a JDBC CLOB parameter as a java.sql.Clob object in the Java
programming language.

getDate(int parameterIndex)
Date
Retrieves the value of the designated JDBC DATE parameter as a java.sql.Date object.

getDate(int parameterIndex, Calendar cal)


Date Retrieves the value of the designated JDBC DATE parameter as a java.sql.Date object,
using the given Calendar object to construct the date.

getDate(String parameterName)
Date
Retrieves the value of a JDBC DATE parameter as a java.sql.Date object.

getDate(String parameterName, Calendar cal)


Date Retrieves the value of a JDBC DATE parameter as a java.sql.Date object, using the
given Calendar object to construct the date.

getDouble(int parameterIndex)
double
Retrieves the value of the designated JDBC DOUBLE parameter as a double in the Java
programming language.

getDouble(String parameterName)
double
Retrieves the value of a JDBC DOUBLE parameter as a double in the Java programming
language.

getFloat(int parameterIndex)
float
Retrieves the value of the designated JDBC FLOAT parameter as a float in the Java
programming language.

getFloat(String parameterName)
float
Retrieves the value of a JDBC FLOAT parameter as a float in the Java programming
language.

getInt(int parameterIndex)
int
Retrieves the value of the designated JDBC INTEGER parameter as an int in the Java
programming language.

CSE, KSIT, 2019-20 Page 290


Advanced Java & J2EE (17CS553) Study Material

getInt(String parameterName)
int
Retrieves the value of a JDBC INTEGER parameter as an int in the Java programming
language.

getLong(int parameterIndex)
long
Retrieves the value of the designated JDBC BIGINT parameter as a long in the Java
programming language.

getLong(String parameterName)
long
Retrieves the value of a JDBC BIGINT parameter as a long in the Java programming
language.

getNCharacterStream(int parameterIndex)
Reader Retrieves the value of the designated parameter as a java.io.Reader object in the Java
programming language.

getNCharacterStream(String parameterName)
Reader Retrieves the value of the designated parameter as a java.io.Reader object in the Java
programming language.

getNClob(int parameterIndex)
NClob Retrieves the value of the designated JDBC NCLOB parameter as a java.sql.NClob
object in the Java programming language.

getNClob(String parameterName)
NClob Retrieves the value of a JDBC NCLOB parameter as a java.sql.NClob object in the Java
programming language.

getNString(int parameterIndex)
String Retrieves the value of the designated NCHAR, NVARCHAR or LONGNVARCHAR parameter as
a String in the Java programming language.

getNString(String parameterName)
String Retrieves the value of the designated NCHAR, NVARCHAR or LONGNVARCHAR parameter as
a String in the Java programming language.

CSE, KSIT, 2019-20 Page 291


Advanced Java & J2EE (17CS553) Study Material

getObject(int parameterIndex)
Object Retrieves the value of the designated parameter as an Object in the Java programming
language.

getObject(int parameterIndex, Class<T> type)

<T> T Returns an object representing the value of OUT parameter parameterIndex and will
convert from the SQL type of the parameter to the requested Java data type, if the conversion
is supported.

getObject(int parameterIndex, Map<String,Class<?>> map)


Object Returns an object representing the value of OUT parameter parameterIndex and uses
map for the custom mapping of the parameter value.

getObject(String parameterName)
Object
Retrieves the value of a parameter as an Object in the Java programming language.

getObject(String parameterName, Class<T> type)

<T> T Returns an object representing the value of OUT parameter parameterName and will
convert from the SQL type of the parameter to the requested Java data type, if the conversion
is supported.

getObject(String parameterName, Map<String,Class<?>> map)


Object Returns an object representing the value of OUT parameter parameterName and uses
map for the custom mapping of the parameter value.

getRef(int parameterIndex)
Ref Retrieves the value of the designated JDBC REF(<structured-type>) parameter as a
Ref object in the Java programming language.

getRef(String parameterName)
Ref Retrieves the value of a JDBC REF(<structured-type>) parameter as a Ref object in
the Java programming language.

getRowId(int parameterIndex)
RowId Retrieves the value of the designated JDBC ROWID parameter as a java.sql.RowId
object.

CSE, KSIT, 2019-20 Page 292


Advanced Java & J2EE (17CS553) Study Material

getRowId(String parameterName)
RowId Retrieves the value of the designated JDBC ROWID parameter as a java.sql.RowId
object.

getShort(int parameterIndex)
short
Retrieves the value of the designated JDBC SMALLINT parameter as a short in the Java
programming language.

getShort(String parameterName)
short
Retrieves the value of a JDBC SMALLINT parameter as a short in the Java programming
language.

getSQLXML(int parameterIndex)
SQLXML Retrieves the value of the designated SQL XML parameter as a java.sql.SQLXML object
in the Java programming language.

getSQLXML(String parameterName)
SQLXML Retrieves the value of the designated SQL XML parameter as a java.sql.SQLXML object
in the Java programming language.

getString(int parameterIndex)
String Retrieves the value of the designated JDBC CHAR, VARCHAR, or LONGVARCHAR parameter
as a String in the Java programming language.

getString(String parameterName)
String Retrieves the value of a JDBC CHAR, VARCHAR, or LONGVARCHAR parameter as a
String in the Java programming language.

getTime(int parameterIndex)
Time
Retrieves the value of the designated JDBC TIME parameter as a java.sql.Time object.

getTime(int parameterIndex, Calendar cal)


Time Retrieves the value of the designated JDBC TIME parameter as a java.sql.Time object,
using the given Calendar object to construct the time.

Time getTime(String parameterName)

CSE, KSIT, 2019-20 Page 293


Advanced Java & J2EE (17CS553) Study Material

Retrieves the value of a JDBC TIME parameter as a java.sql.Time object.

getTime(String parameterName, Calendar cal)


Time Retrieves the value of a JDBC TIME parameter as a java.sql.Time object, using the
given Calendar object to construct the time.

getTimestamp(int parameterIndex)
Timestamp Retrieves the value of the designated JDBC TIMESTAMP parameter as a
java.sql.Timestamp object.

getTimestamp(int parameterIndex, Calendar cal)

Timestamp Retrieves the value of the designated JDBC TIMESTAMP parameter as a


java.sql.Timestamp object, using the given Calendar object to construct the
Timestamp object.

getTimestamp(String parameterName)
Timestamp Retrieves the value of a JDBC TIMESTAMP parameter as a java.sql.Timestamp
object.

getTimestamp(String parameterName, Calendar cal)


Timestamp Retrieves the value of a JDBC TIMESTAMP parameter as a java.sql.Timestamp
object, using the given Calendar object to construct the Timestamp object.

getURL(int parameterIndex)
URL Retrieves the value of the designated JDBC DATALINK parameter as a java.net.URL
object.

getURL(String parameterName)
URL
Retrieves the value of a JDBC DATALINK parameter as a java.net.URL object.

registerOutParameter(int parameterIndex, int sqlType)


void Registers the OUT parameter in ordinal position parameterIndex to the JDBC type
sqlType.

registerOutParameter(int parameterIndex, int sqlType, int scale)


void
Registers the parameter in ordinal position parameterIndex to be of JDBC type

CSE, KSIT, 2019-20 Page 294


Advanced Java & J2EE (17CS553) Study Material

sqlType.

registerOutParameter(int parameterIndex, int sqlType,


void String typeName)

Registers the designated output parameter.

registerOutParameter(String parameterName, int sqlType)


void
Registers the OUT parameter named parameterName to the JDBC type sqlType.

registerOutParameter(String parameterName, int sqlType, int scale)


void
Registers the parameter named parameterName to be of JDBC type sqlType.

registerOutParameter(String parameterName, int sqlType,


void String typeName)

Registers the designated output parameter.

setAsciiStream(String parameterName, InputStream x)


void
Sets the designated parameter to the given input stream.

setAsciiStream(String parameterName, InputStream x, int length)


void Sets the designated parameter to the given input stream, which will have the specified
number of bytes.

setAsciiStream(String parameterName, InputStream x, long length)


void Sets the designated parameter to the given input stream, which will have the specified
number of bytes.

setBigDecimal(String parameterName, BigDecimal x)


void
Sets the designated parameter to the given java.math.BigDecimal value.

setBinaryStream(String parameterName, InputStream x)


void
Sets the designated parameter to the given input stream.

setBinaryStream(String parameterName, InputStream x, int length)


void Sets the designated parameter to the given input stream, which will have the specified
number of bytes.

CSE, KSIT, 2019-20 Page 295


Advanced Java & J2EE (17CS553) Study Material

setBinaryStream(String parameterName, InputStream x, long length)


void Sets the designated parameter to the given input stream, which will have the specified
number of bytes.

setBlob(String parameterName, Blob x)


void
Sets the designated parameter to the given java.sql.Blob object.

setBlob(String parameterName, InputStream inputStream)


void
Sets the designated parameter to a InputStream object.

setBlob(String parameterName, InputStream inputStream, long length)


void
Sets the designated parameter to a InputStream object.

setBoolean(String parameterName, boolean x)


void
Sets the designated parameter to the given Java boolean value.

setByte(String parameterName, byte x)


void
Sets the designated parameter to the given Java byte value.

setBytes(String parameterName, byte[] x)


void
Sets the designated parameter to the given Java array of bytes.

setCharacterStream(String parameterName, Reader reader)


void
Sets the designated parameter to the given Reader object.

setCharacterStream(String parameterName, Reader reader, int length)


void
Sets the designated parameter to the given Reader object, which is the given number of
characters long.

setCharacterStream(String parameterName, Reader reader, long length)


void
Sets the designated parameter to the given Reader object, which is the given number of
characters long.

setClob(String parameterName, Clob x)


void
Sets the designated parameter to the given java.sql.Clob object.

CSE, KSIT, 2019-20 Page 296


Advanced Java & J2EE (17CS553) Study Material

setClob(String parameterName, Reader reader)


void
Sets the designated parameter to a Reader object.

setClob(String parameterName, Reader reader, long length)


void
Sets the designated parameter to a Reader object.

setDate(String parameterName, Date x)


void
Sets the designated parameter to the given java.sql.Date value using the default time
zone of the virtual machine that is running the application.

setDate(String parameterName, Date x, Calendar cal)


void Sets the designated parameter to the given java.sql.Date value, using the given
Calendar object.

setDouble(String parameterName, double x)


void
Sets the designated parameter to the given Java double value.

setFloat(String parameterName, float x)


void
Sets the designated parameter to the given Java float value.

setInt(String parameterName, int x)


void
Sets the designated parameter to the given Java int value.

setLong(String parameterName, long x)


void
Sets the designated parameter to the given Java long value.

setNCharacterStream(String parameterName, Reader value)


void
Sets the designated parameter to a Reader object.

setNCharacterStream(String parameterName, Reader value, long length)


void
Sets the designated parameter to a Reader object.

setNClob(String parameterName, NClob value)


void
Sets the designated parameter to a java.sql.NClob object.

CSE, KSIT, 2019-20 Page 297


Advanced Java & J2EE (17CS553) Study Material

setNClob(String parameterName, Reader reader)


void
Sets the designated parameter to a Reader object.

setNClob(String parameterName, Reader reader, long length)


void
Sets the designated parameter to a Reader object.

setNString(String parameterName, String value)


void
Sets the designated parameter to the given String object.

setNull(String parameterName, int sqlType)


void
Sets the designated parameter to SQL NULL.

setNull(String parameterName, int sqlType, String typeName)


void
Sets the designated parameter to SQL NULL.

setObject(String parameterName, Object x)


void
Sets the value of the designated parameter with the given object.

setObject(String parameterName, Object x, int targetSqlType)


void
Sets the value of the designated parameter with the given object.

setObject(String parameterName, Object x, int targetSqlType,


void int scale)

Sets the value of the designated parameter with the given object.

setRowId(String parameterName, RowId x)


void
Sets the designated parameter to the given java.sql.RowId object.

setShort(String parameterName, short x)


void
Sets the designated parameter to the given Java short value.

setSQLXML(String parameterName, SQLXML xmlObject)


void
Sets the designated parameter to the given java.sql.SQLXML object.

void setString(String parameterName, String x)

CSE, KSIT, 2019-20 Page 298


Advanced Java & J2EE (17CS553) Study Material

Sets the designated parameter to the given Java String value.

setTime(String parameterName, Time x)


void
Sets the designated parameter to the given java.sql.Time value.

setTime(String parameterName, Time x, Calendar cal)


void Sets the designated parameter to the given java.sql.Time value, using the given
Calendar object.

setTimestamp(String parameterName, Timestamp x)


void
Sets the designated parameter to the given java.sql.Timestamp value.

setTimestamp(String parameterName, Timestamp x, Calendar cal)


void Sets the designated parameter to the given java.sql.Timestamp value, using the given
Calendar object.

setURL(String parameterName, URL val)


void
Sets the designated parameter to the given java.net.URL object.

wasNull()
boolean
Retrieves whether the last OUT parameter read had the v

java.sql

Interface Connection

A connection (session) with a specific database. SQL statements are executed and results are returned within
the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported SQL
grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained
with the getMetaData method.

Note: When configuring a Connection, JDBC applications should use the appropriate Connection
method such as setAutoCommit or setTransactionIsolation. Applications should not invoke
SQL commands directly to change the connection's configuration when there is a JDBC method available.
By default a Connection object is in auto-commit mode, which means that it automatically commits

CSE, KSIT, 2019-20 Page 299


Advanced Java & J2EE (17CS553) Study Material

changes after executing each statement. If auto-commit mode has been disabled, the method commit must
be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map
associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved
from a data source with the method ResultSet.getObject, the getObject method will check the
connection's type map to see if there is an entry for that UDT. If so, the getObject method will map the
UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to
the java.sql methods that can perform custom mapping. In this case, the method will use the given type
map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the
class Athletes in the Java programming language. The code fragment retrieves the type map for the
Connection object con, inserts the entry into it, and then sets the type map with the new entry as the
connection's type map.

java.util.Map map = con.getTypeMap();


map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));
con.setTypeMap(map);

Method Summary
Methods

Modifier and Type Method and Description

abort(Executor executor)
void
Terminates an open connection.

clearWarnings()
void
Clears all warnings reported for this Connection object.

close()
void Releases this Connection object's database and JDBC resources immediately
instead of waiting for them to be automatically released.

commit()
void Makes all changes made since the previous commit/rollback permanent and
releases any database locks currently held by this Connection object.

CSE, KSIT, 2019-20 Page 300


Advanced Java & J2EE (17CS553) Study Material

createArrayOf(String typeName, Object[] elements)


Array
Factory method for creating Array objects.

createBlob()
Blob
Constructs an object that implements the Blob interface.

createClob()
Clob
Constructs an object that implements the Clob interface.

createNClob()
NClob
Constructs an object that implements the NClob interface.

createSQLXML()
SQLXML
Constructs an object that implements the SQLXML interface.

createStatement()
Statement
Creates a Statement object for sending SQL statements to the database.

createStatement(int resultSetType,
int resultSetConcurrency)
Statement
Creates a Statement object that will generate ResultSet objects with the
given type and concurrency.

createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
Statement
Creates a Statement object that will generate ResultSet objects with the
given type, concurrency, and holdability.

createStruct(String typeName, Object[] attributes)


Struct
Factory method for creating Struct objects.

getAutoCommit()
boolean
Retrieves the current auto-commit mode for this Connection object.

String getCatalog()

CSE, KSIT, 2019-20 Page 301


Advanced Java & J2EE (17CS553) Study Material

Retrieves this Connection object's current catalog name.

getClientInfo()
Properties Returns a list containing the name and current value of each client info property
supported by the driver.

getClientInfo(String name)
String
Returns the value of the client info property specified by name.

getHoldability()
int Retrieves the current holdability of ResultSet objects created using this
Connection object.

getMetaData()
DatabaseMetaData Retrieves a DatabaseMetaData object that contains metadata about the
database to which this Connection object represents a connection.

getNetworkTimeout()
int Retrieves the number of milliseconds the driver will wait for a database request to
complete.

getSchema()
String
Retrieves this Connection object's current schema name.

getTransactionIsolation()
int
Retrieves this Connection object's current transaction isolation level.

getTypeMap()
Map<String,Class<?>>
Retrieves the Map object associated with this Connection object.

getWarnings()
SQLWarning
Retrieves the first warning reported by calls on this Connection object.

isClosed()
boolean
Retrieves whether this Connection object has been closed.

CSE, KSIT, 2019-20 Page 302


Advanced Java & J2EE (17CS553) Study Material

isReadOnly()
boolean
Retrieves whether this Connection object is in read-only mode.

isValid(int timeout)
boolean
Returns true if the connection has not been closed and is still valid.

nativeSQL(String sql)
String
Converts the given SQL statement into the system's native SQL grammar.

prepareCall(String sql)
CallableStatement
Creates a CallableStatement object for calling database stored procedures.

prepareCall(String sql, int resultSetType,


int resultSetConcurrency)
CallableStatement
Creates a CallableStatement object that will generate ResultSet objects
with the given type and concurrency.

prepareCall(String sql, int resultSetType,


int resultSetConcurrency, int resultSetHoldability)
CallableStatement
Creates a CallableStatement object that will generate ResultSet objects
with the given type and concurrency.

prepareStatement(String sql)
PreparedStatement Creates a PreparedStatement object for sending parameterized SQL
statements to the database.

prepareStatement(String sql, int autoGeneratedKeys)


PreparedStatement Creates a default PreparedStatement object that has the capability to
retrieve auto-generated keys.

prepareStatement(String sql, int[] columnIndexes)


PreparedStatement Creates a default PreparedStatement object capable of returning the auto-
generated keys designated by the given array.

prepareStatement(String sql, int resultSetType,


PreparedStatement
int resultSetConcurrency)

CSE, KSIT, 2019-20 Page 303


Advanced Java & J2EE (17CS553) Study Material

Creates a PreparedStatement object that will generate ResultSet objects


with the given type and concurrency.

prepareStatement(String sql, int resultSetType,


int resultSetConcurrency, int resultSetHoldability)
PreparedStatement
Creates a PreparedStatement object that will generate ResultSet objects
with the given type, concurrency, and holdability.

prepareStatement(String sql, String[] columnNames)


PreparedStatement Creates a default PreparedStatement object capable of returning the auto-
generated keys designated by the given array.

releaseSavepoint(Savepoint savepoint)
void Removes the specified Savepoint and subsequent Savepoint objects from
the current transaction.

rollback()
void Undoes all changes made in the current transaction and releases any database
locks currently held by this Connection object.

rollback(Savepoint savepoint)
void
Undoes all changes made after the given Savepoint object was set.

setAutoCommit(boolean autoCommit)
void
Sets this connection's auto-commit mode to the given state.

setCatalog(String catalog)
void
Sets the given catalog name in order to select a subspace of this Connection
object's database in which to work.

setClientInfo(Properties properties)
void
Sets the value of the connection's client info properties.

setClientInfo(String name, String value)


void Sets the value of the client info property specified by name to the value specified
by value.

CSE, KSIT, 2019-20 Page 304


Advanced Java & J2EE (17CS553) Study Material

setHoldability(int holdability)
void Changes the default holdability of ResultSet objects created using this
Connection object to the given holdability.

setNetworkTimeout(Executor executor, int milliseconds)


void Sets the maximum period a Connection or objects created from the
Connection will wait for the database to reply to any one request.

setReadOnly(boolean readOnly)
void Puts this connection in read-only mode as a hint to the driver to enable database
optimizations.

setSavepoint()
Savepoint Creates an unnamed savepoint in the current transaction and returns the new
Savepoint object that represents it.

setSavepoint(String name)
Savepoint Creates a savepoint with the given name in the current transaction and returns the
new Savepoint object that represents it.

setSchema(String schema)
void
Sets the given schema name to access.

setTransactionIsolation(int level)
void
Attempts to change the transaction isolation level for this Connection object to
the one given.

setTypeMap(Map<String,Class<?>> map)
void
Installs the given TypeMap object as the type map for this Connection object.

java.sql

Interface ResultSet
ublic interface ResultSet
extends Wrapper, AutoCloseable
A table of data representing a database result set, which is usually generated by executing a statement that
queries the database.

CSE, KSIT, 2019-20 Page 305


Advanced Java & J2EE (17CS553) Study Material

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned
before the first row. The next method moves the cursor to the next row, and because it returns false
when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through
the result set.

A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can
iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet
objects that are scrollable and/or updatable. The following code fragment, in which con is a valid
Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by
others, and that is updatable. See ResultSet fields for other options.

Statement stmt = con.createStatement(


ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
// rs will be scrollable, will not show changes made by others,
// and will be updatable

The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving
column values from the current row. Values can be retrieved using either the index number of the column or
the name of the column. In general, using the column index will be more efficient. Columns are numbered
from 1. For maximum portability, result set columns within each row should be read in left-to-right order,
and each column should be read only once.

For the getter methods, a JDBC driver attempts to convert the underlying data to the Java type specified in
the getter method and returns a suitable Java value. The JDBC specification has a table showing the
allowable mappings from SQL types to Java types that can be used by the ResultSet getter methods.

Column names used as input to getter methods are case insensitive. When a getter method is called with a
column name and several columns have the same name, the value of the first matching column will be
returned. The column name option is designed to be used when column names are used in the SQL query
that generated the result set. For columns that are NOT explicitly named in the query, it is best to use
column numbers. If column names are used, the programmer should take care to guarantee that they
uniquely refer to the intended columns, which can be assured with the SQL AS clause.

A set of updater methods were added to this interface in the JDBC 2.0 API (Java TM 2 SDK, Standard
Edition, version 1.2). The comments regarding parameters to the getter methods also apply to parameters to
the updater methods.

The updater methods may be used in two ways:

1. to update a column value in the current row. In a scrollable ResultSet object, the cursor can be
moved backwards and forwards, to an absolute position, or to a position relative to the current row.
The following code fragment updates the NAME column in the fifth row of the ResultSet object
rs and then uses the method updateRow to update the data source table from which rs was
derived.

CSE, KSIT, 2019-20 Page 306


Advanced Java & J2EE (17CS553) Study Material

2.
3. rs.absolute(5); // moves the cursor to the fifth row of rs
4. rs.updateString("NAME", "AINSWORTH"); // updates the
5. // NAME column of row 5 to be AINSWORTH
6. rs.updateRow(); // updates the row in the data source
7.

8. to insert column values into the insert row. An updatable ResultSet object has a special row
associated with it that serves as a staging area for building a row to be inserted. The following code
fragment moves the cursor to the insert row, builds a three-column row, and inserts it into rs and
into the data source table using the method insertRow.
9.
10. rs.moveToInsertRow(); // moves cursor to the insert row
11. rs.updateString(1, "AINSWORTH"); // updates the
12. // first column of the insert row to be AINSWORTH
13. rs.updateInt(2,35); // updates the second column to be 35
14. rs.updateBoolean(3, true); // updates the third column to true
15. rs.insertRow();
16. rs.moveToCurrentRow();
17.

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-
executed, or used to retrieve the next result from a sequence of multiple results.

The number, types and properties of a ResultSet object's columns are provided by the
ResultSetMetaData object returned by the ResultSet.getMetaData method.

Method Summary
Methods

Modifier and
Method and Description
Type

absolute(int row)
boolean
Moves the cursor to the given row number in this ResultSet object.

afterLast()
void
Moves the cursor to the end of this ResultSet object, just after the last row.

beforeFirst()
void
Moves the cursor to the front of this ResultSet object, just before the first row.

CSE, KSIT, 2019-20 Page 307


Advanced Java & J2EE (17CS553) Study Material

cancelRowUpdates()
void
Cancels the updates made to the current row in this ResultSet object.

clearWarnings()
void
Clears all warnings reported on this ResultSet object.

close()
void
Releases this ResultSet object's database and JDBC resources immediately instead
of waiting for this to happen when it is automatically closed.

deleteRow()
void
Deletes the current row from this ResultSet object and from the underlying
database.

findColumn(String columnLabel)
int
Maps the given ResultSet column label to its ResultSet column index.

first()
boolean
Moves the cursor to the first row in this ResultSet object.

getArray(int columnIndex)
Array Retrieves the value of the designated column in the current row of this ResultSet
object as an Array object in the Java programming language.

getArray(String columnLabel)
Array Retrieves the value of the designated column in the current row of this ResultSet
object as an Array object in the Java programming language.

getAsciiStream(int columnIndex)
InputStream Retrieves the value of the designated column in the current row of this ResultSet
object as a stream of ASCII characters.

getAsciiStream(String columnLabel)
InputStream Retrieves the value of the designated column in the current row of this ResultSet
object as a stream of ASCII characters.

CSE, KSIT, 2019-20 Page 308


Advanced Java & J2EE (17CS553) Study Material

getBigDecimal(int columnIndex)
BigDecimal Retrieves the value of the designated column in the current row of this ResultSet
object as a java.math.BigDecimal with full precision.

getBigDecimal(int columnIndex, int scale)


BigDecimal
Deprecated.

getBigDecimal(String columnLabel)
BigDecimal Retrieves the value of the designated column in the current row of this ResultSet
object as a java.math.BigDecimal with full precision.

getBigDecimal(String columnLabel, int scale)


BigDecimal
Deprecated.

getBinaryStream(int columnIndex)
InputStream Retrieves the value of the designated column in the current row of this ResultSet
object as a stream of uninterpreted bytes.

getBinaryStream(String columnLabel)
InputStream Retrieves the value of the designated column in the current row of this ResultSet
object as a stream of uninterpreted bytes.

getBlob(int columnIndex)
Blob Retrieves the value of the designated column in the current row of this ResultSet
object as a Blob object in the Java programming language.

getBlob(String columnLabel)
Blob Retrieves the value of the designated column in the current row of this ResultSet
object as a Blob object in the Java programming language.

getBoolean(int columnIndex)
boolean Retrieves the value of the designated column in the current row of this ResultSet
object as a boolean in the Java programming language.

getBoolean(String columnLabel)
boolean
Retrieves the value of the designated column in the current row of this ResultSet

CSE, KSIT, 2019-20 Page 309


Advanced Java & J2EE (17CS553) Study Material

object as a boolean in the Java programming language.

getByte(int columnIndex)
byte Retrieves the value of the designated column in the current row of this ResultSet
object as a byte in the Java programming language.

getByte(String columnLabel)
byte Retrieves the value of the designated column in the current row of this ResultSet
object as a byte in the Java programming language.

getBytes(int columnIndex)
byte[] Retrieves the value of the designated column in the current row of this ResultSet
object as a byte array in the Java programming language.

getBytes(String columnLabel)
byte[] Retrieves the value of the designated column in the current row of this ResultSet
object as a byte array in the Java programming language.

getCharacterStream(int columnIndex)
Reader Retrieves the value of the designated column in the current row of this ResultSet
object as a java.io.Reader object.

getCharacterStream(String columnLabel)
Reader Retrieves the value of the designated column in the current row of this ResultSet
object as a java.io.Reader object.

getClob(int columnIndex)
Clob Retrieves the value of the designated column in the current row of this ResultSet
object as a Clob object in the Java programming language.

getClob(String columnLabel)
Clob Retrieves the value of the designated column in the current row of this ResultSet
object as a Clob object in the Java programming language.

int getConcurrency()

CSE, KSIT, 2019-20 Page 310


Advanced Java & J2EE (17CS553) Study Material

Retrieves the concurrency mode of this ResultSet object.

getCursorName()
String
Retrieves the name of the SQL cursor used by this ResultSet object.

getDate(int columnIndex)
Date Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Date object in the Java programming language.

getDate(int columnIndex, Calendar cal)


Date Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Date object in the Java programming language.

getDate(String columnLabel)
Date Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Date object in the Java programming language.

getDate(String columnLabel, Calendar cal)


Date Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Date object in the Java programming language.

getDouble(int columnIndex)
double Retrieves the value of the designated column in the current row of this ResultSet
object as a double in the Java programming language.

getDouble(String columnLabel)
double Retrieves the value of the designated column in the current row of this ResultSet
object as a double in the Java programming language.

getFetchDirection()
int
Retrieves the fetch direction for this ResultSet object.

getFetchSize()
int
Retrieves the fetch size for this ResultSet object.

float getFloat(int columnIndex)

CSE, KSIT, 2019-20 Page 311


Advanced Java & J2EE (17CS553) Study Material

Retrieves the value of the designated column in the current row of this ResultSet
object as a float in the Java programming language.

getFloat(String columnLabel)
float Retrieves the value of the designated column in the current row of this ResultSet
object as a float in the Java programming language.

getHoldability()
int
Retrieves the holdability of this ResultSet object

getInt(int columnIndex)
int Retrieves the value of the designated column in the current row of this ResultSet
object as an int in the Java programming language.

getInt(String columnLabel)
int Retrieves the value of the designated column in the current row of this ResultSet
object as an int in the Java programming language.

getLong(int columnIndex)
long Retrieves the value of the designated column in the current row of this ResultSet
object as a long in the Java programming language.

getLong(String columnLabel)
long Retrieves the value of the designated column in the current row of this ResultSet
object as a long in the Java programming language.

getMetaData()
ResultSetMetaData
Retrieves the number, types and properties of this ResultSet object's columns.

getNCharacterStream(int columnIndex)
Reader Retrieves the value of the designated column in the current row of this ResultSet
object as a java.io.Reader object.

getNCharacterStream(String columnLabel)
Reader
Retrieves the value of the designated column in the current row of this ResultSet

CSE, KSIT, 2019-20 Page 312


Advanced Java & J2EE (17CS553) Study Material

object as a java.io.Reader object.

getNClob(int columnIndex)
NClob Retrieves the value of the designated column in the current row of this ResultSet
object as a NClob object in the Java programming language.

getNClob(String columnLabel)
NClob Retrieves the value of the designated column in the current row of this ResultSet
object as a NClob object in the Java programming language.

getNString(int columnIndex)
String Retrieves the value of the designated column in the current row of this ResultSet
object as a String in the Java programming language.

getNString(String columnLabel)
String Retrieves the value of the designated column in the current row of this ResultSet
object as a String in the Java programming language.

getObject(int columnIndex)
Object Gets the value of the designated column in the current row of this ResultSet object
as an Object in the Java programming language.

getObject(int columnIndex, Class<T> type)

<T> T Retrieves the value of the designated column in the current row of this ResultSet
object and will convert from the SQL type of the column to the requested Java data
type, if the conversion is supported.

getObject(int columnIndex, Map<String,Class<?>> map)


Object Retrieves the value of the designated column in the current row of this ResultSet
object as an Object in the Java programming language.

getObject(String columnLabel)
Object Gets the value of the designated column in the current row of this ResultSet object
as an Object in the Java programming language.

<T> T getObject(String columnLabel, Class<T> type)

CSE, KSIT, 2019-20 Page 313


Advanced Java & J2EE (17CS553) Study Material

Retrieves the value of the designated column in the current row of this ResultSet
object and will convert from the SQL type of the column to the requested Java data
type, if the conversion is supported.

getObject(String columnLabel, Map<String,Class<?>> map)


Object Retrieves the value of the designated column in the current row of this ResultSet
object as an Object in the Java programming language.

getRef(int columnIndex)
Ref Retrieves the value of the designated column in the current row of this ResultSet
object as a Ref object in the Java programming language.

getRef(String columnLabel)
Ref Retrieves the value of the designated column in the current row of this ResultSet
object as a Ref object in the Java programming language.

getRow()
int
Retrieves the current row number.

getRowId(int columnIndex)
RowId Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.RowId object in the Java programming language.

getRowId(String columnLabel)
RowId Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.RowId object in the Java programming language.

getShort(int columnIndex)
short Retrieves the value of the designated column in the current row of this ResultSet
object as a short in the Java programming language.

getShort(String columnLabel)
short Retrieves the value of the designated column in the current row of this ResultSet
object as a short in the Java programming language.

SQLXML getSQLXML(int columnIndex)

CSE, KSIT, 2019-20 Page 314


Advanced Java & J2EE (17CS553) Study Material

Retrieves the value of the designated column in the current row of this ResultSet as
a java.sql.SQLXML object in the Java programming language.

getSQLXML(String columnLabel)
SQLXML Retrieves the value of the designated column in the current row of this ResultSet as
a java.sql.SQLXML object in the Java programming language.

getStatement()
Statement
Retrieves the Statement object that produced this ResultSet object.

getString(int columnIndex)
String Retrieves the value of the designated column in the current row of this ResultSet
object as a String in the Java programming language.

getString(String columnLabel)
String Retrieves the value of the designated column in the current row of this ResultSet
object as a String in the Java programming language.

getTime(int columnIndex)
Time Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Time object in the Java programming language.

getTime(int columnIndex, Calendar cal)


Time Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Time object in the Java programming language.

getTime(String columnLabel)
Time Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Time object in the Java programming language.

getTime(String columnLabel, Calendar cal)


Time Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Time object in the Java programming language.

getTimestamp(int columnIndex)
Timestamp
Retrieves the value of the designated column in the current row of this ResultSet

CSE, KSIT, 2019-20 Page 315


Advanced Java & J2EE (17CS553) Study Material

object as a java.sql.Timestamp object in the Java programming language.

getTimestamp(int columnIndex, Calendar cal)


Timestamp Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Timestamp object in the Java programming language.

getTimestamp(String columnLabel)
Timestamp Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Timestamp object in the Java programming language.

getTimestamp(String columnLabel, Calendar cal)


Timestamp Retrieves the value of the designated column in the current row of this ResultSet
object as a java.sql.Timestamp object in the Java programming language.

getType()
int
Retrieves the type of this ResultSet object.

getUnicodeStream(int columnIndex)

InputStream Deprecated.

use getCharacterStream in place of getUnicodeStream

getUnicodeStream(String columnLabel)

InputStream Deprecated.

use getCharacterStream instead

getURL(int columnIndex)
URL Retrieves the value of the designated column in the current row of this ResultSet
object as a java.net.URL object in the Java programming language.

getURL(String columnLabel)
URL Retrieves the value of the designated column in the current row of this ResultSet
object as a java.net.URL object in the Java programming language.

SQLWarning getWarnings()

CSE, KSIT, 2019-20 Page 316


Advanced Java & J2EE (17CS553) Study Material

Retrieves the first warning reported by calls on this ResultSet object.

insertRow()
void
Inserts the contents of the insert row into this ResultSet object and into the database.

isAfterLast()
boolean
Retrieves whether the cursor is after the last row in this ResultSet object.

isBeforeFirst()
boolean
Retrieves whether the cursor is before the first row in this ResultSet object.

isClosed()
boolean
Retrieves whether this ResultSet object has been closed.

isFirst()
boolean
Retrieves whether the cursor is on the first row of this ResultSet object.

isLast()
boolean
Retrieves whether the cursor is on the last row of this ResultSet object.

last()
boolean
Moves the cursor to the last row in this ResultSet object.

moveToCurrentRow()
void
Moves the cursor to the remembered cursor position, usually the current row.

moveToInsertRow()
void
Moves the cursor to the insert row.

next()
boolean
Moves the cursor froward one row from its current position.

previous()
boolean
Moves the cursor to the previous row in this ResultSet object.

CSE, KSIT, 2019-20 Page 317


Advanced Java & J2EE (17CS553) Study Material

refreshRow()
void
Refreshes the current row with its most recent value in the database.

relative(int rows)
boolean
Moves the cursor a relative number of rows, either positive or negative.

rowDeleted()
boolean
Retrieves whether a row has been deleted.

rowInserted()
boolean
Retrieves whether the current row has had an insertion.

rowUpdated()
boolean
Retrieves whether the current row has been updated.

setFetchDirection(int direction)
void
Gives a hint as to the direction in which the rows in this ResultSet object will be
processed.

setFetchSize(int rows)
void Gives the JDBC driver a hint as to the number of rows that should be fetched from the
database when more rows are needed for this ResultSet object.

updateArray(int columnIndex, Array x)


void
Updates the designated column with a java.sql.Array value.

updateArray(String columnLabel, Array x)


void
Updates the designated column with a java.sql.Array value.

updateAsciiStream(int columnIndex, InputStream x)


void
Updates the designated column with an ascii stream value.

updateAsciiStream(int columnIndex, InputStream x, int length)


void Updates the designated column with an ascii stream value, which will have the
specified number of bytes.

CSE, KSIT, 2019-20 Page 318


Advanced Java & J2EE (17CS553) Study Material

updateAsciiStream(int columnIndex, InputStream x, long length)


void Updates the designated column with an ascii stream value, which will have the
specified number of bytes.

updateAsciiStream(String columnLabel, InputStream x)


void
Updates the designated column with an ascii stream value.

updateAsciiStream(String columnLabel, InputStream x, int length)


void
Updates the designated column with an ascii stream value, which will have the
specified number of bytes.

updateAsciiStream(String columnLabel, InputStream x, long length)


void Updates the designated column with an ascii stream value, which will have the
specified number of bytes.

updateBigDecimal(int columnIndex, BigDecimal x)


void
Updates the designated column with a java.math.BigDecimal value.

updateBigDecimal(String columnLabel, BigDecimal x)


void
Updates the designated column with a java.sql.BigDecimal value.

updateBinaryStream(int columnIndex, InputStream x)


void
Updates the designated column with a binary stream value.

updateBinaryStream(int columnIndex, InputStream x, int length)


void
Updates the designated column with a binary stream value, which will have the
specified number of bytes.

updateBinaryStream(int columnIndex, InputStream x, long length)


void Updates the designated column with a binary stream value, which will have the
specified number of bytes.

updateBinaryStream(String columnLabel, InputStream x)


void
Updates the designated column with a binary stream value.

void updateBinaryStream(String columnLabel, InputStream x, int length)

CSE, KSIT, 2019-20 Page 319


Advanced Java & J2EE (17CS553) Study Material

Updates the designated column with a binary stream value, which will have the
specified number of bytes.

updateBinaryStream(String columnLabel, InputStream x, long length)


void Updates the designated column with a binary stream value, which will have the
specified number of bytes.

updateBlob(int columnIndex, Blob x)


void
Updates the designated column with a java.sql.Blob value.

updateBlob(int columnIndex, InputStream inputStream)


void
Updates the designated column using the given input stream.

updateBlob(int columnIndex, InputStream inputStream,


long length)
void
Updates the designated column using the given input stream, which will have the
specified number of bytes.

updateBlob(String columnLabel, Blob x)


void
Updates the designated column with a java.sql.Blob value.

updateBlob(String columnLabel, InputStream inputStream)


void
Updates the designated column using the given input stream.

updateBlob(String columnLabel, InputStream inputStream,


long length)
void
Updates the designated column using the given input stream, which will have the
specified number of bytes.

updateBoolean(int columnIndex, boolean x)


void
Updates the designated column with a boolean value.

updateBoolean(String columnLabel, boolean x)


void
Updates the designated column with a boolean value.

void updateByte(int columnIndex, byte x)

CSE, KSIT, 2019-20 Page 320


Advanced Java & J2EE (17CS553) Study Material

Updates the designated column with a byte value.

updateByte(String columnLabel, byte x)


void
Updates the designated column with a byte value.

updateBytes(int columnIndex, byte[] x)


void
Updates the designated column with a byte array value.

updateBytes(String columnLabel, byte[] x)


void
Updates the designated column with a byte array value.

updateCharacterStream(int columnIndex, Reader x)


void
Updates the designated column with a character stream value.

updateCharacterStream(int columnIndex, Reader x, int length)


void Updates the designated column with a character stream value, which will have the
specified number of bytes.

updateCharacterStream(int columnIndex, Reader x, long length)


void Updates the designated column with a character stream value, which will have the
specified number of bytes.

updateCharacterStream(String columnLabel, Reader reader)


void
Updates the designated column with a character stream value.

updateCharacterStream(String columnLabel, Reader reader,


int length)
void
Updates the designated column with a character stream value, which will have the
specified number of bytes.

updateCharacterStream(String columnLabel, Reader reader,


long length)
void
Updates the designated column with a character stream value, which will have the
specified number of bytes.

void updateClob(int columnIndex, Clob x)

CSE, KSIT, 2019-20 Page 321


Advanced Java & J2EE (17CS553) Study Material

Updates the designated column with a java.sql.Clob value.

updateClob(int columnIndex, Reader reader)


void
Updates the designated column using the given Reader object.

updateClob(int columnIndex, Reader reader, long length)


void
Updates the designated column using the given Reader object, which is the given
number of characters long.

updateClob(String columnLabel, Clob x)


void
Updates the designated column with a java.sql.Clob value.

updateClob(String columnLabel, Reader reader)


void
Updates the designated column using the given Reader object.

updateClob(String columnLabel, Reader reader, long length)


void Updates the designated column using the given Reader object, which is the given
number of characters long.

updateDate(int columnIndex, Date x)


void
Updates the designated column with a java.sql.Date value.

updateDate(String columnLabel, Date x)


void
Updates the designated column with a java.sql.Date value.

updateDouble(int columnIndex, double x)


void
Updates the designated column with a double value.

updateDouble(String columnLabel, double x)


void
Updates the designated column with a double value.

updateFloat(int columnIndex, float x)


void
Updates the designated column with a float value.

void updateFloat(String columnLabel, float x)

CSE, KSIT, 2019-20 Page 322


Advanced Java & J2EE (17CS553) Study Material

Updates the designated column with a float value.

updateInt(int columnIndex, int x)


void
Updates the designated column with an int value.

updateInt(String columnLabel, int x)


void
Updates the designated column with an int value.

updateLong(int columnIndex, long x)


void
Updates the designated column with a long value.

updateLong(String columnLabel, long x)


void
Updates the designated column with a long value.

updateNCharacterStream(int columnIndex, Reader x)


void
Updates the designated column with a character stream value.

updateNCharacterStream(int columnIndex, Reader x, long length)


void Updates the designated column with a character stream value, which will have the
specified number of bytes.

updateNCharacterStream(String columnLabel, Reader reader)


void
Updates the designated column with a character stream value.

updateNCharacterStream(String columnLabel, Reader reader,


long length)
void
Updates the designated column with a character stream value, which will have the
specified number of bytes.

updateNClob(int columnIndex, NClob nClob)


void
Updates the designated column with a java.sql.NClob value.

updateNClob(int columnIndex, Reader reader)


void
Updates the designated column using the given Reader The data will be read from the
stream as needed until end-of-stream is reached.

CSE, KSIT, 2019-20 Page 323


Advanced Java & J2EE (17CS553) Study Material

updateNClob(int columnIndex, Reader reader, long length)


void
Updates the designated column using the given Reader object, which is the given
number of characters long.

updateNClob(String columnLabel, NClob nClob)


void
Updates the designated column with a java.sql.NClob value.

updateNClob(String columnLabel, Reader reader)


void
Updates the designated column using the given Reader object.

updateNClob(String columnLabel, Reader reader, long length)


void
Updates the designated column using the given Reader object, which is the given
number of characters long.

updateNString(int columnIndex, String nString)


void
Updates the designated column with a String value.

updateNString(String columnLabel, String nString)


void
Updates the designated column with a String value.

updateNull(int columnIndex)
void
Updates the designated column with a null value.

updateNull(String columnLabel)
void
Updates the designated column with a null value.

updateObject(int columnIndex, Object x)


void
Updates the designated column with an Object value.

updateObject(int columnIndex, Object x, int scaleOrLength)


void
Updates the designated column with an Object value.

updateObject(String columnLabel, Object x)


void
Updates the designated column with an Object value.

CSE, KSIT, 2019-20 Page 324


Advanced Java & J2EE (17CS553) Study Material

updateObject(String columnLabel, Object x, int scaleOrLength)


void
Updates the designated column with an Object value.

updateRef(int columnIndex, Ref x)


void
Updates the designated column with a java.sql.Ref value.

updateRef(String columnLabel, Ref x)


void
Updates the designated column with a java.sql.Ref value.

updateRow()
void Updates the underlying database with the new contents of the current row of this
ResultSet object.

updateRowId(int columnIndex, RowId x)


void
Updates the designated column with a RowId value.

updateRowId(String columnLabel, RowId x)


void
Updates the designated column with a RowId value.

updateShort(int columnIndex, short x)


void
Updates the designated column with a short value.

updateShort(String columnLabel, short x)


void
Updates the designated column with a short value.

updateSQLXML(int columnIndex, SQLXML xmlObject)


void
Updates the designated column with a java.sql.SQLXML value.

updateSQLXML(String columnLabel, SQLXML xmlObject)


void
Updates the designated column with a java.sql.SQLXML value.

updateString(int columnIndex, String x)


void
Updates the designated column with a String value.

CSE, KSIT, 2019-20 Page 325


Advanced Java & J2EE (17CS553) Study Material

updateString(String columnLabel, String x)


void
Updates the designated column with a String value.

updateTime(int columnIndex, Time x)


void
Updates the designated column with a java.sql.Time value.

updateTime(String columnLabel, Time x)


void
Updates the designated column with a java.sql.Time value.

updateTimestamp(int columnIndex, Timestamp x)


void
Updates the designated column with a java.sql.Timestamp value.

updateTimestamp(String columnLabel, Timestamp x)


void
Updates the designated column with a java.sql.Timestamp value.

wasNull()
boolean
Reports whether the last column read had a value of SQL NULL.

java.sql

Interface Statement
public interface Statement
extends Wrapper, AutoCloseable

The object used for executing a static SQL statement and returning the results it produces.

By default, only one ResultSet object per Statement object can be open at the same time. Therefore,
if the reading of one ResultSet object is interleaved with the reading of another, each must have been
generated by different Statement objects. All execution methods in the Statement interface implicitly
close a statment's current ResultSet object if an open one exists.

Method Summary
Methods

Modifier and
Method and Description
Type

addBatch(String sql)
void
Adds the given SQL command to the current list of commmands for this Statement

CSE, KSIT, 2019-20 Page 326


Advanced Java & J2EE (17CS553) Study Material

object.

cancel()
void
Cancels this Statement object if both the DBMS and driver support aborting an SQL
statement.

clearBatch()
void
Empties this Statement object's current list of SQL commands.

clearWarnings()
void
Clears all the warnings reported on this Statement object.

close()
void
Releases this Statement object's database and JDBC resources immediately instead of
waiting for this to happen when it is automatically closed.

closeOnCompletion()
void
Specifies that this Statement will be closed when all its dependent result sets are closed.

execute(String sql)
boolean
Executes the given SQL statement, which may return multiple results.

execute(String sql, int autoGeneratedKeys)


boolean Executes the given SQL statement, which may return multiple results, and signals the driver
that any auto-generated keys should be made available for retrieval.

execute(String sql, int[] columnIndexes)

boolean Executes the given SQL statement, which may return multiple results, and signals the driver
that the auto-generated keys indicated in the given array should be made available for
retrieval.

execute(String sql, String[] columnNames)

boolean Executes the given SQL statement, which may return multiple results, and signals the driver
that the auto-generated keys indicated in the given array should be made available for
retrieval.

CSE, KSIT, 2019-20 Page 327


Advanced Java & J2EE (17CS553) Study Material

executeBatch()
int[] Submits a batch of commands to the database for execution and if all commands execute
successfully, returns an array of update counts.

executeQuery(String sql)
ResultSet
Executes the given SQL statement, which returns a single ResultSet object.

executeUpdate(String sql)
int
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE
statement or an SQL statement that returns nothing, such as an SQL DDL statement.

executeUpdate(String sql, int autoGeneratedKeys)

int Executes the given SQL statement and signals the driver with the given flag about whether
the auto-generated keys produced by this Statement object should be made available for
retrieval.

executeUpdate(String sql, int[] columnIndexes)


int Executes the given SQL statement and signals the driver that the auto-generated keys
indicated in the given array should be made available for retrieval.

executeUpdate(String sql, String[] columnNames)


int Executes the given SQL statement and signals the driver that the auto-generated keys
indicated in the given array should be made available for retrieval.

getConnection()
Connection
Retrieves the Connection object that produced this Statement object.

getFetchDirection()
int Retrieves the direction for fetching rows from database tables that is the default for result
sets generated from this Statement object.

getFetchSize()
int Retrieves the number of result set rows that is the default fetch size for ResultSet
objects generated from this Statement object.

ResultSet getGeneratedKeys()

CSE, KSIT, 2019-20 Page 328


Advanced Java & J2EE (17CS553) Study Material

Retrieves any auto-generated keys created as a result of executing this Statement object.

getMaxFieldSize()
int Retrieves the maximum number of bytes that can be returned for character and binary
column values in a ResultSet object produced by this Statement object.

getMaxRows()
int Retrieves the maximum number of rows that a ResultSet object produced by this
Statement object can contain.

getMoreResults()

boolean Moves to this Statement object's next result, returns true if it is a ResultSet object,
and implicitly closes any current ResultSet object(s) obtained with the method
getResultSet.

getMoreResults(int current)

boolean Moves to this Statement object's next result, deals with any current ResultSet
object(s) according to the instructions specified by the given flag, and returns true if the
next result is a ResultSet object.

getQueryTimeout()
int
Retrieves the number of seconds the driver will wait for a Statement object to execute.

getResultSet()
ResultSet
Retrieves the current result as a ResultSet object.

getResultSetConcurrency()
int Retrieves the result set concurrency for ResultSet objects generated by this
Statement object.

getResultSetHoldability()
int Retrieves the result set holdability for ResultSet objects generated by this Statement
object.

getResultSetType()
int
Retrieves the result set type for ResultSet objects generated by this Statement object.

CSE, KSIT, 2019-20 Page 329


Advanced Java & J2EE (17CS553) Study Material

getUpdateCount()
int
Retrieves the current result as an update count; if the result is a ResultSet object or there
are no more results, -1 is returned.

getWarnings()
SQLWarning
Retrieves the first warning reported by calls on this Statement object.

isClosed()
boolean
Retrieves whether this Statement object has been closed.

isCloseOnCompletion()
boolean
Returns a value indicating whether this Statement will be closed when all its dependent
result sets are closed.

isPoolable()
boolean
Returns a value indicating whether the Statement is poolable or not.

setCursorName(String name)
void Sets the SQL cursor name to the given String, which will be used by subsequent
Statement object execute methods.

setEscapeProcessing(boolean enable)
void
Sets escape processing on or off.

setFetchDirection(int direction)
void Gives the driver a hint as to the direction in which rows will be processed in ResultSet
objects created using this Statement object.

setFetchSize(int rows)

void Gives the JDBC driver a hint as to the number of rows that should be fetched from the
database when more rows are needed for ResultSet objects genrated by this
Statement.

setMaxFieldSize(int max)
void
Sets the limit for the maximum number of bytes that can be returned for character and

CSE, KSIT, 2019-20 Page 330


Advanced Java & J2EE (17CS553) Study Material

binary column values in a ResultSet object produced by this Statement object.

setMaxRows(int max)
void Sets the limit for the maximum number of rows that any ResultSet object generated by
this Statement object can contain to the given number.

setPoolable(boolean poolable)
void
Requests that a Statement be pooled or not pooled.

setQueryTimeout(int seconds)
void
Sets the number of seconds the driver will wait for a Statement object to execute to the
given number of seconds.

java.sql

Interface Savepoint
public interface Savepoint

The representation of a savepoint, which is a point within the current transaction that can be
referenced from the Connection.rollback method. When a transaction is rolled back to a
savepoint all changes made after that savepoint are undone.

Savepoints can be either named or unnamed. Unnamed savepoints are identified by an ID generated
by the underlying data source.

o Method Summary

Methods

Modifier and
Method and Description
Type

getSavepointId()
int Retrieves the generated ID for the savepoint that this Savepoint object
represents.

CSE, KSIT, 2019-20 Page 331


Advanced Java & J2EE (17CS553) Study Material

getSavepointName()
String Retrieves the name of the savepoint that this Savepoint object
represents.

java.sql

Class DriverManager

java.lang.Object

o java.sql.DriverManager

public class DriverManager


extends Object

The basic service for managing a set of JDBC drivers.


NOTE: The DataSource interface, new in the JDBC 2.0 API, provides another way to connect to a
data source. The use of a DataSource object is the preferred means of connecting to a data source.

As part of its initialization, the DriverManager class will attempt to load the driver classes
referenced in the "jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used
by their applications. For example in your ~/.hotjava/properties file you might specify:

jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver

The DriverManager methods getConnection and getDrivers have been enhanced to support
the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-
INF/services/java.sql.Driver. This file contains the name of the JDBC drivers
implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-
INF/services/java.sql.Driver file would contain the entry:

my.sql.Driver

Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing
programs which currently load JDBC drivers using Class.forName() will continue to work without
modification.

When the method getConnection is called, the DriverManager will attempt to locate a suitable
driver from amongst those loaded at initialization and those loaded explicitly using the same classloader
as the current applet or application.

Starting with the Java 2 SDK, Standard Edition, version 1.3, a logging stream can be set only if the
proper permission has been granted. Normally this will be done with the tool PolicyTool, which can be
used to grant permission java.sql.SQLPermission "setLog".

CSE, KSIT, 2019-20 Page 332


Advanced Java & J2EE (17CS553) Study Material

Method Summary
Methods

Modifier and Type Method and Description

deregisterDriver(Driver driver)
static void
Drops a driver from the DriverManager's list.

getConnection(String url)
static Connection
Attempts to establish a connection to the given database URL.

getConnection(String url, Properties info)


static Connection
Attempts to establish a connection to the given database URL.

getConnection(String url, String user, String password)


static Connection
Attempts to establish a connection to the given database URL.

getDriver(String url)
static Driver
Attempts to locate a driver that understands the given URL.

getDrivers()
static
Enumeration<Driver> Retrieves an Enumeration with all of the currently loaded JDBC drivers to
which the current caller has access.

getLoginTimeout()
static int Gets the maximum time in seconds that a driver can wait when attempting to
log in to a database.

getLogStream()
static PrintStream
Deprecated.

getLogWriter()
static PrintWriter
Retrieves the log writer.

println(String message)
static void
Prints a message to the current JDBC log stream.

CSE, KSIT, 2019-20 Page 333


Advanced Java & J2EE (17CS553) Study Material

registerDriver(Driver driver)
static void
Registers the given driver with the DriverManager.

setLoginTimeout(int seconds)
static void Sets the maximum time in seconds that a driver will wait while attempting to
connect to a database.

setLogStream(PrintStream out)
static void
Deprecated.

setLogWriter(PrintWriter out)
static void Sets the logging/tracing PrintWriter object that is used by the
DriverManager and all drivers.

java.sql

Class Date

java.lang.Object

o java.util.Date
o
 java.sql.Date

public class Date


extends Date

A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A
milliseconds value represents the number of milliseconds that have passed since January 1, 1970
00:00:00.000 GMT.

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date
instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the
particular time zone with which the instance is associated.

Constructor Summary
Constructors

Constructor and Description

Date(int year, int month, int day)

Deprecated.

CSE, KSIT, 2019-20 Page 334


Advanced Java & J2EE (17CS553) Study Material

instead use the constructor Date(long date)

Date(long date)

Constructs a Date object using the given milliseconds time value.

Method Summary
Methods

Modifier and Type Method and Description

getHours()
int
Deprecated.

getMinutes()
int
Deprecated.

getSeconds()
int
Deprecated.

setHours(int i)
void
Deprecated.

setMinutes(int i)
void
Deprecated.

setSeconds(int i)
void
Deprecated.

setTime(long date)
void
Sets an existing Date object using the given milliseconds time value.

toString()
String
Formats a date in the date escape format yyyy-mm-dd.

static Date valueOf(String s)

CSE, KSIT, 2019-20 Page 335


Advanced Java & J2EE (17CS553) Study Material

Converts a string in JDBC date escape format to a Date value.

java.sql

Class Timestamp

java.lang.Object

o java.util.Date
o
 java.sql.Timestamp

public class Timestamp


extends Date

A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL
TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing
the specification of fractional seconds to a precision of nanoseconds. A Timestamp also provides formatting
and parsing operations to support the JDBC escape syntax for timestamp values.

The precision of a Timestamp object is calculated to be either:

19 , which is the number of characters in yyyy-mm-dd hh:mm:ss


20 + s , which is the number of characters in the yyyy-mm-dd hh:mm:ss.[fff...] and s represents
the scale of the given Timestamp, its fractional seconds precision.

Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral
seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate.
The Timestamp.equals(Object) method never returns true when passed an object that isn't an
instance of java.sql.Timestamp, because the nanos component of a date is unknown. As a result, the
Timestamp.equals(Object) method is not symmetric with respect to the
java.util.Date.equals(Object) method. Also, the hashCode method uses the underlying
java.util.Date implementation and therefore does not include nanos in its computation.

Due to the differences between the Timestamp class and the java.util.Date class mentioned above,
it is recommended that code not view Timestamp values generically as an instance of
java.util.Date. The inheritance relationship between Timestamp and java.util.Date really
denotes implementation inheritance, and not type inheritance.

Constructor Summary
Constructors

Constructor and Description

Timestamp(int year, int month, int date, int hour, int minute,
int second, int nano)

CSE, KSIT, 2019-20 Page 336


Advanced Java & J2EE (17CS553) Study Material

Deprecated.

instead use the constructor Timestamp(long millis)

Timestamp(long time)

Constructs a Timestamp object using a milliseconds time value.

Method Summary
Methods

Modifier and
Method and Description
Type

after(Timestamp ts)
boolean
Indicates whether this Timestamp object is later than the given Timestamp
object.

before(Timestamp ts)
boolean
Indicates whether this Timestamp object is earlier than the given Timestamp
object.

compareTo(Date o)
int
Compares this Timestamp object to the given Date object.

compareTo(Timestamp ts)
int
Compares this Timestamp object to the given Timestamp object.

equals(Object ts)
boolean
Tests to see if this Timestamp object is equal to the given object.

equals(Timestamp ts)
boolean
Tests to see if this Timestamp object is equal to the given Timestamp object.

getNanos()
int
Gets this Timestamp object's nanos value.

CSE, KSIT, 2019-20 Page 337


Advanced Java & J2EE (17CS553) Study Material

getTime()
long Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Timestamp object.

hashCode()
int
Returns a hash code value for this object.

setNanos(int n)
void
Sets this Timestamp object's nanos field to the given value.

setTime(long time)
void Sets this Timestamp object to represent a point in time that is time milliseconds
after January 1, 1970 00:00:00 GMT.

toString()
String
Formats a timestamp in JDBC timestamp escape format.

valueOf(String s)
static
Timestamp Converts a String object in JDBC timestamp escape format to a Timestamp
value.

CSE, KSIT, 2019-20 Page 338

You might also like