17CS553-AJJ - 5th-Sem-Modulewise-Notes-CSE - Muneshwara M.S
17CS553-AJJ - 5th-Sem-Modulewise-Notes-CSE - Muneshwara M.S
* Visit https://vtuconnect.in for more info. For any queries or questions wrt our
platform contact us at: support@vtuconnect.in
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
MODULEWISE NOTES OF
SEMESTER – V
Prepared by,
Mr. Muneshwara M S
Asst. Prof, Dept. of CSE
Vision
To develop technical professionals acquainted with recent trends and technologies of computer science to serve as valuable resource
for the nation/society.
Mission:
Facilitating and exposing the students to various learning opportunities through dedicated academic teaching, guidance and
monitoring.
Vision
To emerge as one of the finest technical institutions of higher learning, to develop engineering professionals who are technically
- 560064.
competent, ethical and environment friendly for betterment of the society.
Mission
Accomplish stimulating learning environment through high quality academic instruction, innovation and industry-institute interface
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
MODULE -1
Enumerations, Autoboxing, and Annotations(Metadata)
Enumerations
• Enumerations included in JDK 5. An enumeration is a list of named constants.
It is similar to final variables.
• Enum in java is a data type that contains fixed set of constants.
• An enumeration defines a class type in Java. By making enumerations into
classes, so it can have constructors, methods, and instance variables.
• An enumeration is created using the enum keyword.
Ex:
enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }
• The identifiers Jonathan, GoldenDel, and so on, are called enumeration
constants.
• Each is implicitly declared as a public, static final member of Apple.
• Enumeration variable can be created like other primitive variable. It does not
use the new for creating object.
Ex:Apple ap;
Ap is of type Apple, the only values that it can be assigned (or can contain)
are those defined by the enumeration. For example, this assigns:
ap = Apple.RedDel;
Example Code-1
if(ap == Apple.GoldenDel)
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
All enumerations automatically contain two predefined methods: values( ) and valueOf( ).
The values( ) method returns an array that contains a list of the enumeration constants.
The valueOf( ) method returns the enumeration constant whose value corresponds to
the string passed in str.
Example Code-2:
Example Code-3
class EnumExample5
{
enum Day
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDA Y,
SATURDAY
}
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
switch(day)
{
case SUNDAY: System.out.println("sunday"); break;
case MONDAY: System.out.println("monday"); break;
default: System.out.println("other day");
}
}
}
class EnumDemo3
{
public static void main(String args[])
{
Apple ap;
System.out.println("Winesap costs " + Apple.Winesap.getPrice() + " cents.\n");
System.out.println("All apple prices:");
for(Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() + " cents.");
The first is the instance variable price, which is used to hold the price of each variety of
apple.
The second is the Apple constructor, which is passed the price of an apple.
The third is the method getPrice( ), which returns the value of price.
When the variable ap is declared in main( ), the constructor for Apple is called once
for each constant that is specified. the arguments to the constructor are specified, by
putting them inside parentheses after each constant, as shown here:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
These values are passed to the parameter of Apple(),which then assigns this value to
price. The constructor is called once for each constant.
Because each enumeration constant has its own copy of price, you can obtain the
price of a specified type of apple by calling getPrice().
For example, in main() the price of a Winesap is obtained by the following
call:Apple.Winesap.getPrice()
ordinal( )
compareTo( )
To compare the ordinal value of two constants of the same enumeration by using the
compareTo( ) method. It has this general form:
final int compareTo(enum-type e)
equals()
equals method is overridden method from Object class, it is used to compare the
enumeration constant. Which returns true if both constants are same.
class EnumDemo4
{
public static void main(String args[])
{
Apple ap, ap2, ap3;
System.out.println("Here are all apple constants" + " and their ordinal values: ");
for(Apple a : Apple.values())
System.out.println(a + " " + a.ordinal());
ap = Apple.RedDel;
ap2 = Apple.GoldenDel;
ap3 = Apple.RedDel;
System.out.println();
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
if(ap.compareTo(ap2) < 0)
System.out.println(ap + " comes before " + ap2);
if(ap.compareTo(ap2) > 0)
System.out.println(ap2 + " comes before " + ap);
if(ap.compareTo(ap3) == 0)
System.out.println(ap + " equals " + ap3);
System.out.println();
if(ap.equals(ap2))
System.out.println("Error!");
if(ap.equals(ap3))
System.out.println(ap + " equals " + ap3);
if(ap == ap3)
System.out.println(ap + " == " + ap3);
}
}
Wrappers Classes
Java uses primitive types such as int or double, to hold the basic data types supported
by the language.
The primitive types are not part of the object hierarchy, and they do not inherit
Object.
Despite the performance benefit offered by the primitive types, there are times when
you will need an object representation.
Many of the standard data structures implemented by Java operate on objects,
which means that you can‘t use these data structures to store primitive types.
To handle the above situation, Java provides type wrappers, which are classes
that encapsulate a primitive type within an object.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Character:
Character is a wrapper around a char. The constructor for Character is
Character(char ch)
Here, ch specifies the character that will be wrapped by the Character object
being created.
To obtain the char value contained in a Character object, call charValue( ),
shown here:
char charValue( )
Boolean:
Boolean(boolean boolValue)
Boolean(String boolString)
In the second version, if boolString contains the string ―true‖ (in uppercase or
lowercase), then the new Boolean object will be true. Otherwise, it will be false.
To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:
boolean booleanValue( )
It returns the boolean equivalent of the invoking object.
int i = iOb.intValue();
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
AutoBoxing
Auto-unboxing
Auto- unboxing is the process by which the value of a boxed object is automatically
extracted from a type wrapper when it is assigned to primitive type value is needed.
There is no need to call a method such as
intValue( ). int i = iOb; // auto-unbox
Example Program:
class AutoBoxUnBox
{
public static void main(String args[])
{
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb); // displays 100 100
}
}
class AutoBox2
{
static int m(Integer v)
{
return v ; }
public static void main(String args[])
{
Integer iOb = m(100);
System.out.println(iOb);// 100
}
}
In the program, notice that m( ) specifies an Integer parameter and returns an int
result.
Inside main( ), m( ) is passed the value 100.
Because m( ) is expecting an Integer, this value is automatically boxed.
Then, m( ) returns the int equivalent of its argument. This causes v to be auto-unboxed.
Next, this int value is assigned to iOb in main( ), which causes the int return value
to be autoboxed.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
class AutoBox3
{
public static void main(String args[])
{
Integer iOb, iOb2; int i;
iOb = 100;
System.out.println("Original value of iOb: " + iOb);
++iOb; // auto unbox and rebox
System.out.println("After ++iOb: " + iOb);
iOb2 = iOb + (iOb / 3);
System.out.println("iOb2 after expression: " + iOb2);
i = iOb + (iOb / 3); // auto unbox and rebox
System.out.println("i after expression: " + i);
}
}
++iOb;
This causes the value in iOb to be incremented. It works like this: iOb is unboxed, the
value is incremented, and the result is reboxed.
When the switch expression is evaluated, iOb is unboxed and its int value is obtained.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
class AutoBox5
{
public static void main(String args[])
{
Boolean b = true; // auto boxing boolean
if(b)
System.out.println("b is true");// auto unboxed when used in
conditional expression Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char
System.out.println("ch2 is " + ch2);
}
}
Annotations
Annotations (Metadata) Beginning with JDK 5, a new facility was added to Java that
enables you to embed supplemental information into a source file.
This information, called an annotation, does not change the actions of a program.
Thus, an annotation leaves the semantics of a program unchanged.
However this information can be used by various tools during both development and
deployment.
@interface MyAnno
{
String str();
int val();
}
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
All annotations consist solely of method declarations. However, you don‘t provide
bodies for these methods. Instead, Java implements these methods. Moreover, the
methods act much like fields.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno
{
String str();
int val();
}
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
import java.lang.annotation.*;
import java.lang.reflect.*;
class Meta
{
// Annotate a method.
@MyAnno(str = "Annotation Example", val = 100)
This program uses reflection as described to obtain and display the values of str and val in
the MyAnnoannotation associated with myMeth()in the Metaclass.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
However, to obtain a method that has parameters, you must specify class objects
representing the types of those parameters as arguments to getMethod( ). For example,
here is a slightly different version of the preceding program:
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno { String str(); int val(); }
class Meta
{
// myMeth now has two arguments.
@MyAnno(str = "Two Parameters", val = 19)
public static void myMeth(String str, int i)
{
Meta ob = new Meta();
Try
{
Class c = ob.getClass();
// Here, the parameter types are specified.
Method m = c.getMethod("myMeth", String.class, int.class);
MyAnno anno = m.getAnnotation(MyAnno.class);
System.out.println(anno.str() + " " + anno.val());
}
catch (NoSuchMethodException exc)
{
System.out.println("Method Not Found.");
}
}
Two Parameters 19
To obtain information about this method, getMethod( ) must be called as shown here:
Here, the Class objects representing String and int are passed as additional arguments.
Obtaining All Annotations
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
You can obtain all annotations that have RUNTIME retention that are associated with an
item by calling getAnnotations( ) on that item.
getAnnotations( )
It can be called on objects of type Class, Method, Constructor, and Field. Here is
another reflection example that shows how to obtain all annotations associated with a
class and with a method.
It declares two annotations.It then uses those annotations to annotate a class and a
method.
Example code:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
@MyAnno(str=Meta2, val=99)
@MyAnno(str=Testing, val=100)
The program uses getAnnotations( ) to obtain an array of all annotations associated with
the Meta2 class and with the myMeth( ) method. As explained, getAnnotations( ) returns
an array of Annotation objects.
Recall that Annotation is a super-interface of all annotation interfaces and that it overrides
toString( ) in Object.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
1. getAnnotation( ) --- It can be invoked with method, class. It return the used
annotation.
2. getAnnotations( ) --- It can be invoked with method, class. It return the used
annotations.
You can give annotation members default values that will be used if no value is
specified when the annotation is applied.
@interface MyAnno { String str() default "Testing"; int val() default 9000; }
Example:
Dept. of CS&E,BMSIT&M Page 15 By. Muneshwara M S, Asst. Prof
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
@interface MyAnno { String str() default "Testing"; int val() default 9000;
} class Meta3 {
@MyAnno()
Method m = c.getMethod("myMeth");
MyAnno anno =
m.getAnnotation(MyAnno.class);
System.out.println(anno.str() + " " + anno.val()); }
catch (NoSuchMethodException exc)
{
Output:
Testing 9000
Marker Annotations
import java.lang.annotation.*;
import java.lang.reflect.*;
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker { }
class Marker {
@MyMarker
if(m.isAnnotationPresent(MyMarker.class))
System.out.println("MyMarker is present.");
Output
MyMarker is present.
Built in Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class,
interface, methods or fields to indicate some additional information which can be used
by java compiler and JVM.
• @Override
• @SuppressWarnings
• @Deprecated
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
• @Target
• @Retention
• @Inherited
• @Documented
@Override
@Override annotation assures that the subclass method is overriding the parent class method.
If it is not so, compile time error occurs.Sometimes, we does the silly mistake such as
spelling mistakes etc. So, it is better to mark @Override annotation that provides assurity that
method is overridden.
void eatSomething()
{System.out.println("eating something");}
void eatsomething()
{
System.out.println("eating foods");
}//Compile time error }
@SuppressWarnings
annotation: is used to suppress warnings issued by the compiler.
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
list.add("sonoo");
}}
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It
informs user that it may be removed in the future versions.
class A{
@Deprecated
class TestAnnotation3{
A a=new A();
a.n();
}}
@Inherited
@Inherited
public @interface MyCustomAnnotation {
}
@MyCustomAnnotation
public class
MyParentClass {
...
}
Dept. of CS&E,BMSIT&M Page 22 By. Muneshwara M S, Asst. Prof
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
...
}
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
@Documented
@Documented
@MyCustomAnnotatio
n public class MyClass
{
//Class body
}
@Target
For example: In the below code, we have defined the target type as METHOD which means
the below annotation can only be used on methods.
import
java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
public @interface MyCustomAnnotation {
//Doing something
}
}
If you do not define any Target type that means annotation can be applied to any element.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Mechanisms were added that allow the integration of standard arrays into the
Collections Framework.
Algorithms operate on collections and are defined as static methods within the
Collections class.
Generics
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
parameters Generics add the one feature that collections had been missing: type safety.
Prior to generics, all collections stored Object references, which meant that any collection could
store any type of object. Thus, it was possible to accidentally store in compatible type s in a
collection.
Doing so could result in run-time type mismatch errors. With generics, it is possible to
explicitly state the type of data being stored, and run-time type mismatch errors can be
avoided.
Autoboxing/unboxing
As you will see, a collection can store only references, not primitive values. In the past, if you
wanted to store a primitive value, such as an int, in a collection, you had to manually box it into
its type wrapper.
When the value was retrieved, it needed to be manually unboxed (by using an explicit cast) into
its proper primitive type.
Because of autoboxing/unboxing, Java can automatically perform the proper boxing and
unboxing needed when storing or retrieving primitive types. There is no need to manually
perform these operations.
collection can be cycled through by use of the for-each style for loop.
Earlier it was done with Iteratable interface. For each loop is easier than the earlier iterator.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
• Queue extends Collection to handle special types of lists in which elements are
removed only from the head.
• Set extends Collection to handle sets, which must contain unique elements.
4. Give the syntax of collection interface. Explain the methods present in collection
interface.
interface Collection<E>
Iterating through the list cane be done through the iteratable interface.
Methods in collection interface
add
addAll
clear
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
void clear( )
contains
containsAll
boolean containsAll(Collection<?> c )
equals
hashCode
int hashCode( ) Returns the hash code for the invoking collection.
isEmpty
boolean isEmpty( )
iterator
remove
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
removeAll
boolean removeAll(Collection<?> c )
retainAll
boolean retainAll(Collection<?> c )
size
toArray
Object[ ] toArray( )
If the size of array equals the number of elements, these are returned in
array.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
List interface extends collection interface. It includes new method. Which are
given below.
Inserts obj into the invoking list at the index passed in index.
Any pre existing elements at or beyond the point of insertion are shifted up.
Inserts all elements of C into the invoking list at the index passed in
index . Any pre existing elements at or beyond the point of insertion are shifted up.
Thus, no elements are overwritten. Returns true if the invoking list changes and
returns false otherwise.
E get(int index )
Returns the object stored at the specified index within the invoking collection.
Returns the index of the first instance of obj in the invoking list. If obj is not an
element of the list, –1 is returned.
Returns the index of the last instance of obj in the invoking list. If obj is not an
element of the list, –1 is returned.
ListIterator<E> listIterator( )
Returns an iterator to the invoking list that begins at the specified index.
E remove(int index )
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Removes the element at position index from the invoking list and returns the deleted
element. The resulting list is compacted. That is, the indexes of subsequent elements are
decremented by one.
Assigns obj to the location specified by index within the invoking list.
Returns a list that includes elements from start to end –1 in the invoking list.
Elements in the returned list are also referenced by the invoking object.
It extends Collection and declares the behaviour of a collection that does not allow
duplicate elements.
interface Set<E>
Here, E specifies the type of objects that the set will hold.
The SortedSet interface extends Set and declares the behavior of a set sorted in
ascending order.
SortedSet is a generic interface that has this declaration: interface SortedSet<E> Here, E
specifies the type of objects that the set will hold.
In addition to those methods defined by Set, the SortedSet interface declares the
methods.
E first( )
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Returns a SortedSet containing those elements less than end that are contained in the
invoking sorted set.
Elements in the returned sorted set are also referenced by the invoking sorted set.
E last( )
Returns a SortedSet that includes those elements between start and end– 1. Elements in
the returned collection are also referenced by the invoking object.
Returns a SortedSet that contains those elements greater than or equal to start that are
contained in the sorted set. Elements in the returned set are also referenced by the
invoking object.
The NavigableSet interface extends SortedSet and declares the behavior of a collection
that supports the retrieval of elements based on the closest match to a given value or values.
interface NavigableSet<E>
Here, E specifies the type of objects that the set will hold.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
E ceiling(E obj )
Returns an iterator that moves from the greatest to least. In other words, it returns a
reverse iterator.
NavigableSet<E> descendingSet( )
Returns a NavigableSet that is the reverse of the invoking set. The resulting set is
backed by the invoking set.
E floor(E obj )
Searches the set for the largest element e such that e <= obj . If such an element is
found, it is returned. Otherwise, null is returned.
Returns a NavigableSet that includes all elements from the invoking set that are less
than upperBound . If incl is true, then an element equal to upperBound is included. The
resulting set is backed by the invoking set.
E higher(E obj ) Searches the set for the largest element e such that e > obj . If such an
element is found, it is returned. Otherwise, null is returned.
E lower(E obj )
Searches the set for the largest element e such that e < obj . If such an element is
found, it is returned. Otherwise, null is returned.
E pollFirst( )
Returns the first element, removing the element in the process. Because the set is
sorted, this is the element with the least value. null is returned if the set is empty.
E pollLast( )
Returns the last element, removing the element in the process. Because the set is
sorted, this is the element with the greatest value. null is returned if the set is empty.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Returns a NavigableSet that includes all elements from the invoking set that are
greater than lowerBound and less than upperBound .
Returns a NavigableSet that includes all elements from the invoking set that are
greater than lowerBound . If incl is true, then an element equal to lowerBound is
included. The resulting set is backed by the invoking set
interface Queue<E>
E element( )
Returns the element at the head of the queue. The element is not removed. It
throws NoSuchElementException if the queue is empty.
Attempts to add obj to the queue. Returns true if obj was added and false otherwise.
E peek( )
Returns the element at the head of the queue. It returns null if the queue is empty. The
element is not removed.
E poll( )
Returns the element at the head of the queue, removing the element in the process. It
returns null if the queue is empty.
E remove( )
Removes the element at the head of the queue, returning the element in the process. It
throws NoSuchElementException if the queue is empty.
9. Deque interface
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
interface Deque<E>
Iterator<E> descendingIterator( )
Returns an iterator that moves from the tail to the head of the deque. In other
words, it returns a reverse iterator.
E getFirst( )
Returns the first element in the deque. The object is not removed from the deque. It throws
NoSuchElementException if the deque is empty.
E getLast( )
Attempts to add obj to the head of the deque. Returns true if obj was added and
false otherwise. Therefore, this method returns false when an attempt is made to add
obj to a full, capacity-restricted deque.
Attempts to add obj to the tail of the deque. Returns true if obj was added and
false otherwise.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
E peekFirst( )
Returns the element at the head of the deque. It returns null if the deque is
empty. The object is not removed.
E peekLast( )
Returns the element at the tail of the deque. It returns null if the deque is
empty. The object is not removed.
E pollFirst( )
Returns the element at the head of the deque, removing the element in the process. It
returns null if the deque is empty.
E pollLast( ) Returns the element at the tail of the deque, removing the element in the
process. It returns null if the deque is empty.
E pop( ) Returns the element at the head of the deque, removing it in the process. It
throws NoSuchElementException if the deque is empty.
void push(E obj ) Adds obj to the head of the deque. Throws an IllegalStateException if
a capacity-restricted deque is out of space.
E removeFirst( ) Returns the element at the head of the deque, removing the element in
the process. It throws NoSuchElementException if the deque is empty.
Removes the first occurrence of obj from the deque. Returns true if successful and
false if the deque did not contain obj .
E removeLast( )
Returns the element at the tail of the deque, removing the element in the process. It
throws NoSuchElementException if the deque is empty.
Removes the last occurrence of obj from the deque. Returns true if successful and
false if the deque did not contain
AbstractCollection
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
AbstractList
AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather than
random access of its elements.
AbstractSet
class ArrayList<E>
builds an array list that is initialized with the elements of the collection c.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
ArrayList(int capacity)
builds an array list that has the specified initial capacity. The capacity is the size
of the underlying array that is used to store the elements. The capacity grows
automatically as elements are added to an array list.
class ArrayListDemo {
al.add("F");
al.add(1, "A2");
al.remove(2);
}}
class ArrayListToArray {
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
ia = al.toArray(ia); int
sum = 0;
}
}
LinkedList
The LinkedList class extends AbstractSequentialList and implements the List, Deque, and
Queue interfaces.
class LinkedList<E>
Here, E specifies the type of objects that the list will hold. LinkedList has the two
constructors
LinkedList( )
LinkedList(Collection<? extends E> c)
The first constructor builds an empty linked list.
The second constructor builds a linked list that is initialized with the elements of the
collection c.
Example code:
import java.util.*;
class LinkedListDemo {
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
ll.addFirst("A");
ll.add(1, "A2");
ll.remove(2);
ll.removeLast();
}
}
HashSet
HashSet extends AbstractSet and implements the Set interface. It creates a collection
that uses a hash table for storage.
Java HashSet class is used to create a collection that uses a hash table for storage.
Here, E specifies the type of objects that the set will hold.
Constructor
HashSet( )
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
HashSet(int capacity)
Example: import
java.util.*;
class HashSetDemo {
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
output
[D, A, F, C, B, E]
LinkedHashSet
LinkedHashSet class is a Hash table and Linked list implementation of the set interface.
It inherits HashSet class and implements Set interface.
The LinkedHashSet class extends HashSet and adds no members of its own. It
is a generic class that has this declaration:
class LinkedHashSet<E>
Here, E specifies the type of objects that the set will hold.
LinkedHashSet maintains a linked list of the entries in the set, in the order in which
they were inserted.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
That is, when cycling through a LinkedHashSet using an iterator, the elements will be
returned in the order in which they were inserted.
This is also the order in which they are contained in the string returned by
toString( ) when called on a LinkedHashSet object.
[B, A, D, E, C, F]
excellent choice when storing large amounts of sorted information that must be found
quickly.
Here, E specifies the type of objects that the set will hold.
TreeSet has the following constructors:
TreeSet( )
TreeSet(Collection<? extends E> c)
TreeSet(Comparator<? super E> comp)
TreeSet(SortedSet<E> ss)
Example
ts.add("E");
ts.add("F");
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
ts.add("D");
System.out.println(ts);
}
}
PriorityQueue
PriorityQueue(int capacity)
ArrayDeque
class ArrayDeque<E>
Example:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
import java.util.*;
class ArrayDequeDemo {
adq.push("F"); System.out.print("Popping
the stack: "); while(adq.peek() != null)
System.out.print(adq.pop() + " ");
System.out.println();
}
}
Before you can access a collection through an iterator, you must obtain one. Each of the
collection classes provides an iterator( ) method that returns an iterator to the start of the
collection.
By using this iterator object, you can access each element in the collection. Element at a
time. In general, to use an iterator to cycle through the contents of a collection, follow these
steps:
1. Obtain an iterator to the start of the collection by calling the collection‘s iterator( )
method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( )
returns true.
4. For collections that implement List, you can also obtain an iterator by calling
listIterator( ).
5.As explained, a list iterator gives you the ability to access the collection in either the
forward or backward direction and lets you modify an element.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
}
System.out.println();
}
System.out.println();
}
}
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Output:
class ForEachDemo {
}
}
Output:
The power of collections is that they can store any type of object, including objects of
classes that you create.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
return name + "\n" + street + "\n" + city + " " + state + " " +
code;
}}
class MailList {
Mahomet IL 61853
Tom Carlton
By checking for the RandomAccess interface, client code can determine at run time whether a
collection is suitable for certain types of random access operations—especially as they apply to
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
large collections.
RandomAccess is implemented by ArrayList and by the legacy Vector class, among others.
A map is an object that stores associations between keys and values, or key/value pairs.
Keys and values are objects. Keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, others cannot.
There is one key point about maps that is important to mention at the outset: they don‘t
implement the Iterable interface. This means that you cannot cycle through a map using a
for-each style for loop. Furthermore, you can‘t obtain an iterator to a map.
However, as you will soon see, you can obtain a collection-view of a map, which does allow the
use of either the for loop or an iterator.
Because the map interfaces define the character and nature of maps, this discussion of maps
begins with them.
The Map interface maps unique keys to values. A key is an object that you use to retrieve a
value at a later date. Given a key and a value, you can store the value in a Map object. After the
value is stored, you can retrieve it by using its key.
Several methods
A NullPointerException is thrown if an attempt is made to use a null object and null is not
allowed in the map.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
An IllegalArgumentException is thrown if an
invalid argument is used.
Maps revolve around two basic operations: get( ) and put( ). To put a value into a map,
use put( ), specifying the key and the value.
maps are not, themselves, collections because they do not implement the Collection
interface. However, you can obtain a collection-view of a map. To do this, you can use the
entrySet( ) method. It returns a Set that contains the elements in the map.
Collection-views are the means by which maps are integrated into the larger Collections
Framework.
SortedMap
The SortedMap interface extends Map. It ensures that the entries are maintained in
ascending
Several methods throw a NoSuchElementException when no items are in the invoking map. A
ClassCastException is thrown when an object is incompatible with the elements in a map. A
NullPointerException is thrown if an attempt is made to use a null object when null is not
allowed in the map.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
NavigableMap Interface
It extends SortedMap and declares the behavior of a map that supports the retrieval of
entries based on the closest match to a given key or keys. NavigableMap is a generic
interface that has this declaration:
interface NavigableMap<K,V>
Here, K specifies the type of the keys, and V specifies the type of the values associated with the
keys.
Several methods throw a ClassCastException when an object is incompatible with the keys in
the map.
A NullPointerException is thrown if an attempt is made to use a null object and null keys are
not allowed in the set.
Map.Entry Interface
The Map.Entry interface enables you to work with a map entry. Recall that the entrySet( )
method declared by the Map interface returns a Set containing the map entries.
Each of these set elements is a Map.Entry object. Map.Entry is generic and is declared like
this:
interface Map.Entry<K, V> Here, K specifies the type of keys, and V specifies the type of
values.
Map Classes
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Several classes provide implementations of the map interfaces. The classes that can be used for
maps are summarized here:
HashMap:
The HashMap class extends AbstractMap and implements the Map interface. It uses a hash
table to store the map.
This allows the execution time of get( ) and put( ) to remain constant even
for large sets. HashMap is a generic class that has this declaration:
The first form constructs a default hash map. The second form initializes the hash map by using
the elements of m. The third form initializes the capacity of the hash map to capacity. The fourth
form initializes both the capacity and fill ratio of the hash map by using its arguments.
The meaning of capacity and fill ratio is the same as for HashSet, described earlier. The
default capacity is 16.
HashMap implements Map and extends AbstractMap. It does not add any methods of its
own.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
}
System.out.println();
}
}
Output from this program is shown here (the precise order may vary):
Ralph Smith: -19.08
that are defined by Map.Entry. Pay close attention to how the deposit is made into John
Doe‘s
account. The put( ) method automatically replaces any preexisting value that is associated
with the specified key with the new value. Thus, after John Doe‘s account is updated, the
hash map will still contain just one ―John Doe‖ account.
TreeMap
The TreeMap class extends AbstractMap and implements the NavigableMap interface. It
creates maps stored in a tree structure.
A TreeMap provides an efficient means of storing key/value pairs in sorted order and allows
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its elements
will be sorted in ascending key order.
Here, K specifies the type of keys, and V specifies the type of values.
The first form constructs an empty tree map that will be sorted by using the natural order of its
keys. The second form constructs an empty tree-based map that will be sorted by using the
Comparator comp. (Comparators are discussed later in this chapter.) The third form initializes
a tree map with the entries from m, which will be sorted by using the natural order of the keys.
The fourth form initializes a tree map with the entries from sm, which will be sorted in the same
order as sm.
TreeMap has no methods beyond those specified by the NavigableMap interface and the
AbstractMap class.
The following program reworks the preceding example so that it uses TreeMap:
import java.util.*;
class TreeMapDemo {
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
}
System.out.println();
}
}
You can alter this behavior by specifying a comparator when the map is
created, as described shortly.
LinkedHashMap
1order in which they were inserted. This allows insertion-order iteration over the map. That is,
when iterating through a collection-view of a LinkedHashMap, the elements will be returned in
the order in which they were inserted.
LinkedHashMap that returns its elements in the order in which they were last accessed.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Here, K specifies the type of keys, and V specifies the type of values.
LinkedHashMap( )
LinkedHashMap(Map<? extends K, ? extends V> m)
LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio)
LinkedHashMap(int capacity, float fillRatio, boolean Order)
The first form constructs a default LinkedHashMap.
The second form initializes the LinkedHashMap with the elements from m. The third form
initializes the capacity. The fourth form initializes both capacity and fill ratio. The meaning of
capacity and fill ratio are the same as for HashMap. The default capactiy is 16. The default
ratio is 0.75. The last form allows you to specify whether the elements will be stored in the
linked list by insertion order, or by order of last access.
IdentityHashMap
It is similar to HashMap except that it uses reference equality when comparing elements.
IdentityHashMap is a generic class that has this declaration:
Here, K specifies the type of key, and V specifies the type of value. The API documentation
explicitly states that IdentityHashMap is not for general use.
EnumMap extends AbstractMap and implements Map. It is specifically for use with keys of
an enum type. It is a generic class that has this declaration:
Here, K specifies the type of key, and V specifies the type of value. Notice that K must extend
Enum<K>, which enforces the requirement that the keys must be of an enum type.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
EnumMap(Class<K> kType)
EnumMap(Map<K, ? extends V> m)
EnumMap(EnumMap<K, ? extends V> em)
The first constructor creates an empty EnumMap of type kType. The second creates an
EnumMap map that contains the same entries as m. The third creates an EnumMap
initialized with the values in em.
Comparator interface
The Comparator interface defines two methods: compare( ) and equals( ). The compare( )
method, shown here, compares two elements for order:
It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.
ClassCastException if the types of the objects are not compatible for comparison.
By overriding compare( ), you can alter the way that objects are ordered.
For example, to sort in reverse order, you can create a comparator that reverses the outcome of
a comparison. The equals( ) method, shown here, tests whether an object equals the invoking
comparator:
Here, obj is the object to be tested for equality. The method returns true if obj and the
invoking object are both Comparator objects and use the same ordering. Otherwise, it
returns false.
import java.util.*;
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
bStr = b;
return bStr.compareTo(aStr);
}
}
class CompDemo {
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D"); for(String
element : ts)
}}
Output:
FEDCBA
algorithms are defined as static methods within the Collections class. static
<T> Boolean addAll(Collection <? super T> c, T ... elements)
collection specified by c. Returns true if the elements were added and false otherwise.
static <T>int binarySearch(List<? extends T> list, T value, Comparator<? super T> c)
Searches for value in list ordered according to c. Returns the position of value
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
static <T> int binarySearch(List<? extends Comparable<? super T>> list,T value)
Searches for value in list. The list must be sorted. Returns the position of value in
list, or a negative value if value is not found.
static <K, V> Map<K, V> checkedMap(Map<K, V> c, Class<K> keyT, Class<V>
valueT)
import java.util.*;
class AlgorithmsDemo {
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
ll.add(-8);
ll.add(20);
ll.add(-20);
ll.add(8);
Comparator<Integer> r = Collections.reverseOrder();
Collections.sort(ll, r);
Output:
Notice that min( ) and max( ) operate on the list after it has been shuffled. Neither requires a
sorted list for its operation.
As mentioned at the start of this chapter, the entire Collections Framework was refitted for
generics when JDK 5 was released.
Furthermore, the Collections Framework is arguably the single most important use of
generics in the Java API.
The reason for this is that generics add type safety to the Collections Framework. Before
moving on, it is worth taking some time to examine in detail the significance of this
improvement.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
import java.util.*;
class OldStyle {
list.add("two");
list.add("three");
list.add("four");
}
}
}
Prior to generics, all collections stored references of type Object.
The preceding program uses this feature to store references to objects of type String in list, but
any type of reference could have been stored. Unfortunately, the fact that a pre-generics
collection stored Object references could easily lead to errors.
First, it required that you, rather than the compiler, ensure that only objects of
the proper type be stored in a specific collection. For example, in the preceding example, list is
clearly intended to store Strings, but there is nothing that actually prevents another type of
reference from being added to the collection
For example, the compiler will find nothing wrong with this line of code:
list.add(new Integer(100));
Because list stores Object references, it can store a reference to Integer as well as it can
store a reference to String.
However, if you intended list to hold only strings, then the preceding statement would corrupt
the collection. Again, the compiler had no way to know that the preceding statement is invalid.
The second problem with pre-generics collections is that when you retrieve a reference
from the collection, you must manually cast that reference into the proper type.
This is why the preceding program casts the reference returned by next( ) into String. Prior to
generics, collections simply stored Object references. Thus, the cast was necessary when
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
retrieving
Aside from the inconvenience of always having to cast a retrieved reference into its proper type,
this lack of type safety often led to a rather serious, but surprisingly easy-to-create, error.
Because Object can be cast into any type of object, it was possible to cast a reference obtained
from a collection into the wrong type. For example, if the following statement were added to the
preceding example, it would still compile without error, but generate a run-time exception when
executed:
• Ensures that only references to objects of the proper type can actually be stored in a
collection. Thus, a collection will always contain references of a known type.
• Eliminates the need to cast a reference retrieved from a collection. Instead, a reference
retrieved from a collection is automatically cast into the proper type. This prevents run-
time errors due to invalid casts and avoids an entire category of errors.
As explained at the start of this chapter, early versions of java.util did not include the
Collections Framework. Instead, it defined several classes and an interface that provided an ad
hoc method of storing objects.
When collections were added (by J2SE 1.2), several of the original classes were reengineered to
support the collection interfaces.
Thus, they are fully compatible with the framework. While no classes have actually been
deprecated, one has been rendered obsolete.
Of course, where a collection duplicates the functionality of a legacy class,you will usually
want to use the collection for new code. In general, the legacy classes are supported because
there is still code that uses them.
One other point: none of the collection classes are synchronized, but all the legacy classes
are synchronized.
This distinction may be important in some situations. Of course, you can
easily synchronize collections, too, by using one of the algorithms provided by Collections.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Stack
Vector
There is one legacy interface called Enumeration.
The following sections examine Enumeration and each of the legacy classes, in turn. The
Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one at a
time) the elements in a collection of objects. This legacy interface has been superseded by
Iterator.
interface Enumeration<E>
where E specifies the type of element being enumerated.
Vector
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized, and it contains many legacy methods that are not part of the
Collections.
• The first form creates a default vector, which has an initial size of 10.
• The second form creates a vector whose initial capacity is specified by size.
• The third form creates a vector whose initial capacity is specified by size and whose
increment is specified by incr.
The increment specifies the number of elements to allocate each time that a vector is resized
upward.
The fourth form creates a vector that contains the elements of collection c.
Stack
Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only
defines the default constructor, which creates an empty stack. With the release of JDK 5, Stack
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
class Stack<E>
Here, E specifies the type of element stored in the stack.
Stack includes all the methods defined by Vector.
Dictionary
Dictionary is an abstract class that represents a key/value storage repository and operates
much like Map.
Given a key and value, you can store the value in a Dictionary object. Once
the value is stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be
thought of as a list of key/value pairs.
classified as obsolete, because it is fully superseded by Map. However, Dictionary is still in use
and thus is fully discussed here.
Here, K specifies the type of keys, and V specifies the type of values. The abstract methods
defined by Dictionary are listed in Table 17-17.
Hashtable
HashMap, Hashtable stores key/value pairs in a hash table. However, neither keys
nor values can be null. When using a Hashtable, you specify an object that is used as a key, and
the value that you want linked to that key. The key is then hashed, and the resulting hash code is
used as the index at which the value is stored within the table.
Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map<? extends K, ? extends V> m)
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
The third version creates a hash table that has an initial size specified by size and a fill ratio
specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full the
hash table can be before it is resized upward. Specifically, when the number of elements is
greater than the capacity of the hashtable multiplied by its fill ratio, the hash table is expanded.
If you do not specify a fill ratio,
Finally, the fourth version creates a hash table that is initialized with the
elements in m. The capacity of the hash table is set to twice the number of elements in m. The
default load factor of 0.75 is used.
Properties
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a
String and the value is also a String.
The Properties class is used by many other Java classes. For example, it is the type of object
returned by System.getProperties( ) when obtaining environmental values.
Although the Properties class, itself, is not generic, several of its methods are.
Properties defines the following instance variable:
Properties defaults;
This variable holds a default property list associated with a Properties object. Properties
defines these constructors:
Properties( )
Properties(Properties propDefault)
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Module 3
The String Constructors, String Length, Special String Operations, String Literals, String
Concatenation, String Concatenation with Other Data Types, String Conversion and toString( )
Character Extraction, charAt( ), getChars( ), getBytes( ) toCharArray(), String Comparison,
equals( ) and equalsIgnoreCase( ), regionMatches( ) startsWith( ) and endsWith( ), equals( )
Versus == , compareTo( ) Searching Strings, Modifying a String, substring( ), concat( ), replace(
), trim( ), Data Conversion Using valueOf( ), Changing the Case of Characters Within a String,
Additional String Methods, StringBuffer , StringBuffer Constructors, length( ) and capacity( ),
ensureCapacity( ), setLength( ), charAt( ) and setCharAt( ), getChars( ),append( ), insert( ),
reverse( ), delete( ) and deleteCharAt( ), replace( ), substring( ), Additional StringBuffer
Methods, StringBuilder.
String(char chars[ ])
Here, startIndex specifies the index at which the subrange begins, and
numChars specifies the number of characters to use. Here is an example:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
String(String strObj)
class MakeString
Java
Even though Java‘s char type uses 16 bits to represent the basic Unicode
character set, the typical format for strings on the Internet uses arrays of 8-bit bytes
constructed from the ASCII character set.
Because 8-bit ASCII strings are common, the String class provides
constructors that initialize a string when given a byte array.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
CDE
Note:
String concatenation can be done using + operator. With other data type also.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
String Length
• Syntax:
int length( )
\{ Example
toString()
// For most important classes that you create, will want to override toString()
and provide your own string representations.
String toString( )
// By overriding toString() for classes that you create, you allow them to be
fully integrated into Java‘s programming environment. For example, they
can be used in print() and println() statements and in concatenation
expressions.
class Box
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
{ return "Dimensions are " + width + " by " + depth + " by " + height + "."; }
class toStringDemo {
System.out.println(s);
Character Extraction
The String class provides a number of ways in which characters can be extracted
from a String object. String object can not be indexed as if they were a character
array, many of the String methods employ an index (or offset) into the string for
their operation. Like arrays, the string indexes begin at zero.
A. charAt( )
1. description:
2. Syntax
Here, where is the index of the character that you want to obtain.
charAt( ) returns the character at the specified location.
3. example,
char ch;
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
ch = "abc".charAt(1); assigns
the value ―b‖ to ch.
B. getChars( )
5. to extract more than one character at a time, you can use the getChars()
method.
6. Syntax
\} class getCharsDemo {
C. getBytes( )
Syntax:
byte[ ] getBytes( )
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
2. getBytes( ) is most useful when you are exporting a String value into an
environment that does not support 16-bit Unicode characters. For example,
most Internet protocols and text file formats use 8-bit ASCII for all text
interchange.
D. toCharArray( )
If you want to convert all the characters in a String object into a character
array, the easiest way is to call toCharArray( ).
2. String Comparison:
equals( )
Here, str is the String object being compared with the invoking String object. It
returns true if the strings contain the same characters in the same order, and false
otherwise. The comparison is case-sensitive.
A. equalsIgnoreCase( )
Here, str is the String object being compared with the invoking String object. It,
too, returns true if the strings contain the same characters in the same order, and
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
false otherwise.
B. regionMatches( )
2. Syntax:
The String being compared is specified by str2. The index at which the
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
comparison will start within str2 is specified by str2 StartIndex. The length of the
substring being compared is passed in numChars.
3. Syntax
For example,
"Foobar".endsWith("bar")
"Foobar".startsWith("Foo") are
both true.
Here, startIndex specifies the index into the invoking string at which point the
search will begin. For example,
"Foobar".startsWith("bar", 3)
returns true.
D. equals( ) Versus ==
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
The == operator compares two object references to see whether they refer to the
same instance.
class EqualsNotEqualTo {
E. compareTo( )
1. Sorting applications, you need to know which is less than, equal to, or
greater than the next.
Here, str is the String being compared with the invoking String. The
result of the comparison is returned and is interpreted,
{ static String arr[] = { "Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country" };
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
{ String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
} System.out.println(arr[j]);
Now aid all come country for good is men of the the their time to to
5. Searching String
–1 on failure.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
7. int indexOf(String str, int startIndex) int lastIndexOf(String str, int startIndex) Here,
startIndex specifies the index at which point the search begins.
8. For indexOf( ), the search runs from startIndex to the end of the string. For lastIndexOf(
), the search runs from startIndex to zero. The following example shows how to use the
various index methods to search inside of Strings:
{ String s = "Now is the time for all good men " + "to come to the aid of
their country.";
System.out.println(s); System.out.println("indexOf(t) =
" + s.indexOf('t'));
Output
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
6. Modifying a String
String objects are immutable, whenever you want to modify a String, you
must either copy it into a StringBuffer or StringBuilder, or use one of the
following String methods, which will construct a new copy of the string
with your modifications complete.
1. You can extract a substring using substring( ). It has two forms. The
first is String substring(int startIndex)
2. Here, 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.
Here, startIndex specifies the beginning index, and endIndex specifies the
stopping point.
4. The string returned contains all the characters from the beginning index,
up to, but not including, the ending index. The following program uses
substring( ) to replace all instances of one substring with another within a
string:
// Substring replacement.
class StringReplace {
do {
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
System.out.println(org); i =
org.indexOf(search);
} } while(i != -1);
2. This method creates a new object that contains the invoking string
with the contents of str appended to the end.
4. String s1 = "one";
C. replace( )
Syntax:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Example
D. trim( )
The trim() method returns a copy of the invoking string from which any
leading and trailing whitespace has been removed.
Syntax: String
trim( ) Example:
String s = " Hello World ".trim();
The trim( ) method is quite useful when you process user commands.
class UseTrim
String str;
do { str = br.readLine();
str = str.trim();
if(str.equals("Illinois"))
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
if(str.equals("California"))
System.out.println("Capital is Sacramento."); else
if(str.equals("Washington"))
System.out.println("Capital is Olympia."); // ... }
while(!str.equals("stop"));
5. Data Conversion
1. The valueOf( ) method converts data from its internal format into a
human-readable form.
Syntax:
5. Any object that you pass to valueOf( ) will return the result of a
call to the object‘s toString( ) method.
Syntax:
7. Here, chars is the array that holds the characters, startIndex is the
index into the array of characters at which the desired substring
begins, and numChars specifies the length of the substring.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Syntax
String toLowerCase( )
B. toUpperCase()
Syntax
String toUpperCase( )
class ChangeCase {
Output:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
StringBuffer
StringBuffer is a peer class of String that provides much of the functionality of strings. As you
know, String represents fixed-length, immutable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended to the end.
StringBuffer 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
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
a. The default constructor (the one with no parameters) reserves room for 16 characters
without reallocation.
b. The second version accepts an integer argument that explicitly sets the size of the
buffer.
c. The third version accepts a String argument that sets the initial contents of the
StringBuffer object and reserves room for 16 more characters without reallocation.
a. The current length of a StringBuffer can be found via the length( ) method, while the
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
capacity( )
b. Example:
class StringBufferDemo
}}
Output
buffer = Hello
length = 5
capacity = 21
B. ensureCapacity( )
a. If you want to pre allocate room for a certain number of characters after a StringBuffer
has been constructed, you can use ensureCapacity( ) to set the size of the buffer.
b. This is useful if you know in advance that you will be appending a large number of
small strings to a StringBuffer.
Syntax
C. setLength( )
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Syntax:
Here, len specifies the length of the buffer. This value must be nonnegative.
When you increase the size of the buffer, null characters are added to the end of the existing
buffer.
If you call setLength( ) with a value less than the current value returned by length(), then the
characters stored beyond the new length will be lost.
a. The value of a single character can be obtained from a StringBuffer via the
charAt()method. You can set the value of a character within a StringBuffer using
setCharAt( ).
b. Syntax
c. For charAt( ), where specifies the index of the character being obtained.
d. For setCharAt( ), where specifies the index of the character being set, and ch specifies the
new value of that character.
class setCharAtDemo {
sb.setCharAt(1, 'i');
sb.setLength(2);
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Output
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
E. getChars( )
Syntax
Syntax
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd
specifies an index that is one past the end of the desired substring.
b. This means that the substring contains the characters from sourceStart through
sourceEnd–1.
The index within target which the substring will be copied is passed in targetStart.
d. Care must be taken to assure that the target array is large enough to hold the number of
characters in the specified substring.
F. append( )
1. The append() method concatenates the string representation of any other type of data to
the end of the invoking StringBuffer object. It has several overloaded versions. Here are a
few of its forms:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
class appendDemo {
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
Output
a = 42!
G. insert( )
2. It is overloaded to accept values of all the simple types, plus Strings, Objects, and
CharSequences.
3. Like append(),it calls String.valueOf() to obtain the string representation of the value it is
called with.
Here, index specifies the index at which point the string will be inserted into the
invoking StringBuffer object.
6. The following sample program inserts ―like‖ between ―I‖ and ―Java‖:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
7. Output
I like Java!
H. reverse( )
You can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
This method returns the reversed object on which it was called. The
following program demonstrates reverse( )
class ReverseDemo {
s.reverse();
System.out.println(s);
Output abcdef
fedcba
I. delete( ) and deleteCharAt( )
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
You can delete characters within a StringBuffer by using the methods delete( ) and
deleteCharAt( ).
Syntax:
The delete( ) method deletes a sequence of characters from the invoking object.
Here, startIndex specifies the index of the first character to remove, and endIndex specifies an
index one past the last character to remove.
Thus, the substring deleted runs from startIndex to endIndex–1. The resulting StringBuffer
object is returned.
The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the
resulting StringBuffer object.
sb.delete(4, 7);
sb.deleteCharAt(0);
Output
J. replace( )
a. You can replace one set of characters with another set inside a StringBuffer object by
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
calling replace( ).
b. Syntax
The substring being replaced is specified by the indexes startIndex and endIndex.
}
}
K. substring( )
2. The first form returns the substring that starts at startIndex and runs to the end of the
invoking StringBuffer object.
3.The second form returns the substring that starts at startIndex and runs through endIndex–1.
These methods work just like those defined for String that were described earlier.
Difference between StringBuffer and StringBuilder.
1. J2SE 5 adds a new string class to Java‘s already powerful string handling capabilities.
This new class is called StringBuilder.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
1. int codePointAt(int i )
2. int codePointBefore(int i )
Returns the Unicode code point at the location that precedes that specified by i.
Returns the number of code points in the portion of the invoking String that are
between start and end– 1.
Returns true if the invoking object contains the string specified by str . Returns false,
otherwise.
Returns true if the invoking string contains the same string as str. Otherwise, returns
false.
Returns true if the invoking string contains the same string as str. Otherwise, returns
false.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Returns true if the invoking string matches the regular expression passed in regExp.
Otherwise, returns false.
Returns the index with the invoking string that is num code points beyond the starting
index specified by start.
Returns a string in which the first substring that matches the regular expression
specified by regExp is replaced by newStr.
Returns a string in which all substrings that match the regular expression specified by
regExp are replaced by newStr
Decomposes the invoking string into parts and returns an array that contains the
result. Each part is delimited by the regular expression passed in regExp.
Decomposes the invoking string into parts and returns an array that contains the
result. Each part is delimited by the regular expression passed in regExp. The number of
pieces is specified by max. If max is negative, then the invoking string is fully
decomposed. Otherwise, if max contains a nonzero value, the last entry in the returned
array contains the remainder of the invoking string. If max is zero, the invoking string is
fully decomposed.
StringBuffer appendCodePoint(int ch )
Appends a Unicode code point to the end of the invoking object. A reference to the
object is returned.
int codePointAt(int i )
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Returns the Unicode code point at the location that precedes that specified by i.
int codePointCount(int start , int end )
Returns the number of code points in the portion of the invoking String that are
between start and end– 1.
Searches the invoking StringBuffer for the first occurrence of str. Returns the index of
the match, or –1 if no match is found.
Searches the invoking StringBuffer for the first occurrence of str, beginning at
startIndex. Returns the index of the match, or –1 if no match is found.
Searches the invoking StringBuffer for the last occurrence of str. Returns the index of the
match, or –1 if no match is found.
Searches the invoking StringBuffer for the last occurrence of str, beginning at
startIndex. Returns the index of the match, or –1 if no match is found.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Module- 4 Servlet
Introdution to servlet
Servlet is small program that execute on the server side of a web connection. Just as
applet extend the functionality of web browser the applet extend the functionality of web server.
In order to understand the advantages of servlet, you must have basic understanding of
how web browser communicates with the web server.
Consider a request for static page. A user enters a URL into browser. The browser generates http
request to a specific file. The file is returned by http response. Web server map this particular
request for this purpose. The http header in the response indicates the content. Source of web
page as MIME type of text/html.
Java servlet is more efficient, easier to use, more powerful, more portable, and cheaper than
traditional CGI and than many alternative CGI-like technologies. (More importantly, servlet
developers get paid more than Perl programmers :-).
• Efficient. With traditional CGI, a new process is started for each HTTP request. If the
CGI program does a relatively fast operation, the overhead of starting the process can
dominate the execution time. With servlets, the Java Virtual Machine stays up, and each
request is handled by a lightweight Java thread, not a heavyweight operating system
process. Similarly, in traditional CGI, if there are N simultaneous request to the same
CGI program, then the code for the CGI program is loaded into memory N times. With
servlets, however, there are N threads but only a single copy of the servlet class.
• Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience
of being able to use a familiar language, servlets have an extensive infrastructure for
automatically parsing and decoding HTML form data, reading and setting HTTP headers,
handling cookies, tracking sessions, and many other such utilities.
Powerful. Java servlets let you easily do several things that are difficult or impossible with
regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs
can't). This simplifies operations that need to look up images and other data stored in standard
places. Servlets can also share data among each other, making useful things like database
connection pools easy to implement. They can also maintain
information from request to request, simplifying things like session tracking and caching
of previous computations.
\} Portable. Servlets are written in Java and follow a well-standardized API. Consequently,
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
servlets written for, say I-Planet Enterprise Server can run virtually unchanged on
Apache, Microsoft IIS, or Web Star. Servlets are supported directly or via a plug in on
almost every major Web server.
\} Inexpensive. There are a number of free or very inexpensive Web servers available that
are good for "personal" use or low-volume Web sites. However, with the major exception
of Apache, which is free, most commercial-quality Web servers are relatively expensive.
Nevertheless, once you have a Web server, no matter the cost of that server, adding
servlet support to it (if it doesn't come preconfigured to support servlets) is generally free
or cheap.
2. What is servlet? What are the phases of servlet life cycle? Give an example.
Servlets are small programs that execute on the server side of a web connection. Just as
applet extend the functionality of web browser the applet extend the functionality of web server.
It class the init method when it loads the instance. It is used to intialise servlet.
Web container calls service method each time when request for the servlet is
received. If servlet is not initialized it calls init then it calls the service method. Syntax of
service method is as follows
• public void service(Servlet request, ServletResponse response) throws
ServletException, IOException
•
• Destroy method is invoked.
•
• The web container calls the destroy method before it removes the servlet from
service. It gives servlet an opportunity to clean up memory, resources etc. Servlet
destroy method has following syntax.
•
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Ready
There are three states of servlet new, ready, end. It is in new state when servlet is created.
The servlet instance is created when it is in new state. After invoking the init () method
servlet comes to ready state. In ready state servlet invokes destroy method it comes to end
state.
Deployment descriptor is a file located in the WEB-INF directory that controls the behavior
of a java servlet and java server pages. The file is called the web.xml file and contains the
header, DOCTYPE, and web app element. The web app element should contain a servlet
element with three elements. These are servlet name, servlet class, and init-param.
The servlet name elements contain the name used to access the java servlet. The servlet
class is the name of the java servlet class. init-param is the name of an initialization
parameter that is used when request is made to the java servlet.
Example file:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Application2.2//EN‖> ..doctype
<web-app>
<servlet> <servlet-
name>MyJavaservlet</servlet-name>
<servlet-class>myPackage.MyJavaservletClass</servlet-class>
<init-param><param-name>parameter1</param-name>
<param-value>735</param-value>
</init-param>
</servlet>
</web-app>
Example code
Html code that calls a servlet:
<FORM ACTION=‖/servlet/myservlets.js2‖>
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
</FORM>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class js2 extends Httpservlet {
//String email;
//Email=request.getParameter(―email‖);
Respose.setContentType(―text/html‖);
PrinterWriter pw=response.getWriter();
pw.println(―<HTML>\n‖ +
―</BODY>\n‖ +
</HTML>‖);
}
}
5. How to read HTTP Request Headers?
A request from client contains two components these are implicit data,
such as email address explicit data at HTTP request header. Servlet can read these
request headers to process the data component of the request.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Referrer: Contains the URL of the web page that is currently displayed in
the browser.
A java servlet can read an HTTP request header by calling the getHeader()
method of the HttpservletRequest object. getHeader() requires one argument
which is the name of the http request header.
getHeader()
6. How to send data to client and writing the HTTP Response Header?
A java servlet responds to a client‘s request by reading client data and HTTP
request headers, and then processing information based on the nature of the request.
There are two ways in which java servlet replies to client request. These are
sent by sending information to the response stream and sending information in http
response header. The http response header is similar to the http request header.
Explicit data are sent by creating an instance of the PrintWriter object and then
using println() method to transmit the information to the client.
My Response
Java servlet can write to the HTTP response header by calling setStatus() method
requires one argument which is an integer that represent the status code.
Response.setStatus(100);
Cookies are text files stored on the client computer and they are kept for various
information tracking purpose. Java Servlets transparently supports HTTP cookies.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
• Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
• When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie
value, both of which are strings.
cookie.setMaxAge(60*60*24);
(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to
add cookies in the HTTP response header as follows:
response.addCookie(cookie);
Writing Cookie
import java.io.*;
import
javax.servlet.*;
import javax.servlet.http.*;
HttpServletResponse response)
throws ServletException, IOException
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
out.println( "<html>\n" +
―<nody>\n‖ +
}
Reading Cookies with Servlet:
Cookie cookie;
Cookie[] cookies;
cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Cookies Example";
out.println( "<html>\n" +
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
cookie = cookies[i];
}
}else{ out.println( "<h2>No cookies founds</h2>");
} out.println("</body>"); out.println("</html>");
}}
1. A session is created each time a client requests service from a java servlet. The
java. The java servlet processes the request and response accordingly, after which
the session is terminated. Many times the same client follows with another request
to the same client follows with another request to the same java servlet, java
servlet requires information regarding the previous session to process request.
2. However , HTTP is stateless protocol, meaning that there is not hold over from
the previous sessions.
Syntax :
HttpSession s1=request.getSession(true);
JSP program
A jsp is java server page is server side program that is similar in design and functionality
to a java servlet.
A JSP is called by a client to provide web services, the nature of which depends on client
application.
A jsp is simpler to create than a java servlet because a jsp is written in HTML rather than
with the java programming language. . There are three methods that are automatically called
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
when jsp is requested and when jsp terminates normally. These are the jspInit() method , the
jspDestroy()m ethod and service() method.
A jspInit() is identical ti init() method of java servlet. It is called when first time jsp is
called.
A jspDestroy() is identical to destroy() method of servlet. The destroy() method is
automatically called when jsp erminates normally.It is not called when jsp terminates abruptly. It
is used for placing clean up codes.
A jsp tag consists of a combination of HTML tags and JSP tags. JSP tags define
java code that is to be executed before the output of jsp program is sent to the browser.
A jsp tag begin with a <%, which is followed by java code , and wnds with %>,
A jsp tags are embedded into the HTML component of a jsp program and are
processed by Jsp virtual engine such as Tomcat.
Java code associated with jsp tag are executed and sent to browser.
Comment tag :A comment tag opens with <%-- and close with --%> and is follwed by a
comment that usually describes the functionality of statements that follow a comment tag.
Declaration statement tags: A declartion statement tag opens with <%! And is followed
by declaration statements that define the variables, object, and methods that are avilabe to other
component of jsp program.
Directive tags: A directive tag opens with <%@ and commands the jsp virtual engine to
perform a specific task, such as importing java package required by objects and methods used in
a declaration statement. The directive tag closes with %> . There are commonly used in
directives import, include , and taglib. The import tag is used to import java packages into the jsp
program. Include is used for importing file. Taglib is used for including file.
Example:
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Expression tags: An expression tag opens with <%= and is used for an expression
statement whose result page replaces the expression tag when the jsp virtual engine resolves JSP
tags. An expression tag closes with %>
Scriptlet tag: A sciptlet tag opens with <% and contains commonly used java control
statements and loops. And Scriptlet tag closes with %>
You can declare java variables and objects that are used in a JSP program
by using the same codin technique used to declare them in java. JSP declaration
statements must appear as jsp tag
Ex:
<html>
<head>
<.head>
<body>
</body>
</html>
Methods are defined same way as it is defined in jsp program, except these
are placed in JSP tag.methods are declared in JSP decalration tag. The jsp calls
method in side the expression tag.
Example:
<html>
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
<head>
<title> Jsp
programming</title> </head>
<body>
int c;
c=a+b;
return c;
}
%>
One of the most powerful features avilable in JSP is the ability to change the
flow of the program to truly create dynamic content for a web based on
conditions received from the browser.
Ther are two control statements used to change the flow of program are ―if ―
and ―switch‖ statement , both of which are also used to direct the flow of a
java program.
Ex:
<html>
<head>
<body>
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
</body>
</html>
Jsp loops are nearly identical to loops that you use in your java program
except you can repeat the html tags
There are three kind of jsp loop that are commonly used in jsp program.
Ex: for loop , while loop , do while .
<body>
<%
%>
</html>
A browser generate requst string whenever the submit button is selected. The
user requests the string consists of URL and the query the string.
Your jsp programneeds to parse the query string to extract the values of fields
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
that are to be processed by your program. You can parse the query string by
using the methods of the request object.
6. Other than requset string url has protocols, port no, the host name
7. Write the JSP program to create and read cookie called “EMPID” and
that has value “AN2536”.
Create cookie:
<html>
<head>
<title> creating
cookie</title> </head>
<body>
<%! String MyCookieName=‖EMPID‖;
String UserValue=‖AN2536‖;
%>
</body>
</html>
Reading Cookie:
<html>
<head>
<body>
<% String myCookieName=‖EMPID‖;
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
String myCookieValue;
String CName, CValue;
int found=0;
myCookieValue=Cvalue; } }
If(found== 1) { %>
Connect to Jakarta.apache.org.
Select down load
Tomcat.
Open your browser. Enter http://localhost:8080.
Tomcat home page is displayed on the screen verifying that Tomcat is
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
running.
<body>
Session.setAttributes(AtName, AtValue);
%></body></html>
<body><% !
Enumaration purchases=session.getAttributeNames();
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Module -5
• Java was not considered industrial strength programming language since java was
unable to access the DBMS.
• Each dbms has its own way to access the data storage. low level code required to
access oracle data storage need to be rewritten to access db2.
• JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases
JDBC Architecture
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
10. SQL statements are transferred into the format required by the DBMS.
JDBC Packages
JDBC API contains two packages. First package is called java.sql, second package is
called javax.sql which extends java.sql for advanced JDBC features.
Explain the various steps of the JDBC process with code snippets.
1. Loading the JDBC driver
• The jdbc driver must be loaded before the J2EE compnet can be connected to
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
the database.
• Driver is loaded by calling the method and passing it the name of driver
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Once the driver is loaded , J2EE component must connect to the DBMS using
DriverManager.getConnection() method.
String url=‖jdbc:odbc:JdbcOdbcDriver‖;
String userId=‖jim‖
String password=‖Keogh‖;
Statement DatRequest;
Private Connection db;
try{
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Db=DriverManager.getConnection(url,userId,password);
}
The next step after the JDBC is loaded and connection is successfully made with a
particular database managed by the dbms, is to end a particular query to the DBMS for
processing.
SQL query consists series of SQL command that direct DBMS to do something
example Return rows.
The statement object is then used to execute a query and return result object that
contain response from the DBMS
Statement DataRequest;
ResultSet Results;
try {
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
DataRequest=Database.createStatement();
Results= DataRequests.executeQuery(query);
}
java.sql.ResultSet object is assigned the result received from the DBMS after the query
is processed.
java.sql.ResultSet contain method to interct with data that is returned by the DBMS to
the J2EE Component.
Results= DataRequests.executeQuery(query);
do
{
Fname=Results.getString(Fname)
}
While(Results.next())
In the above code it return result from the query and executes the
query. And getString is used to process the String retrived from the
database.
1 After the JDBC driver is successfully loaded and registered, the J2EE component
must connect to the database. The database must be associated with the JDBC driver.
2 The datasource that JDBC component will connect to is identified using the URL
format. The URL consists of three format.
• These are jdbc which indicate jdbc protocol is used to read the URL.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
• getConnection(String url)
5 getConnection(String url)
Class.forName(―sun:jdbc.odbc.JdbcOdbcDriver‖);
Db=DriverManager.getConnection(url);
}
• Database has limited access to the database to authorized user and require
J2EE to supply user id and password with request access to the database.
The this method is used.
try{
Class.forName(―sun:jdbc.odbc.JdbcOdbcDriver‖);
Db=DriverManager.getConnection(url,userId,password);
}
• The property is stored in text file. And then loaded by load method of
Properties class.
Connection db;
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
try {
5. Database may not connect immediately delayed response because database may not
available.
6. Rather than delayed waiting timeJ2EE component can stop connection. After some
time. This time can bet set with the following method:
DriverManager.setLoginTimeout(int sec).
B Client needs frequent that needs to frequently interact with database must either open
connection and leave open connection during processing or open or close and
reconnect each time.
C Leaving the connection may open might prevent another client from accessing the
database when DBS have limited no of connections. Connecting and reconnecting is
time consuming.
D The release of JDBC 2.1 Standard extension API introduced concept on connection
pooling
E A connection pool is a collection of database connection that are opened and loaded
into memory so these connection can be reused with out reconnecting to the
database.
G There are two types of connection to the database 1.) Logical 2.) Physical
H The following is code to connect to connection pool.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Connection db=pool.getConnection();
Briefly explain the Statement object. Write program to execute a SQL statement.(10)
2. The statement object contains the excuteQuery() method , which accept query
as argument then query is transmitted for processing.It returns ResultSet as
object.
Example Program
String url=‖jdbc:odbc:JdbcOdbcDriver‖;
String userId=‖jim‖
String password=‖Keogh‖;
Statement DatRequest;
Private Connection db;
ResultSet rs;
DatRequest=Db.createStaement();
rs=DatRequest.executeQuery(query);// return result set
object
}catch(SQLException err)
{
System.err.println(―Error‖);
System.exit(1);
}
3. Another method is used when DML and DDL operations are used for
processing query is executeUpdate(). This returns no of rows as integer.
try{
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
System.err.println(―Error‖);
System.exit(1);
Briefly explain the prepared statement object. Write program to call a stored
procedure.(10)
1. A SQL query must be compiled before DBMS processes the query. Query is
precompiled and executed using Prepared statements.
2. Question mark is placed as the value of the customer number. The value will be
inserted into the precompiled query later in the code.
3. Setxxx() is used to replace the question mark with the value passed to the setxxx()
method . xxx represents data type of the field.
4. It takes two arguments on is position of question mark and other is value to the filed.
}catch(SQLException err)
{
System.err.println(―Error‖);
System.exit(1);
}
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Briefly explain the callable statement object. Write program to call a stored procedure.(10)
1. The callableStatement object is used to call a stored procedure from with in J2EE
object. A stored procedure is block of code and is identified by unique name. the
code can bewritten in Transact-C ,PL/SQL.
3. The callableStatement uses three types of parameter when calling stored procedure.
The parameters are IN ,OUT,INOUT.
4. IN parameter contains data that needs to be passed to the stored procedure whose
value is assigned using setxxx() method.
5. OUT parameter contains value returned by stored procedure.the OUT parameter
should be registers by using registerOutParameter() method and then later
retrieved by the J2EE component using getxxx() method.
6. INOUT parameter is used to both pass information to the stored procedure and
retrieve the information from the procedure.
BEGIN
END;
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
receive an SQLException.
10. If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java
data type you are binding.
11. When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The registerOutParameter()
method binds the JDBC data type to the data type the stored procedure is expected
to return.
12. Once you call your stored procedure, you retrieve the value from the OUT
parameter with the appropriate getXXX() method. This method casts the retrieved
value of SQL type to a Java data type.
ResultSet
1. ResultSet object contain the methods that are used to copy data from
ResultSet into java collection object or variable for further processing.
8. Data in the ResultSet is logically organized into the virtual table for further
processing. Result set along with row and column it also contains meta data.
10. J2EE component should use the virtual cursor to each row and the use other
methods of the ResultSet to object to interact with the data stored in column of
the row.
11. The virtual cursor is positioned above the first row of data when the ResultSet
is returned by executeQuery () method.
12. The virtual cursor is moved to the first row with help of next() method
of ResultSet
13. Once virtual cursor is positioned getxxx() is used to return the data. Data
type of data is represents by xxx. It should match with column data type.
stmt =
conn.createStatement();
String sql;
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
int id = rs.getInt("id");/ /
rs.getInt(1); int age =
rs.getInt("age");
9. Until the release of JDBC 2.1 API , the virtual cursor can move only in forward
directions. But today the virtual cursor can be positioned at a specific row.
10. There are six methods to position the cursor at specific location in addition to next() in
scrollable result set. firs() ,last(), absolute(), relative(), previous(), and getRow().
15. relative()………… move relative to current row. Positive and negative no can be given.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
2.) TYPE_SCROLL_SENSITIVE
11. TYPE_SCROLL makes cursor to move both direction. INSENSITIVE makes changes
made by J2EE component will not reflect. SENSITIVE means changes by J2EE will
reflect in the result set.
Example code.
DR=Db.createStatement(TYPE_SCROLL_INSENSITIVE);
RS= DR.executeQuery(sql);
1. Rows contained in the result set is updatable similar to how rows in the table can
be updated. This is possible by sending CONCUR_UPDATABLE.
2. There are three ways in which result set can be changed. These are updating row ,
deleting a row, inserting a new row.
3. Update ResultSet
B. Once the executeQuery() method of the statement object returns a result set.
updatexxx() method is used to change the value of column in the current row of
result set.
D. updateRow() method is called after all the updatexxx() methods are called.
Example:
try{
DataRequest= Db.
createStatement(ResultSet.CONCUR_UPDATABLE);
Rs= DataRequest.executeQuery(query);
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Rs.updateString(“LastName”,”Smith”);
Rs.updateRow();
}
try{
DataRequest= Db.
createStatement(ResultSet.CONCUR_UPDATABLE);
Rs= DataRequest.executeQuery(query);
Rs.updateString(1 ,”Jon”);
Rs.updateString(2 ,”Smith”);
Rs.insertRow();
}
6. Whatever the changes making will affect only in the result set not in the table.
To update in the table have to execute the DML( update, insert, delete)
statements.
Explain the Transaction processing with example
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
2. Transaction is not completed until the J2EE component calls the commit() method of the
connection object. All SQL statements executed prior to the call to commit() method can
be rolled back.
3. Commit() method was automatically called in the program. DBMS has set AutoCommit
feature.
4. If the J2EE component is processing a transaction then it has to deactivate the auto
commit() option false.
try {
DataBase.setAutoCommit(false)
DR= DataBase.createStatement();
DataRequest=DataBase.createStatement();
DataRequest.executeUpdate(query1);
DataBase.commit();
7. A transaction may consists of many tasks , some of which no need to roll back . in such
situation we can create a savepoints, in between transactions. It was introduced in JDBC
3.0. save points are created and then passed as parameters to rollback() methods.
8. releseSavepint() is used to remove the savepoint from the transaction.
10. Another way to combine sql statements into a single into a single transaction and then
execute the entire transaction .
11. To do this the addBatch() method of statement object. The addBatch() method receives a
SQL statement as a parameter and places the SQL statement in the batch.
12. executeBatch() method is called to execute the entire batch at the same time. It returns an
array that contains no of SQL statement that execute successfully.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
―Where Fname=‘BoB‘ ―;
Statement DR=DB.createStatement();
DR.addBatch(query1);
DR.addBatch(query2);
2. This interface is used to return the meta data information about database.
Database metadata
ResultSet Metadata
ResultSetMetaData rm=Result.getMeatData()
The method used to retrieve meta data information about result set are
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
SQL JDBC/Java
VARCHAR java.lang.String
CHAR java.lang.String
LONGVARCHAR java.lang.String
BIT Boolean
NUMERIC java.math.BigDecimal
TINYINT Byte
SMALLINT Short
INTEGER Int
BIGINT Long
REAL Float
FLOAT Float
DOUBLE Double
VARBINARY byte[ ]
BINARY byte[ ]
DATE java.sql.Date
TIME java.sql.Time
Dept. of CS&E,BMSIT&M Page 125 By. Muneshwara M S, Asst. Prof
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
TIMESTAMP java.sql.Timestamp
CLOB java.sql.Clob
BLOB java.sql.Blob
ARRAY java.sql.Array
REF java.sql.Ref
Exception handling allows you to handle exceptional conditions such as program-defined errors
in a controlled fashion.
2. JDBC Exception handling is very similar to Java Excpetion handling but for
JDBC.
SQLWarnings
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
DataTruncation
• A standard Statement is used for creating a Java representation for a literal SQL statement
and for executing it on the database.
6. But, if we want to execute a single SQL statement for the multiple number of times, it‘ll
go to the PreparedStatement.
Java.sql.package include classes and interface to perform almost all JDBC operation such
as creating and executing SQL queries
Methods in Connection
setSavePoint()
rollback()
commit()
setAutoCommit()
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
Methods in CallableStatement
execute()
registerOutParameter()
4. java.sql.CLOB ------------ support for CLOB data type.
getConnection()
setLoginTimeout()
getLoginTimeout()
executeUpdate()
rs.last()
rs.first()
10. java.sql.Savepoint------- Specify savepoint in transaction.
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more
Modulewise Notes : Advanced Java & J2EE-17cs553
VTU Connect Download Android App from Play Store for Notes, Question Papers, Results Class Rank, Prev Sem Result and more