Java Collections Framework Overview
Java Collections Framework Overview
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
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.
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.
}
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);
Output:
grade: (Mike, A)
mark: (Mike, 100)
13 is prime.
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].*;
[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]
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.
EXAMPLE:
The following program illustrates several of the methods supported by this data structure:
import [Link].*;
9
// Create a hash map
Hashtable balance = new Hashtable();
Enumeration names;
String str;
double bal;
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].*;
11
[Link]("stack: " + st);
}
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.
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”.
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.
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.
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.
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.
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.
23
is not a directory
is normal file
is absolute
File last modified: 812465204000
File size: 695 Bytes
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].*;
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]();
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];
try{
// create new file object
file = new File("/tmp");
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.
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 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);
}
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.
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