0% found this document useful (0 votes)
15 views40 pages

Java Collections Framework Overview

The document provides a comprehensive overview of the Java Collections Framework, detailing its structure, advantages, and commonly used classes such as ArrayList, Vector, and Hashtable. It explains the concept of generics in Java, showcasing how they enhance type safety and flexibility in collections. Additionally, it covers file management and database connectivity using JDBC, highlighting various input/output operations and database interactions.

Uploaded by

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

Java Collections Framework Overview

The document provides a comprehensive overview of the Java Collections Framework, detailing its structure, advantages, and commonly used classes such as ArrayList, Vector, and Hashtable. It explains the concept of generics in Java, showcasing how they enhance type safety and flexibility in collections. Additionally, it covers file management and database connectivity using JDBC, highlighting various input/output operations and database interactions.

Uploaded by

sgiddalu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Sl no CONTENT Pg no

Collection Framework in Java


1 Introduction to Java Collections 1
2 Overview of Java Collection frame work 1
3 Generics 2
4 Commonly used Collection classes Array List 3
5 Vector 4
6 Hash table 8
7 Stack 11
8 Enumeration 13
9 Iterator 14
10 String Tokenizer 17
11 Random 17
12 Scanner 18
13 calender and Properties 20

Files
14 streams - byte streams 24
15 character streams 25
16 text input/output (file input/output) 25
17 binary input/output 25
18 random access file operations 25
19 File managament using File class 27

Connecting to Database
20 JDBC Type 1 to 4 drives 31
21 connecting to a database 33
22 querying a database and processing the results 36
23 updating data with JDBC 37
COLLECTION FRAMEWORK IN JAVA

Collections Framework in Java- Introduction to Java collections:


The Java platform includes a collections framework. A collection is an object that represents a
group of objects (such as the classic Vector class). A collections framework is a unified
architecture for representing and manipulating collections, enabling collections to be
manipulated independently of implementation details.

It is a group of objects. It stores data in the form of objects. It supports the following operations:
1. Adding objects
2. Removing objects
3. Searching for objects
4. Sorting objects
5. Navigating through collection.
The [Link] package contains one of Java’s most powerful subsystems: collections.

The primary advantages of a collections framework are:


 Reduces programming effort by providing data structures and algorithms.
 Increases performance by providing high-performance implementations of data
structures and algorithms. Because the various implementations of each interface are
interchangeable, programs can be tuned by switching implementations.
 Provides interoperability between unrelated APIs by establishing a common language
to pass collections back and forth.
 Reduces the effort required to learn APIs by requiring the programmer to learn
multiple ad hoc collection APIs.
 Reduces the effort required to design and implement APIs by not requiring to
produce ad hoc collections APIs.
 Fosters software reuse by providing a standard interface for collections and algorithms
with which to manipulate them.

Overview of Java collection Framework:


The collections framework consists of:
 Collection interfaces. Represent different types of collections, such as sets, lists, and maps.
These interfaces form the basis of the framework.
 General-purpose implementations. Primary implementations of the collection interfaces.
 Legacy implementations. The collection classes from earlier releases, Vector and Hashtable,
were retrofitted to implement the collection interfaces.
 Special-purpose implementations. Implementations designed for use in special situations.
These implementations display nonstandard performance characteristics, usage restrictions,
or behavior.
 Concurrent implementations. Implementations designed for highly concurrent use.
 Wrapper implementations. Add functionality, such as synchronization, to other
implementations.

1
 Convenience implementations. High-performance "mini-implementations" of the collection
interfaces.
 Abstract implementations. Partial implementations of the collection interfaces to facilitate
custom implementations.
 Algorithms. Static methods that perform useful functions on collections, such as sorting a
list.
 Infrastructure. Interfaces that provide essential support for the collection interfaces.
 Array Utilities. Utility functions for arrays of primitive types and reference objects.

Generics:
Generics are a facility of generic programming that were added to theJava programming
language in 2004. They allow "a type or method to operate on objects of various types while
providing compile-time type safety." This feature specifies the type of objects stored in a
Java Collection.

GENERIC CLASS DEFINITIONS


Here is an example of a generic Java class, which can be used to represent individual entries (key
to value mappings) in amap:

public class Entry<KeyType, ValueType> {

private final KeyType key;


private final ValueType value;

public Entry(KeyType key, ValueType value) {


[Link] = key;
[Link] = value;
}

public KeyType getKey() {


return key;
}

public ValueType getValue() {


return value;
}

public String toString() {


return "(" + key + ", " + value + ")";
}

}
This generic class could be used in the following ways, for example:
Entry<String, String> grade = new Entry<String, String>("Mike", "A");

2
Entry<String, Integer> mark = new Entry<String, Integer>("Mike", 100);
[Link]("grade: " + grade);
[Link]("mark: " + mark);

Entry<Integer, Boolean> prime = new Entry<Integer, Boolean>(13, true);


if ([Link]()) [Link]([Link]() + " is prime.");
else [Link]([Link]() + " is not prime.");

Output:

grade: (Mike, A)
mark: (Mike, 100)
13 is prime.

GENERIC METHOD DEFINITIONS


Here is an example of a generic method using the generic class above:
public static <Type> Entry<Type, Type> twice(Type value) {
return new Entry<Type, Type>(value, value);
}

Creation of generic methods based on given parameters.


public <Type> Type[] toArray(Type... elements) {
return elements;
}
In such cases don't use primitive types either, ex:
Integer[] array = toArray(1, 2, 3, 4, 5, 6);

Commonly used collection classes:

Array List:
o Java ArrayList class uses a dynamic array for storing the [Link] extends AbstractList
class and implements List interface.
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.

3
Example of Java ArrayList class
import [Link].*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();//creating arraylist
[Link]("Ravi");//adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator itr=[Link]();//getting Iterator from arraylist to traverse elements
while([Link]()){
[Link]([Link]());
}
}
}

OUTPUT:
Ravi
Vijay
Ravi
Ajay

Vector:
 It is a dynamic array. Its size can be increased / decreased at runtime. It can store any
kind of data in the form of objects.
Eg. [Link]
 Vector implements a dynamic array. It is similar to ArrayList, but with two
differences:
o Vector is synchronized.
o Vector contains many legacy methods that are not part of the collections
framework.
 Vector proves to be very useful if the size of the array is not known in advance or
there is a need for one that can change sizes over the lifetime of a program.
 The Vector class supports four constructors. The first form creates a default vector,
which has an initial size of 10:
Vector( )
The second form creates a vector whose initial capacity is specified by size:
Vector(int 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:
Vector(int size, int incr)
The fourth form creates a vector that contains the elements of collection c:

4
Vector(Collection c)
Apart from the methods inherited from its parent classes, Vector defines the following methods:
SN Methods with Description
void add(int index, Object element)
1
Inserts the specified element at the specified position in this Vector.
boolean add(Object o)
2
Appends the specified element to the end of this Vector.
void addElement(Object obj)
3 Adds the specified component to the end of this vector, increasing its
size by one.
int capacity()
4
Returns the current capacity of this vector.

void clear()
5
Removes all of the elements from this Vector.
Object clone()
6
Returns a clone of this vector.
Object elementAt(int index)
7
Returns the component at the specified index.
Enumeration elements()
8
Returns an enumeration of the components of this vector.
Object firstElement()
9
Returns the first component (the item at index 0) of this vector.
Object get(int index)
10
Returns the element at the specified position in this Vector.
int hashCode()
11
Returns the hash code value for this Vector.
int indexOf(Object elem)
12 Searches for the first occurence of the given argument, testing for
equality using the equals method.
void insertElementAt(Object obj, int index)
13 Inserts the specified object as a component in this vector at the specified
index.
14 Object lastElement()

5
Returns the last component of the vector.
Object remove(int index)
15
Removes the element at the specified position in this Vector.
void removeElementAt(int index)
16
removeElementAt(int index)
Object set(int index, Object element)
17 Replaces the element at the specified position in this Vector with the
specified element.
void setElementAt(Object obj, int index)
18 Sets the component at the specified index of this vector to be the
specified object.
void setSize(int newSize)
19
Sets the size of this vector.
int size()
20
Returns the number of components in this vector.
void trimToSize()
21
Trims the capacity of this vector to be the vector's current size.

EXAMPLE:
The following program illustrates several of the methods supported by this collection:
import [Link].*;

public class VectorDemo {

public static void main(String args[]) {


// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
[Link]("Initial size: " + [Link]());
[Link]("Initial capacity: " +
[Link]());
[Link](new Integer(1));
[Link](new Integer(2));
[Link](new Integer(3));
[Link](new Integer(4));
[Link]("Capacity after four additions: " +
[Link]());

[Link](new Double(5.45));
[Link]("Current capacity: " +
[Link]());
[Link](new Double(6.08));
[Link](new Integer(7));

6
[Link]("Current capacity: " +
[Link]());
[Link](new Float(9.4));
[Link](new Integer(10));
[Link]("Current capacity: " +
[Link]());
[Link](new Integer(11));
[Link](new Integer(12));
[Link]("First element: " +
(Integer)[Link]());
[Link]("Last element: " +
(Integer)[Link]());
if([Link](new Integer(3)))
[Link]("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = [Link]();
[Link]("\nElements in vector:");
while([Link]())
[Link]([Link]() + " ");
[Link]();
}
}
This would produce the following result:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.

Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12

7
Hashtable:
It is sub class of Dictionary. It allows data to be stored in the form of key/value pairs.
Eg: [Link]
Properties
It is sub class of Hashtable. It has all qualities of Hashtable. In addition, it does the following:
1. Can read key/value pairs from a file.
2. Can write key/value pairs to a file.
3. Can obtain System properties.
4. Can read all system properties in the form of key value pairs.
Eg. [Link] (read system properties)
Eg. [Link]
Eg. [Link]

Hashtable is part of the [Link] and is an implementation of a Dictionary.


It is similar to HashMap, but is synchronized.
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable,
specify an object that is used as a key, and the value that is to be 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.

The Hashtable defines four constructors. The first version is the default constructor:
Hashtable( )
The second version creates a hash table that has an initial size specified by size:
Hashtable(int size)
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.
Hashtable(int size, float fillRatio)
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.
Hashtable(Map m)
Apart from the methods defined by Map interface, Hashtable defines the following methods:
SN Methods with Description
void clear( )
1
Resets and empties the hash table.
Object clone( )
2
Returns a duplicate of the invoking object.
boolean contains(Object value)
3
Returns true if some value equal to value exists within the hash table.

8
Returns false if the value isn't found.
boolean containsKey(Object key)
4 Returns true if some key equal to key exists within the hash table.
Returns false if the key isn't found.
boolean containsValue(Object value)
5 Returns true if some value equal to value exists within the hash table.
Returns false if the value isn't found.
Enumeration elements( )
6
Returns an enumeration of the values contained in the hash table.

Object get(Object key)


7 Returns the object that contains the value associated with key. If key is
not in the hash table, a null object is returned.
boolean isEmpty( )
8 Returns true if the hash table is empty; returns false if it contains at least
one key.
Enumeration keys( )
9
Returns an enumeration of the keys contained in the hash table.
Object put(Object key, Object value)
Inserts a key and a value into the hash table. Returns null if key isn't
10
already in the hash table; returns the previous value associated with key if
key is already in the hash table.
void rehash( )
11
Increases the size of the hash table and rehashes all of its keys.
Object remove(Object key)
12 Removes key and its value. Returns the value associated with key. If key
is not in the hash table, a null object is returned.
int size( )
13
Returns the number of entries in the hash table.
String toString( )
14
Returns the string equivalent of a hash table.

EXAMPLE:
The following program illustrates several of the methods supported by this data structure:
import [Link].*;

public class HashTableDemo {

public static void main(String args[]) {

9
// Create a hash map
Hashtable balance = new Hashtable();
Enumeration names;
String str;
double bal;

[Link]("Zara", new Double(3434.34));


[Link]("Mahnaz", new Double(123.22));
[Link]("Ayan", new Double(1378.00));
[Link]("Daisy", new Double(99.22));
[Link]("Qadir", new Double(-19.08));

// Show all balances in hash table.


names = [Link]();
while([Link]()) {
str = (String) [Link]();
[Link](str + ": " +
[Link](str));
}
[Link]();
// Deposit 1,000 into Zara's account
bal = ((Double)[Link]("Zara")).doubleValue();
[Link]("Zara", new Double(bal+1000));
[Link]("Zara's new balance: " +
[Link]("Zara"));
}
}
This would produce the following result:
Qadir: -19.08
Zara: 3434.34
Mahnaz: 123.22
Daisy: 99.22
Ayan: 1378.0

Zara's new balance: 4434.34

10
Stack:
It is a subclass of vector. In addition to vector’s qualities, it can be used as a LIFO data structure.
It provides methods like.
push() : adds an item to stack
pop() : removes an item from stack
peek() : retrieves an item without removing it from stack.
Eg. [Link]
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. Stack includes all the
methods defined by Vector, and adds several of its own.
Stack( )
Apart from the methods inherited from its parent class Vector, Stack defines following methods:
SN Methods with Description
boolean empty()
1 Tests if this stack is empty. Returns true if the stack is empty, and
returns false if the stack contains elements.
Object peek( )
2
Returns the element on the top of the stack, but does not remove it.
Object pop( )
3
Returns the element on the top of the stack, removing it in the process.
Object push(Object element)
4
Pushes element onto the stack. element is also returned.
int search(Object element)
5 Searches for element in the stack. If found, its offset from the top of the
stack is returned. Otherwise, .1 is returned.

EXAMPLE:
The following program illustrates several of the methods supported by this collection:
import [Link].*;

public class StackDemo {

static void showpush(Stack st, int a) {


[Link](new Integer(a));
[Link]("push(" + a + ")");
[Link]("stack: " + st);
}

static void showpop(Stack st) {


[Link]("pop -> ");
Integer a = (Integer) [Link]();
[Link](a);

11
[Link]("stack: " + st);
}

public static void main(String args[]) {


Stack st = new Stack();
[Link]("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
[Link]("empty stack");
}
}
}
This would produce the following result:
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack

12
Enumeration:
It is used to navigate through legacy collection classes. It is a legacy collection interface, which
is used to iterate through legacy collections.

The Enumeration interface defines the methods by which can be enumerated (obtain one at a
time) the elements in a collection of objects.

This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is
considered obsolete for new code. However, it is used by several methods defined by the legacy
classes such as Vector and Properties, is used by several other API classes.

The methods declared by Enumeration are summarized in the following table:


SN Methods with Description
boolean hasMoreElements( )
When implemented, it must return true while there are still more
1
elements to extract, and false when all the elements have been
enumerated.
Object nextElement( )
2 This returns the next object in the enumeration as a generic Object
reference.
EXAMPLE:
Following is the example showing usage of Enumeration.
import [Link];
import [Link];

public class EnumerationTester {

public static void main(String args[]) {


Enumeration days;
Vector dayNames = new Vector();
[Link]("Sunday");
[Link]("Monday");
[Link]("Tuesday");
[Link]("Wednesday");
[Link]("Thursday");
[Link]("Friday");
[Link]("Saturday");
days = [Link]();
while ([Link]()){
[Link]([Link]());
}
}
}
This would produce the following result:

13
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Iterator:
Often, there is a need to cycle through the elements in a collection. For example, if the
programmer want to display each element.
The easiest way to do this is to employ an iterator, which is an object that implements either the
“Iterator” or the “ListIterator interface”.

Iterator enables to cycle through a collection, obtaining or removing elements.

ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of
elements.
Before accessing a collection through an iterator, 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, each element in the collection can be accessed, one element at a time.

In general, to use an iterator to cycle through the contents of a collection, follow these steps:
 Obtain an iterator to the start of the collection by calling the collection's iterator( )
method.
 Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( )
returns true.
 Within the loop, obtain each element by calling next( ).

For collections that implement List, an iterator can also be obtained by calling ListIterator.

THE METHODS DECLARED BY ITERATOR:


SN Methods with Description
boolean hasNext( )
1
Returns true if there are more elements. Otherwise, returns false.
Object next( )
2 Returns the next element. Throws NoSuchElementException if there is
not a next element.
void remove( )
3 Removes the current element. Throws IllegalStateException if an
attempt is made to call remove( ) that is not preceded by a call to next( ).

14
THE METHODS DECLARED BY LISTITERATOR:
SN Methods with Description
void add(Object obj)
1 Inserts obj into the list in front of the element that will be returned by the
next call to next( ).
boolean hasNext( )
2
Returns true if there is a next element. Otherwise, returns false.
boolean hasPrevious( )
3
Returns true if there is a previous element. Otherwise, returns false.
Object next( )
4 Returns the next element. A NoSuchElementException is thrown if there
is not a next element.
int nextIndex( )
5 Returns the index of the next element. If there is not a next element,
returns the size of the list.
Object previous( )
6 Returns the previous element. A NoSuchElementException is thrown if
there is not a previous element.
int previousIndex( )
7 Returns the index of the previous element. If there is not a previous
element, returns -1.
void remove( )
8 Removes the current element from the list. An IllegalStateException is
thrown if remove( ) is called before next( ) or previous( ) is invoked.
void set(Object obj)
9 Assigns obj to the current element. This is the element last returned by a
call to either next( ) or previous( ).

EXAMPLE:
Here is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but
the general principles apply to any type of collection.
Of course, ListIterator is available only to those collections that implement the List interface.
import [Link].*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
[Link]("C");

15
[Link]("A");
[Link]("E");
[Link]("B");
[Link]("D");
[Link]("F");
// Use iterator to display contents of al
[Link]("Original contents of al: ");
Iterator itr = [Link]();
while([Link]()) {
Object element = [Link]();
[Link](element + " ");
}
[Link]();
// Modify objects being iterated
ListIterator litr = [Link]();
while([Link]()) {
Object element = [Link]();
[Link](element + "+");
}
[Link]("Modified contents of al: ");
itr = [Link]();
while([Link]()) {
Object element = [Link]();
[Link](element + " ");
}
[Link]();
// Now, display the list backwards
[Link]("Modified list backwards: ");
while([Link]()) {
Object element = [Link]();
[Link](element + " ");
}
[Link]();
}
}
This would produce the following result:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+

16
StringTokenizer:
The processing of text often consists of parsing a formatted input string. Parsing is the
division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a
semantic meaning.

The StringTokenizer class provides the first step in this parsing process, often called the
lexer (lexical analyzer) or scanner. StringTokenizer implements the Enumeration interface.
Therefore, given an input string, enumerate the individual tokens contained in it using
StringTokenizer.

To use StringTokenizer, specify an input string and a string that contains delimiters.
Delimiters are characters that separate tokens. Each character in the delimiters string is
considered a valid delimiter—for example, “,;:” sets the delimiters to a comma, semicolon, and
colon. The default set of delimiters consists of the whitespace characters: space, tab, newline,
and carriage return.

The StringTokenizer constructors are shown here:


StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)

In all versions, str is the string that will be tokenized. In the first version, the default delimiters
are used. In the second and third versions, delimiters is a string that specifies
the delimiters. In the third version, if delimAsToken is true, then the delimiters are also
returned as tokens when the string is parsed. Otherwise, the delimiters are not returned.
Delimiters are not returned as tokens by the first two forms.
Once a StringTokenizer object is created, the nextToken( ) method is used to extract
consecutive tokens. The hasMoreTokens( ) method returns true while there are more tokens to
be extracted. Since StringTokenizer implements Enumeration, the
hasMoreElements( ) and nextElement( ) methods are also implemented, and they act
the same as hasMoreTokens( ) and nextToken( ), respectively.

Random:
The Random class is a generator of pseudorandom numbers. These are called pseudorandom
numbers because they are simply uniformly distributed sequences.

Random defines the following constructors:


Random( )
Random(long seed)
The first version creates a number generator that uses the current time as the starting,
or seed, value.

The second form allows to specify a seed value manually. If a Random object is initialized with a
seed, then the starting point for the random sequence must be defined.

17
The easiest way to do this is to use the current time to seed a Random object. This approach
reduces the possibility of getting repeated sequences.
Some of the methods in this class are:
i. boolean nextBoolean( ): Returns the next boolean random number.
ii. void nextBytes(byte vals[ ]): Fills vals with randomly generated values.
iii. double nextDouble( ): Returns the next double random number.
iv. float nextFloat( ): Returns the next float random number.
v. double nextGaussian( ): Returns the next Gaussian random number.
vi. int nextInt( ): Returns the next int random number.
vii. int nextInt(int n): Returns next int random number within the range zero to n.
viii. long nextLong( ): Returns the next long random number.

Scanner:
The [Link] class is a simple text scanner which can parse primitive types and strings
using regular [Link] are the important points about Scanner:
 A Scanner breaks its input into tokens using a delimiter pattern, which by default matches
whitespace.
 A scanning operation may block waiting for input.
 A Scanner is not safe for multithreaded use without external synchronization.
CLASS DECLARATION
Following is the declaration for [Link] class:
public final class Scanner
extends Object
implements Iterator<String>
CLASS CONSTRUCTORS
S.N. Constructor & Description
Scanner(File source)
1 This constructs a new Scanner that produces values scanned from the
specified file.
Scanner(File source, String charsetName)
2 This constructs a new Scanner that produces values scanned from the
specified file.
Scanner(InputStream source)
3 This constructs a new Scanner that produces values scanned from the
specified input stream..
Scanner(InputStream source, String charsetName)
4 This constructs a new Scanner that produces values scanned from the
specified input stream.
Scanner(Readable source)
5 This constructs a new Scanner that produces values scanned from the
specified source.
6 Scanner(ReadableByteChannel source)

18
This constructs a new Scanner that produces values scanned from the
specified channel.
Scanner(ReadableByteChannel source, String charsetName)
7 This constructs a new Scanner that produces values scanned from the
specified channel.
Scanner(String source)
8 This constructs a new Scanner that produces values scanned from the
specified string.
CLASS METHODS
S.N. Method & Description
void close()
1
This method closes this scanner.
Pattern delimiter()
2 This method returns the Pattern this Scanner is currently using to match
delimiters.
String findInLine(Pattern pattern)
3 This method attempts to find the next occurrence of the specified
pattern ignoring delimiters.
String findInLine(String pattern)
4 This method attempts to find the next occurrence of a pattern
constructed from the specified string, ignoring delimiters.
String findWithinHorizon(Pattern pattern, int horizon)
5 This method attempts to find the next occurrence of the specified
pattern.
String findWithinHorizon(String pattern, int horizon)
6 This method attempts to find the next occurrence of a pattern
constructed from the specified string, ignoring delimiters.
boolean hasNext()
7
This method returns true if this scanner has another token in its input.
boolean hasNext(Pattern pattern)
8 This method returns true if the next complete token matches the
specified pattern.
byte nextByte(int radix)
9
This method scans the next token of the input as a byte.
double nextDouble()
10
This method scans the next token of the input as a double.
float nextFloat()
11
This method scans the next token of the input as a float.

19
int nextInt()
12
This method scans the next token of the input as an int.
int nextInt(int radix)
13
This method scans the next token of the input as an int.
String nextLine()
14 This method advances this scanner past the current line and returns the
input that was skipped.
long nextLong()
15
This method scans the next token of the input as a long.

Calendar and Properties:


The [Link] class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting
the date of the next [Link] are the important points about Calendar:
 This class also provides additional fields and methods for implementing a concrete calendar
system outside the package.
 Calendar defines the range of values returned by certain calendar fields.
CLASS DECLARATION
Following is the declaration for [Link] class:
public abstract class Calendar
extends Object
implements Serializable, Cloneable, Comparable<Calendar>
FIELD
Following are the fields for [Link] class:
 static int ALL_STYLES -- This is the style specifier for getDisplayNames indicating names in
all styles, such as "January" and "Jan".
 static int AM -- This is the value of the AM_PM field indicating the period of the day from
midnight to just before noon.
 static int AM_PM -- This is the field number for get and set indicating whether the HOUR is
before or after noon.
 static int APRIL -- This is the value of the MONTH field indicating the fourth month of the
year in the Gregorian and Julian calendars.
 protected boolean areFieldsSet -- This is true if fields[] are in sync with the currently set time.
 static int AUGUST -- This is the value of the MONTH field indicating the eighth month of the
year in the Gregorian and Julian calendars.
 static int DATE -- This is the field number for get and set indicating the day of the month.
 static int DAY_OF_MONTH -- This is the field number for get and set indicating the day of
the month.
 static int DAY_OF_WEEK -- This is the field number for get and set indicating the day of the
week.
 static int DAY_OF_WEEK_IN_MONTH -- This is the field number for get and set indicating
the ordinal number of the day of the week within the current month.

20
 static int DAY_OF_YEAR -- This is the field number for get and set indicating the day number
within the current year.
CLASS CONSTRUCTORS
S.N. Constructor & Description
protected Calendar()
1 This constructor constructs a Calendar with the default time zone and
locale.
protected Calendar(TimeZone zone, Locale aLocale)
2 This constructor constructs a calendar with the specified time zone and
locale.
CLASS METHODS
S.N. Method & Description
abstract void add(int field, int amount)
1 This method adds or subtracts the specified amount of time to the given
calendar field, based on the calendar's rules.
boolean after(Object when)
2 This method returns whether this Calendar represents a time after the
time represented by the specified Object.
boolean before(Object when)
3 This method returns whether this Calendar represents a time before the
time represented by the specified Object.
void clear()
4 This method sets all the calendar field values and the time value
(millisecond offset from the Epoch) of this Calendar undefined.
void clear(int field)
5 This method sets the given calendar field value and the time value
(millisecond offset from the Epoch) of this Calendar undefined.
Object clone()
6
This method creates and returns a copy of this object.
int compareTo(Calendar anotherCalendar)
7 This method compares the time values (millisecond offsets from the
Epoch) represented by two Calendar objects.
protected void complete()
8
This method fills in any unset fields in the calendar fields.
protected abstract void computeFields()
9 This method converts the current millisecond time value time to
calendar field values in fields[].
10 protected abstract void computeTime()

21
This method converts the current calendar field values in fields[] to the
millisecond time value time.
boolean equals(Object obj)
11
This method compares this Calendar to the specified Object.
int get(int field)
12
This method returns the value of the given calendar field.
int getActualMaximum(int field)
13 This method returns the maximum value that the specified calendar
field could have, given the time value of this Calendar.
int getActualMinimum(int field)
14 This method returns the minimum value that the specified calendar
field could have, given the time value of this Calendar.
static Locale[] getAvailableLocales()
15 This method returns an array of all locales for which the getInstance
methods of this class can return localized instances.
String getDisplayName(int field, int style, Locale locale)
16 This method returns the string representation of the calendar field value
in the given style and locale.
Map<String,Integer> getDisplayNames(int field, int style, Locale
locale)
17
This method returns a Map containing all names of the calendar field in
the given style and locale and their corresponding field values.
int getFirstDayOfWeek()
18 This method gets what the first day of the week is; e.g., SUNDAY in
the U.S., MONDAY in France.
abstract int getGreatestMinimum(int field)
19 This method returns the highest minimum value for the given calendar
field of this Calendar instance.
static Calendar getInstance()
20
This method gets a calendar using the default time zone and locale.
static Calendar getInstance(Locale aLocale)
21 This method gets a calendar using the default time zone and specified
locale.
static Calendar getInstance(TimeZone zone)
22 This method gets a calendar using the specified time zone and default
locale.
static Calendar getInstance(TimeZone zone, Locale aLocale)
23
This method gets a calendar with the specified time zone and locale.

22
Files:
Files are a primary source and destination for data within many [Link] are still a central
resource for storing persistent and shared information. A directory in Java is treated simply as a
File with one additional property—a list of filenames that can be examined by the list( ) method.

The following constructors can be used to create File objects:


File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
Here, directoryPath is the path name of the file, filename is the name of the file, dirObj is a File
object that specifies a directory, and uriObj is a URI object that describes a file.
The following example demonstrates several of the File methods:
// Demonstrate File.
import [Link];
class FileDemo
{
static void p(String s)
{
[Link](s);
}
public static void main(String args[])
{
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + [Link]());
p("Path: " + [Link]());
p("Abs Path: " + [Link]());
p("Parent: " + [Link]());
p([Link]() ? "exists" : "does not exist");
p([Link]() ? "is writeable" : "is not writeable");
p([Link]() ? "is readable" : "is not readable");
p("is " + ([Link]() ? "" : "not" + " a directory"));
p([Link]() ? "is normal file" : "might be a named pipe");
p([Link]() ? "is absolute" : "is not absolute");
p("File last modified: " + [Link]());
p("File size: " + [Link]() + " Bytes");
} }

When this program is run, following is the output:


File Name: COPYRIGHT
Path: /java/COPYRIGHT
Abs Path: /java/COPYRIGHT
Parent: /java
exists
is writeable
is readable

23
is not a directory
is normal file
is absolute
File last modified: 812465204000
File size: 695 Bytes

The Stream Classes:


Java’s stream-based I/O is built upon four abstract classes: InputStream, OutputStream,
Reader, and Writer. They are used to create several concrete stream subclasses. Although
programs perform on their I/O operations through concrete subclasses, the top-level classes
define the basic functionality common to all stream classes.
InputStream and OutputStream are designed for byte streams.
Reader and Writer are designed for character streams.
The byte stream classes and the character stream classes form separate hierarchies. In general,
use the character stream classes when working with characters or strings, and use the byte stream
classes when working with bytes or other binary objects.

Byte Stream Classes:


InputStream
InputStream is an abstract class that defines Java’s model of streaming byte input. All of the
methods in this class will throw an IOException on error conditions.
Some of the methods in this class are:
 int available( ): Returns the number of bytes of input currently available for reading.
 void close( ): Closes the input source. Further read attempts will generate an
IOException.
 int read( ): Returns an integer representation of the next available byte of input. –1 is
returned when the end of the file is encountered.
 int read(byte buffer[ ]): Attempts to read up to [Link] bytes into buffer and returns
the actual number of bytes that were successfully read. –1 is returned when the end of the
file is encountered.
OutputStream
OutputStream is an abstract class that defines streaming byte output. All of the methods in this
class return a void value and throw an IOException in the case of errors.
Some of the methods in this class are:
 void close( ): Closes the output stream. Further write attempts will generate an
IOException.
 void write(int b): Writes a single byte to an output stream. Note that the parameter is an
int, which allows to call write( ) with expressions without having to cast them back to
byte.
 void write(byte buffer[ ]): Writes a complete array of bytes to an output stream.
1. FileInputStream
The FileInputStream class creates an InputStream that can be used to read bytes from
a file. Its two most common constructors are shown here:
FileInputStream(String filepath)
FileInputStream(File fileObj)
Either can throw a FileNotFoundException. Here, filepath is the full path name of a file,

24
and fileObj is a File object that describes the file.
2. FileOutputStream
FileOutputStream creates an OutputStream that can be used to write bytes to a file. Its
most commonly used constructors are shown here:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
They can throw a FileNotFoundException or a SecurityException. Here, filePath is the full path
name of a file, and fileObj is a File object that describes the file. If append is true, the file is
opened in append mode
The Character Streams:
While the byte stream classes provide sufficient functionality to handle any type of I/O
operation, they cannot work directly with Unicode characters. Since one of the main
purposes of Java is to support the “write once, run anywhere” philosophy, it was
necessary to include direct I/O support for characters. In this section, several of the
character I/O classes are discussed. As explained earlier, at the top of the character
stream hierarchies are the Reader and Writer abstract classes.

Reader
Reader is an abstract class that defines Java’s model of streaming character input. All of
the methods in this class will throw an IOException on error conditions.

Writer
Writer is an abstract class that defines streaming character output. All of the methods
in this class return a void value and throw an IOException in the case of errors.
1. FileReader
The FileReader class creates a Reader that can be used to read the contents of a file. Its
two most commonly used constructors are shown here:
FileReader(String filePath)
FileReader(File fileObj)
2. FileWriter
FileWriter creates a Writer that can be used to write to a file. Its most commonly used
constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
They can throw an IOException. Here, filePath is the full path name of a file, and fileObj
is a File object that describes the file. If append is true, then output is appended to the
end of the file.
Random access file operations:
RANDOM ACCESS FILES permit nonsequential, or random, access to a file's contents. To
access a file randomly, open the file, seek a particular location, and read from or write to that
file.

25
This functionality is possible with the SeekableByteChannel interface.
The SeekableByteChannel interface extends channel I/O with the notion of a current position.
Method enables to set or query the position, and can then read the data from, or write the data to,
that location. The API consists of a few, easy to use, methods:
 position – Returns the channel's current position
 position(long) – Sets the channel's position
 read(ByteBuffer) – Reads bytes into the buffer from the channel
 write(ByteBuffer) – Writes bytes from the buffer to the channel
 truncate(long) – Truncates the file (or other entity) connected to the channel
Reading and Writing Files With Channel I/O shows that the [Link] methods
return an instance of aSeekableByteChannel. On the default file system, use that channel as is, or
can cast it to a FileChannel giving access to more advanced features, such as mapping a region of
the file directly into memory for faster access, locking a region of the file, or reading and writing
bytes from an absolute location without affecting the channel's current position.
The following code snippet opens a file for both reading and writing by using one of
the newByteChannel methods. TheSeekableByteChannel that is returned is cast to a FileChannel.
Then, 12 bytes are read from the beginning of the file, and the string "I was here!" is written at
that location. The current position in the file is moved to the end, and the 12 bytes from the
beginning are appended. Finally, the string, "I was here!" is appended, and the channel on the file
is closed.
String s = "I was here!\n";
byte data[] = [Link]();
ByteBuffer out = [Link](data);
ByteBuffer copy = [Link](12);
try (FileChannel fc = ([Link](file, READ, WRITE))) {
// Read the first 12
// bytes of the file.
int nread;
do {
nread = [Link](copy);
} while (nread != -1 && [Link]());
// Write "I was here!" at the beginning of the file.
[Link](0);
while ([Link]())
[Link](out);
[Link]();
// Move to the end of the file. Copy the first 12 bytes to
// the end of the file. Then write "I was here!" again.
long length = [Link]();
[Link](length-1);
[Link]();
while ([Link]())
[Link](copy);
while ([Link]())
[Link](out);
} catch (IOException x) {

26
[Link]("I/O Exception: " + x);
}
File management using File class:
READING AND WRITING FILES:
As described earlier, A stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial:
FILEINPUTSTREAM:
This stream is used for reading data from the files. Objects can be created using the keyword new
and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file.:
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First
create a file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once the InputStream object in hand, then there is a list of helper methods which can be used to
read to stream or to do other operations on the stream.
SN Methods with Description
public void close() throws IOException{}
1 This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close
2
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.
3 public int read(int r)throws IOException{}

27
This method reads the specified byte of data from the InputStream.
Returns an int. Returns the next byte of data and -1 will be returned if it's
end of file.
public int read(byte[] r) throws IOException{}
4 This method reads [Link] bytes from the input stream into an array.
Returns the total number of bytes read. If end of file -1 will be returned.
public int available() throws IOException{}
5 Gives the number of bytes that can be read from this file input stream.
Returns an int.

FILEOUTPUTSTREAM:
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file:
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First,
create a file object using File() method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once OutputStream object is obtained, then there is a list of helper methods, which can be used
to write to stream or to do other operations on the stream.
SN Methods with Description
public void close() throws IOException{}
1 This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close
2
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.
public void write(int w)throws IOException{}
3
This methods writes the specified byte to the output stream.
public void write(byte[] w)
4 Writes [Link] bytes from the mentioned byte array to the
OutputStream.

28
EXAMPLE:
Following is the example to demonstrate InputStream and OutputStream:
import [Link].*;

public class fileStreamTest{

public static void main(String args[]){

try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("[Link]");
for(int x=0; x < [Link] ; x++){
[Link]( bWrite[x] ); // writes the bytes
}
[Link]();

InputStream is = new FileInputStream("[Link]");


int size = [Link]();

for(int i=0; i< size; i++){


[Link]((char)[Link]() + " ");
}
[Link]();
}catch(IOException e){
[Link]("Exception");
}
}
}
The above code would create file [Link] and would write given numbers in binary format. Same
would be output on the stdout screen.
FILE NAVIGATION AND I/O:
There are several other classes that would be going through to get to know the basics of File
Navigation and I/O.
 File Class
 FileReader Class
 FileWriter Class
DIRECTORIES IN JAVA:
A directory is a File which can contains a list of other files and [Link] File object to
create directories, to list down files available in a directory. For complete detail check a list of all
the methods which can be called on File object and what are related to directories.
CREATING DIRECTORIES:
There are two useful File utility methods, which can be used to create directories:
 The mkdir( ) method creates a directory, returning true on success and false on failure. Failure
indicates that the path specified in the File object already exists, or that the directory cannot be
created because the entire path does not exist yet.

29
 The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory:
import [Link];

public class CreateDir {


public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
[Link]();
}
}
Compile and execute above code to create "/tmp/user/java/bin".
Note: Java automatically takes care of path separators on UNIX and Windows as per
conventions.
LISTING DIRECTORIES:
Use list( ) method provided by File object to list down all the files and directories available in a
directory as follows:
import [Link];

public class ReadDir {


public static void main(String[] args) {

File file = null;


String[] paths;

try{
// create new file object
file = new File("/tmp");

// array of files and directory


paths = [Link]();

// for each name in the path array


for(String path:paths)
{
// prints filename and directory name
[Link](path);
}
}catch(Exception e){
// if any error occurs
[Link]();
}
}
}

30
This would produce following result based on the directories and files available in
the /tmp directory:
[Link]
[Link]
[Link]
[Link]
Connecting to Database - JDBC Type 1 to 4 drivers:
JDBC Type 1 to 4 drivers:
JDBC drivers implement the defined interfaces in the JDBC API for interacting with the
database server.
For example, using JDBC drivers enables to open database connections and to interact with it by
sending SQL or database commands then receiving results with Java.
The [Link] package that ships with JDK contains various classes with their behaviours defined
and their actual implementaions are done in third-party drivers. Third party vendors implements
[Link] interface in their database driver.
JDBC DRIVERS TYPES:
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below:
TYPE 1: JDBC-ODBC BRIDGE DRIVER:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC requires configuring on the system a Data Source Name (DSN) that
represents the target database.
When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.

The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.

TYPE 2: JDBC-NATIVE API:


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique
to the database. These drivers typically provided by the database vendors and used in the same

31
manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client
machine.
If the Database is changed then change the native API as it is specific to a database and they are
mostly obsolete now but there is some speed increase with a Type 2 driver, because it eliminates
ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.


TYPE 3: JDBC-NET PURE JAVA:
In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use
standard network sockets to communicate with an middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

The application server acts as a JDBC "proxy," meaning that it makes calls for the client
application. As a result, some knowledge of the application server's configuration is needed in
order to effectively use this driver type.
The application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

32
TYPE 4: 100% PURE JAVA:
In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.
This kind of driver is extremely flexible, there is no need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
WHICH DRIVER SHOULD BE USED?
If client is accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.
If the Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for the
database.
The type 1 driver is not considered a deployment-level driver and is typically used for
development and testing purposes only.
Connecting to a database:
After the appropriate driver is installed, it's time to establish a database connection using JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are these
simple four steps:
 Import JDBC Packages: Add import statements to the Java program to import required classes
in the Java code.
 Register JDBC Driver: This step causes the JVM to load the desired driver implementation into
memory so it can fulfill the JDBC requests.

33
 Database URL Formulation: This is to create a properly formatted address that points to the
database to which it is to be connected.
 Create Connection Object: Finally, code a call to the DriverManager object's getConnection(
)method to establish actual database connection.
IMPORT JDBC PACKAGES:
The Import statements tell the Java compiler where to find the classes reference in the code and
are placed at the very beginning of source code.
To use the standard JDBC package, which allows to select, insert, update, and delete data in SQL
tables, add the following imports to source code:
import [Link].* ; // for standard JDBC programs
import [Link].* ; // for BigDecimal and BigInteger support
REGISTER JDBC DRIVER:
The driver in the program must be registered before it can be used. Registering the driver is the
process by which the Oracle driver's class file is loaded into memory so it can be utilized as an
implementation of the JDBC interfaces.
Registration is done only once in program. Register a driver in one of two ways.
APPROACH (I) - [Link]():
The most common approach to register a driver is to use Java's [Link]() method to
dynamically load the driver's class file into memory, which automatically registers it. This
method is preferable because it allows to make the driver registration configurable and portable.
The following example uses [Link]( ) to register the Oracle driver:
try {
[Link]("[Link]");
}
catch(ClassNotFoundException ex) {
[Link]("Error: unable to load driver class!");
[Link](1);
}
Use getInstance() method to work around noncompliant JVMs code for two extra Exceptions as
follows:
try {
[Link]("[Link]").newInstance();
}
catch(ClassNotFoundException ex) {
[Link]("Error: unable to load driver class!");
[Link](1);
catch(IllegalAccessException ex) {
[Link]("Error: access problem while loading!");
[Link](2);
catch(InstantiationException ex) {
[Link]("Error: unable to instantiate driver!");
[Link](3);
}
APPROACH (II) - [Link]():

34
The second approach to register a driver is to use the
[Link]() method.
Use the registerDriver() method while using a non-JDK compliant JVM, such as the one
provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver:
try {
Driver myDriver = new [Link]();
[Link]( myDriver );
}
catch(ClassNotFoundException ex) {
[Link]("Error: unable to load driver class!");
[Link](1);
}

DATABASE URL FORMULATION:


After the driver is loaded, establish a connection using
[Link]() method.
The three overloaded [Link]() methods:
 getConnection(String url)
 getConnection(String url, Properties prop)
 getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to database.
Formulating a database URL is where most of the problems associated with establishing a
connection occur.
Following table lists down popular JDBC driver names and database URL.
RDBMS JDBC driver name URL format
jdbc:mysql://hostname/
MySQL [Link]
databaseName
jdbc:oracle:thin:@hostname:port
ORACLE [Link]
Number:databaseName

CREATE CONNECTION OBJECT:


USING A DATABASE URL WITH A USERNAME AND PASSWORD:
I listed down three forms of [Link]() method to create a connection
object. The most commonly used form of getConnection() requires to pass a database URL,
a username, and a password:
Assuming Oracle's thin driver, specify a host:port:databaseName value for the database portion
of the URL.
If host at TCP/IP address [Link] with a host name of amrood, and Oracle listener is
configured to listen on port 1521, and the database name is EMP, then complete database URL
would then be:
jdbc:oracle:thin:@amroo[Link]MP

35
Now call getConnection() method with appropriate username and password to get
aConnection object as follows:
String URL = "jdbc:oracle:thin:@amroo[Link]MP";
String USER = "username";
String PASS = "password"
Connection conn = [Link](URL, USER, PASS);
CLOSING JDBC CONNECTIONS:
At the end of JDBC program, it is required explicitly close all the connections to the database to
end each database session. However, if the programmer forgets, Java's garbage collector will
close the connection when it cleans up stale objects.
Relying on garbage collection, especially in database programming, is very poor programming
practice. Close the connection with the close() method associated with connection object.

To close above opened connection call close() method as follows:


[Link]();
Explicitly closing a connection conserves DBMS resources.

Querying Database and processing the results:


EXECUTING QUERIES
To execute a query, call an execute method from Statement such as the following:
 execute: Returns true if the first object that the query returns is a ResultSet object. Use
this method if the query could return one or more ResultSet objects. Retrieve
the ResultSet objects returned from the query by repeatedly
[Link].
 executeQuery: Returns one ResultSet object.
 executeUpdate: Returns an integer representing the number of rows affected by the SQL
statement. Use this method while using INSERT, DELETE, or UPDATE SQL
statements.
For example, [Link] executed a Statement object with the following code:
ResultSet rs = [Link](query);
See Retrieving and Modifying Values from Result Sets for more information.
PROCESSING RESULTSET OBJECTS
Access the data in a ResultSet object through a cursor. Note that this cursor is not a database
cursor. This cursor is a pointer that points to one row of data in the ResultSet object. Initially, the
cursor is positioned before the first row. Call various methods defined in the ResultSet object to
move the cursor.
For example, [Link] repeatedly calls the method [Link] to move the
cursor forward by one row. Every time it calls next, the method outputs the data in the row where
the cursor is currently positioned:
try {
stmt = [Link]();
ResultSet rs = [Link](query);
while ([Link]()) {
String coffeeName = [Link]("COF_NAME");
int supplierID = [Link]("SUP_ID");

36
float price = [Link]("PRICE");
int sales = [Link]("SALES");
int total = [Link]("TOTAL");
[Link](coffeeName + "\t" + supplierID +
"\t" + price + "\t" + sales +
"\t" + total);
}
}
Processing a Simple Query in JDBC
This example will issue a simple query and print out the first column of each row using
a Statement.
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM mytable WHERE columnfoo = 500");
while ([Link]())
{
[Link]("Column 1 returned ");
[Link]([Link](1));
} [Link]();
[Link]();
This example issues the same query as before but uses a PreparedStatement and a bind value in
the query.
int foovalue = 500;
PreparedStatement st = [Link]("SELECT * FROM mytable WHERE columnfoo
= ?");
[Link](1, foovalue);
ResultSet rs = [Link]();
while ([Link]())
{
[Link]("Column 1 returned ");
[Link]([Link](1));
}
[Link]();
[Link]();
Updating data with JDBC:
REQUIRED STEPS:
There are following steps required to create a new Database using JDBC application:
 Import the packages: Include the packages containing the JDBC classes needed for database
programming. Most often, using import [Link].* will suffice.
 Register the JDBC driver: Initialize a driver to establish open a communications channel with
the database.
 Open a connection: Requires using the [Link]() method to create a
Connection object, which represents a physical connection with a database server.
 Execute a query: Requires using an object of type Statement for building and submitting an
SQL statement to update records in a table. This Query makes use of IN and WHERE clause to
update conditional records.

37
 Clean up the environment: Requires explicitly closing all database resources versus relying on
the JVM's garbage collection.
SAMPLE CODE:
//STEP 1. Import required packages
import [Link].*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "[Link]";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
[Link]("[Link]");
//STEP 3: Open a connection
[Link]("Connecting to a selected database...");
conn = [Link](DB_URL, USER, PASS);
[Link]("Connected database successfully...");
//STEP 4: Execute a query
[Link]("Creating statement...");
stmt = [Link]();
String sql = "UPDATE Registration " +
"SET age = 30 WHERE id in (100, 101)";
[Link](sql);
// Now extract all the records
// to see the updated records
sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = [Link](sql);
while([Link]()){
//Retrieve by column name
int id = [Link]("id");
int age = [Link]("age");
String first = [Link]("first");
String last = [Link]("last");
//Display values
[Link]("ID: " + id);
[Link](", Age: " + age);
[Link](", First: " + first);
[Link](", Last: " + last);
}
[Link]();
}catch(SQLException se){

38
//Handle errors for JDBC
[Link]();
}catch(Exception e){
//Handle errors for [Link]
[Link]();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
[Link]();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
[Link]();
}catch(SQLException se){
[Link]();
}//end finally try
}//end try
[Link]("Goodbye!");
}//end main
}//end JDBCExample
C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Creating statement...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 101, Age: 30, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Goodbye!

39

You might also like