17CS553 Notes 2019 20
17CS553 Notes 2019 20
Module-1
Enumeration, Auto Boxing and Annotations
Enumeration
Enumeration Fundamentals
Example:
Case Hatchback:
//…
break;
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.
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
General form:
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;
}
Features:
enum Car{
Hatchback(9),Sedan(12),MPV(20),SUV(35);
int price;
Car (int price)
{
this.price=price;
}
int getPrice()
{
return price;
}
}
class EnumClassDemo
{
}
O/P:
Displaying Prices of Cars
Hatchback Car price is 9 Lakh
CSE, KSIT, 2019-20 Page 5
Advanced Java & J2EE (17CS553) Study Material
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
{
}
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
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;
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.
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
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
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
Within an expression, a numeric object is automatically unboxed. The outcome of the expression is reboxed.
Example
class AutoBoxExpressions
{
O/P
class AutoBoxDiffNumObjs
{
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
{
case 2:
System.out.println("Two");
break;
default:
System.out.println("Error");
}
}
}
O/P
Two
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
}
/*
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
*/
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.
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.
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.
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
// deprecation warning
// - suppressed
objectOne.deprecatedMethod();
}
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.
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
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.
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
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).
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.
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.
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.
Interface Description
Collection The root of the collection hierarchy. A collection represents a group of objects
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 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>
Methods Summary
Methods
Modifier and
Method and Description
Type
add(E e)
boolean
Ensures that this collection contains the specified element (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).
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.
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)
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()
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
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
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
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.
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.
AbstractSequentialList Extends AbstractList for use by a collection that uses sequential rather
than random access of its elements.
<E> specifies the type of object that the ArrayList will hold.
Constructors Summary
ArrayList()
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)
Methods Summary
Methods
Modifier and
Method and Description
Type
add(E e)
boolean
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 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.
retainAll(Collection<?> c)
boolean
Retains only the elements in this list that are contained in the specified collection.
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.
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
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
}
}
The output of the program is shown here:
Contents of a1: [1, 2, 3, 4]
Sum is: 10
Constructors Summary
Constructors
LinkedList()
Constructs a list containing the elements of the specified collection, in the order they are returned by the
collection's iterator.
Methods Summary
Methods
Modifier and
Method and Description
Type
add(E e)
boolean
Appends the specified element to the end of this list.
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.
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.
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)
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).
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");
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);
}
}
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
HashSet()
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor
(0.75).
HashSet(int initialCapacity)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default
load factor (0.75).
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);
}
}
[D, E, F, A, B, C]
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
LinkedHashSet()
Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
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).
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);
}
}
Constructors Summary
Constructors
TreeSet()
Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
Constructs a new tree set containing the elements in the specified collection, sorted according to the natural
ordering of its elements.
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
add(E e)
boolean
Adds the specified element to this set if it is not already present.
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
headSet(E toElement)
SortedSet<E> Returns a view of the portion of this set whose elements are strictly less than
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()
tailSet(E fromElement)
SortedSet<E> Returns a view of the portion of this set whose elements are greater than or equal to
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]
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 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
PriorityQueue()
Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their
natural ordering.
PriorityQueue(int initialCapacity)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural
ordering.
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified
comparator.
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.
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.
Constructors Summary
Constructors
ArrayDeque()
Constructs an empty array deque with an initial capacity sufficient to hold 16 elements.
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>();
Method Summary
Methods
clone()
EnumSet<E>
Returns a copy of this set.
Interface Iterator<E>
Type Parameters:
E - the type of elements returned by this iterator
ListIterator<E>, XMLEventReader
Method Summary
Methods
Modifier and
Method and Description
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.
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).
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();
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
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.
Interface Map<K,V>
Type Parameters:
K - the type of keys maintained by this map
This interface takes the place of the Dictionary class, which was a totally abstract class rather than an
interface.
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 Classes
Map.Entry<K,V>
static interface
A map entry (key-value pair).
Method Summary
Methods
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
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.
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
All Superinterfaces:
Map<K,V>
ConcurrentNavigableMap<K,V>, NavigableMap<K,V>
ConcurrentSkipListMap, TreeMap
Map.Entry<K,V>
Method Summary
Methods
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()
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.
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>
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
equals(Object o)
boolean
Compares the specified object with this entry for equality.
getKey()
K
Returns the key corresponding to this entry.
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).
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
LinkedHashMap, PrinterStateReasons
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.)
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.
AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>
Constructor Summary
Constructors
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).
Constructs an empty HashMap with the specified initial capacity and load factor.
Constructs a new HashMap with the same mappings as the specified Map.
Method Summary
Methods
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.
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.
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)
{
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
AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>
Constructor Summary
Constructors
TreeMap()
Constructs a new, empty tree map, using the natural ordering of its keys.
Constructs a new, empty tree map, ordered according to the given comparator.
Constructs a new tree map containing the same mappings as the given map, ordered according to the natural
ordering of its keys.
Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted
map.
Method Summary
Methods
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
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.
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.
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.
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.
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.
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.
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
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).
AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>
Constructor Summary
Constructors
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).
Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and load
factor.
Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering
mode.
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.
java.lang.Object
o java.util.AbstractMap<K,V>
o
java.util.EnumMap<K,V>
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.
AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>
Map.Entry<K,V>
Constructor Summary
Constructors
EnumMap(Class<K> keyType)
Creates an enum map with the same key type as the specified enum map, initially containing the same
mappings (if any).
Method Summary
Methods
void clear()
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.
remove(Object key)
V
Removes the mapping for this key from this map if present.
int size()
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
Collator, RuleBasedCollator
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
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();
}
}
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());
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
*/
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.
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
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.
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)
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.
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)
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.
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.
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.
Returns true if the two specified arrays of floats are equal to one another.
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(char[] a)
static void
Sorts the specified array into ascending numerical order.
sort(double[] a)
static void
Sorts the specified array into ascending numerical order.
sort(float[] a)
static void
Sorts the specified array into ascending numerical order.
sort(int[] a)
static void
Sorts the specified array into ascending numerical order.
sort(long[] a)
static void
Sorts the specified array into ascending numerical order.
sort(Object[] a)
static void
Sorts 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.
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:
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));
}
}
Dictionary
Hashtable
Properties
Stack
Vector
-------------------------------------------------------------------------------------------------------------
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.
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));
}
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));
}
}
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
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
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)
{
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"));
}
}
Class Stack<E>
public class Stack<E>
extends Vector<E>
Field Summary
o Fields inherited from class java.util.Vector
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
{
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");
}
}
}
Class Vector<E>
Field Summary
Fields
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.
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.
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)
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())
System.out.print(e.nextElement()+" ");
System.out.println();
}
}
Enumeration Interface
Interface Enumeration<E>
All Known Subinterfaces:
NamingEnumeration<T>
StringTokenizer
General Form:
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.
Interface Iterator<E>
Type Parameters:
E - the type of elements returned by this iterator
ListIterator<E>, XMLEventReader
Method Summary
Methods
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.
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).
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)
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.
Class Arrays
java.lang.Object
o java.util.Arrays
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
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)
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)
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)
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.
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.
Module-3
String and StringBuffer
Class String
java.lang.Object
o java.lang.String
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:
is equivalent to:
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
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)
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
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()
java.lang
Class StringBuffer
java.lang.Object
o java.lang.StringBuffer
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.
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.
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
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)
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.
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
System.out.println(longStr);
int age=20;
String s=‖ksit is‖+age+‖years old.‖;
System.out.println(s);
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
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;
}
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);
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.
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);
}
}
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()
e.g. program
class toCharArrayDemo
{
public static void main(String args[])
{
String s="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));
}
}
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
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";
}
}
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
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));
}
}
Hello == Hello-->false
Method compareTo()
e.g. program
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
it
is
ksit
metro
near
station
to
to
Searching Strings
Methods:
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)
{
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));
}
}
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;
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);
}
}
concat() method
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);
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);
}
}
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.
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
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.
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.
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(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)
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.
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
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);
}
}
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.");
}
}
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)
{
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");
}
}
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.
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.
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.
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.
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.
Apache Tomcat
―The Apache Tomcat software is an open source implementation of the Java Servlet, JavaServer Pages, Java
Expression Language and Java WebSocket technologies.
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.
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.
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
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.
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.
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.
init()
service()
destroy()
The above methods are implemented by every servlet and are invoked at a specific times by the server.
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.
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.
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.
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.
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.
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.
Exception Summary
ServletException Defines a general exception a servlet can throw when it encounters difficulty.
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
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.
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:
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.
javax.servlet
Interface ServletConfig
All Known Implementing Classes:
GenericServlet, HttpServlet
General Form:
A servlet configuration object used by a servlet container to pass information to a servlet during
initialization.
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.
java.lang.String getContextPath()
Returns the context path of the web application.
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.
int getMinorVersion()
Returns the minor version of the Servlet API that this servlet container supports.
java.lang.String getServerInfo()
Returns the name and version of the servlet container on which the servlet is
running.
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.
Removes the attribute with the given name from the servlet context.
javax.servlet
Interface ServletRequest
All Known Subinterfaces:
HttpServletRequest
HttpServletRequestWrapper, ServletRequestWrapper
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.
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.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 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.
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.
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.
javax.servlet
Interface ServletResponse
All Known Subinterfaces:
HttpServletResponse
HttpServletResponseWrapper, ServletResponseWrapper
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.
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.
javax.servlet
Class GenericServlet
java.lang.Object
javax.servlet.GenericServlet
All Implemented Interfaces:
HttpServlet
Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend
HttpServlet instead.
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.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()
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).
avax.servlet
Class ServletInputStream
java.lang.Object
java.io.InputStream
javax.servlet.ServletInputStream
All Implemented Interfaces:
java.io.Closeable
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.
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
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
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).
javax.servlet
Class ServletException
java.lang.Object
java.lang.Throwable
java.lang.Exception
javax.servlet.ServletException
All Implemented Interfaces:
java.io.Serializable
UnavailableException
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.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.
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
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(java.lang.String msg)
Constructs a new exception with a descriptive message indicating that the servlet is permanently 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.
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.
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.
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.
javax.servlet.http
Interface HttpServletRequest
All Superinterfaces:
ServletRequest
HttpServletRequestWrapper
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.
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
request.
java.util.Enumeration getHeaderNames()
Returns an enumeration of all the header names this request contains.
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()
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.
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.
javax.servlet.http
Interface HttpServletResponse
All Superinterfaces:
ServletResponse
HttpServletResponseWrapper
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.
Method Summary
void addCookie(Cookie cookie)
Adds the specified cookie to the response.
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.
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
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.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.
javax.servlet.http
Interface HttpSessionBindingListener
All Superinterfaces:
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.
javax.servlet.http
Class Cookie
java.lang.Object
javax.servlet.http.Cookie
All Implemented Interfaces:
java.lang.Cloneable
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 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
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 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
javax.servlet.http.HttpServlet
All Implemented Interfaces:
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:
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.
Called by the server (via the service method) to allow a servlet to handle a GET
request.
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
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.
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
HttpSessionBindingEvent
Constructor Summary
HttpSessionEvent(HttpSession source)
Construct a session event from the given source.
Method Summary
HttpSession getSession()
Return the session that changed.
Introduction
• 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.
– 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.
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 %>.
(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.
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.
1. Comment Tag
• 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 %>.
– import: This directive is used to import Java packages into JSP program.
– include: This directive inserts a specified file into the JSP program replacing the include
tag.
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 %>.
5. Scriptlet tags
A scriptlet tag opens with <% and contains commonly used Java control statements and
loops. A scriptlet tag closes with %>.
To declare variables and create objects use declaration statement tag <%! %> with expression tag.
<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
Age is: 20
<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>
Age is: 20
Salary is: 999.99
Emp ID is: 9
<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<%! String Name;
String[] Telephone={―080-1234567‖,‖+91-0123456789‖};
Vector assignments=new Vector();
%>
</body>
</html>
Methods
<html>
<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>
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;
case 60 : %>
<p>Your final grade is a F</p>
<% break;
}
%>
</body>
</html>
Pass
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.
<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">
• 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.
• 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
<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>
</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
Cookies
a) HTML code : JSPCookie.html
<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>
</body>
</html>
<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();
CValue=cookies[i].getValue();
if(MyCookieName.equals(CName))
{
found=1;
MyCookieValue=CValue;
}
}
%>
<% if(found==1){%>
a)
b)
c)
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.
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>
1.SET VARIABLES
AS FOLLOWS
CATALINA_HOME=F:\Tomcat7\apache-tomcat-7.0.64
JAVA_HOME=C:\Program Files\Java\jdk1.7.0_25
JRE_HOME=C:\Program Files\Java\jdk1.7.0_25\jre
CLASSPATH=.;F:\Tomcat7\apache-tomcat-7.0.64\lib\servlet-api.jar;
F:\>%CATALINA_HOME%\bin\startup
F:\>tree tomcat7
F:\TOMCAT7
└───apache-tomcat-7.0.64
├───bin
├───conf
│ └───Catalina
│ └───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
│ │ ├───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
│ │ │ │ └───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
│ │ │ │ ├───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
│ ├───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
│ └───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
└───_
└───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
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String c=req.getParameter("colors");
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String c=req.getParameter("colors");
import java.util.*;
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
import java.util.*;
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
"<p>Today's date:"+d);
import java.util.*;
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
"<p>Today's date:"+d);
import java.io.*;
import java.util.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String s=req.getParameter("nums");
System.out.println("hello");
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("</br>");
import java.io.*;
import java.util.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String s=req.getParameter("nums");
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("</br>");
<html>
<head>
</head>
<body>
<label>Select Color</label>
<select name="colors">
<option value="red">RED</option>
<option value="orange">ORANGE</option>
<option value="green">GREEN</option>
</select>
</form>
</body>
</html>
<html>
<head>
</head>
<body>
</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
F:\tomcat7\apache-tomcat-7.0.64\webapps\fivea\web-inf
<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>
<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>
<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>
http://localhost:8080/fivea/HelloServlet
http://localhost:8080/fivea/Color.html
http://localhost:8080/fivea/Sort.html
Enter the numbers with one space between in the text box as shown below
Module-5
The Java Database Connectivity and Transactions
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.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.
• 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.
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:
Disadvantage:
• Extra translation time might negatively impact performance in a mission critical applications.
• 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:
• 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.
• 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 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);
}
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);
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);
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
{
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
catch (SQLException e)
{
System. err.println ("ResultsetException: "+e.getMessage());
System.exit(4);
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
{
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);
Class Description
Interface Description
Statement Object
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
{
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);
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));
}
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
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)
{
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
CallableStatement object
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.
• 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.
Methods to read values from a Resultset into variables that can be later further processed by the J2EE
components are:
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
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
both directions.
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();
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
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:
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);
• 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);
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);
}
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);
• 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.
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);
}
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
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.
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.
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());
}
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();
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);
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());
}
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]);
}
}
}
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.
• 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.
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 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
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:
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
Others
BatchUpdateException
SQLClientInfoException
SQLDataException
SQLFeatureNotSupportedException
SQLIntegrityConstraintViolationException
SQLInvalidAuthorizationSpecException
SQLNonTransientConnectionException
SQLNonTransientException
SQLRecoverableException
SQLSyntaxErrorException
SQLTimeoutException
SQLTransactionRollbackException
SQLTransientConnectionException
SQLTransientException
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.
Retrieves a description of the given attribute of the given type for a user-defined type (UDT) that
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.
getConnection()
Connection
Retrieves the connection that produced this metadata object.
getDatabaseMajorVersion()
int
Retrieves the major version number of the underlying database.
int getDatabaseMinorVersion()
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.
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 _).
getIdentifierQuoteString()
String
Retrieves the string used to quote SQL identifiers.
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).
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.
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.
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.
getProcedureTerm()
String
Retrieves the database vendor's preferred term for "procedure".
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.
String getSchemaTerm()
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()
getStringFunctions()
String
Retrieves a comma-separated list of string functions available with this database.
getSystemFunctions()
String
Retrieves a comma-separated list of system functions available with this database.
getTableTypes()
ResultSet
Retrieves the table types available in this database.
String getTimeDateFunctions()
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.
getURL()
String
Retrieves the URL for this DBMS.
getUserName()
String
Retrieves the user name as known to this database.
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.
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
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.
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.
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.
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
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
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.
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.
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.
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
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.
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.
For maximum portability, a call's ResultSet objects and update counts should be processed prior to
getting the values of output parameters.
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)
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.
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.
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(String parameterName)
Date
Retrieves the value of a JDBC DATE parameter as a java.sql.Date object.
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.
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.
getObject(int parameterIndex)
Object Retrieves the value of the designated parameter as an Object in the Java programming
language.
<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(String parameterName)
Object
Retrieves the value of a parameter as an Object in the Java programming language.
<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.
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.
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.
getTimestamp(int parameterIndex)
Timestamp Retrieves the value of the designated JDBC TIMESTAMP parameter as a
java.sql.Timestamp object.
getTimestamp(String parameterName)
Timestamp Retrieves the value of a JDBC TIMESTAMP parameter as a java.sql.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.
sqlType.
Sets the value of the designated parameter with the given 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
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.
Method Summary
Methods
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.
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.
getAutoCommit()
boolean
Retrieves the current auto-commit mode for this Connection object.
String getCatalog()
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.
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.
prepareStatement(String sql)
PreparedStatement Creates a PreparedStatement object for sending parameterized SQL
statements to the database.
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.
setHoldability(int holdability)
void Changes the default holdability of ResultSet objects created using this
Connection object to the given holdability.
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.
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.
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.
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.
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.
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.
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(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.
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
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()
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(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.
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.
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
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.
<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(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.
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.
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.
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(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.
getTimestamp(int columnIndex)
Timestamp
Retrieves the value of the designated column in the current row of this ResultSet
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.
getType()
int
Retrieves the type of this ResultSet object.
getUnicodeStream(int columnIndex)
InputStream Deprecated.
getUnicodeStream(String columnLabel)
InputStream Deprecated.
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()
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.
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.
Updates the designated column with a binary stream value, which will have the
specified number of bytes.
updateNull(int columnIndex)
void
Updates the designated column with a null value.
updateNull(String columnLabel)
void
Updates the designated column with a null value.
updateRow()
void Updates the underlying database with the new contents of the current row of this
ResultSet object.
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
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.
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.
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.
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.
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.
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()
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.
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
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.
getSavepointName()
String Retrieves the name of the savepoint that this Savepoint object
represents.
java.sql
Class DriverManager
java.lang.Object
o java.sql.DriverManager
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".
Method Summary
Methods
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.
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.
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
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
Deprecated.
Date(long date)
Method Summary
Methods
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.
java.sql
Class Timestamp
java.lang.Object
o java.util.Date
o
java.sql.Timestamp
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.
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
Timestamp(int year, int month, int date, int hour, int minute,
int second, int nano)
Deprecated.
Timestamp(long time)
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.
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.