Lab Java
Lab Java
asia
UNIT-1V
Collections in Java
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Let us see the hierarchy of collection framework.The java.util package contains all the classes
and interfaces for Collection framework.
There are many methods declared in the Collection interface. They are as follows:
No. Method Description
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
public boolean is used to delete all the elements of specified collection from the
4
removeAll(Collection c) invoking collection.
public boolean retainAll(Collection is used to delete all the elements of invoking collection except
5
c) the specified collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
public boolean
9 is used to search the specified collection in this collection.
containsAll(Collection c)
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
There are only three methods in the Iterator interface. They are:
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
3. public void remove() it removes the last elements returned by the iterator. It is rarely used.
Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList
class and implements List interface.
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because array works at the index basis.
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.
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have
only specified type of objects in it. If you try to add another type of object, it gives compile time
error.
1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Ravi");//adding object in arraylist
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
10.
11. Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Ravi
Vijay
Ravi
Ajay
1. By Iterator interface.
2. By for-each loop.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to
traverse ArrayList elements using for-each loop.
1. import java.util.*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. for(String obj:al)
10. System.out.println(obj);
11. }
12. }
Ravi
Vijay
Ravi
Ajay
1. class Student{
2. int rollno;
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
1. import java.util.*;
2. public class TestCollection3{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8.
9. ArrayList<Student> al=new ArrayList<Student>();//creating arraylist
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13.
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
1. import java.util.*;
2. class TestCollection4{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
9.
10. ArrayList<String> al2=new ArrayList<String>();
11. al2.add("Sonoo");
12. al2.add("Hanumat");
13.
14. al.addAll(al2);
15.
16. Iterator itr=al.iterator();
17. while(itr.hasNext()){
18. System.out.println(itr.next());
19. }
20. }
21. }
Ravi
Vijay
Ajay
Sonoo
Hanumat
1. import java.util.*;
2. class TestCollection5{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList<String> al2=new ArrayList<String>();
11. al2.add("Ravi");
12. al2.add("Hanumat");
13.
14. al.removeAll(al2);
15.
16. System.out.println("iterating the elements after removing the elements of al2...");
17. Iterator itr=al.iterator();
18. while(itr.hasNext()){
19. System.out.println(itr.next());
20. }
21.
22. }
23. }
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
1. import java.util.*;
2. class TestCollection6{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11.
12. al.retainAll(al2);
13.
14. System.out.println("iterating the elements after retaining the elements of al2...");
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. System.out.println(itr.next());
18. }
19. }
20. }
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any type of objects in collection i.e. non-generic. Now generics,
forces the java programmer to store specific type of objects.
1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store
other objects.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
1. ClassOrInterface<Type>
1. ArrayList<String>
1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
1. import java.util.*;
2. class TestGenerics2{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(1,"vijay");
6. map.put(4,"umesh");
7. map.put(2,"ankit");
8.
9. //Now use Map.Entry for Set and Iterator
10. Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12. Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13. while(itr.hasNext()){
14. Map.Entry e=itr.next();//no need to typecast
15. System.out.println(e.getKey()+" "+e.getValue());
16. }
17.
18. }}
Output:1 vijay
2 ankit
4 umesh
Generic class
A class that can refer to any type is known as generic class. Here, we are using T type parameter
to create the generic class of specific type.
Let’s see the simple example to create and use the generic class.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }
The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type
you specify for the class, will be used to store and retrieve the data.
Using generic class:
1. class TestGenerics3{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());
7. }}
Output:2
Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The
commonly type parameters are as follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value
Generic Method
Like generic class, we can create generic method that can accept any type of argument.
Let’s see a simple example of java generic method to print array elements. We are using here E
to denote the element.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
2.
3. public static < E > void printArray(E[] elements) {
4. for ( E element : elements){
5. System.out.println(element );
6. }
7. System.out.println();
8. }
9. public static void main( String args[] ) {
10. Integer[] intArray = { 10, 20, 30, 40, 50 };
11. Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };
12.
13. System.out.println( "Printing Integer Array" );
14. printArray( intArray );
15.
16. System.out.println( "Printing Character Array" );
17. printArray( charArray );
18. }
19. }
1. import java.util.*;
2. abstract class Shape{
3. abstract void draw();
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
4. }
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11.
12.
13. class GenericTest{
14. //creating a method that accepts only child class of Shape
15. public static void drawShapes(List<? extends Shape> lists){
16. for(Shape s:lists){
17. s.draw();//calling method of Shape class by child class instance
18. }
19. }
20. public static void main(String args[]){
21. List<Rectangle> list1=new ArrayList<Rectangle>();
22. list1.add(new Rectangle());
23.
24. List<Circle> list2=new ArrayList<Circle>();
25. list2.add(new Circle());
26. list2.add(new Circle());
27.
28. drawShapes(list1);
29. drawShapes(list2);
30. }}
drawing rectangle
drawing circle
drawing circle
;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........
1. import java.util.*;
2. import java.io.*;
3. public class Test {
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods or, with a single class declaration, a set of related types,
respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types at
compile time.
Using Java Generic concept, we might write a generic method for sorting an array of objects,
then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to
sort the array elements.
Generic Methods:
You can write a single generic method declaration that can be called with arguments of different
types. Based on the types of the arguments passed to the generic method, the compiler handles
each method call appropriately. Following are the rules to define Generic Methods:
All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type ( < E > in the next example).
Each type parameter section contains one or more type parameters separated by commas.
A type parameter, also known as a type variable, is an identifier that specifies a generic
type name.
The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double and
char).
Example:
Following example illustrates how we can print array of different type using a single Generic
method:
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
There may be times when you'll want to restrict the kinds of types that are allowed to be passed
to a type parameter. For example, a method that operates on numbers might only want to accept
instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends
keyword, followed by its upper bound.
Example:
Following example illustrates how extends is used in a general sense to mean either "extends"
(as in classes) or "implements" (as in interfaces). This example is Generic method to return the
largest of three Comparable objects:
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Maximum of 3, 4 and 5 is 5
Generic Classes:
A generic class declaration looks like a non-generic class declaration, except that the class name
is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more type
parameters separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.
Example:
private T t;
public T get() {
return t;
}
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream
in the java.io package supports many data such as primitives, Object, localized characters, etc.
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.
Java provides strong but flexible support for I/O related to Files and networks but this tutorial
covers very basic functionality related to streams and I/O. We would see most commonly used
example one by one:
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are , FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an
input file into an output file:
import java.io.*;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and
do the following:
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are , FileReader and
FileWriter.. Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here major difference is that FileReader reads two bytes at a time and
FileWriter writes two bytes at a time.
We can re-write above example which makes use of these two classes to copy an input file
(having unicode characters) into an output file:
import java.io.*;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and
do the following:
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where user's program can take
input from a keyboard and then produce output on the computer screen. If you are aware if C or
C++ programming languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similar way Java provides following three standard streams
Standard Input: This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's program and
usually a computer screen is used to standard output stream and represented as
System.out.
Standard Error: This is used to output the error data produced by the user's program
and usually a computer screen is used to standard error stream and represented as
System.err.
Following is a simple program which creates InputStreamReader to read standard input stream
until the user types a "q":
import java.io.*;
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This
program continues reading and outputting same character until we press 'q':
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
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.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
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.:
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows:
Once you have 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.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
There are other important input streams available, for more detail you can refer to the following
links:
ByteArrayInputStream
DataInputStream
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:
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows:
Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
There are other important output streams available, for more detail you can refer to the following
links:
ByteArrayOutputStream
DataOutputStream
Example:
import java.io.*;
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();
The above code would create file test.txt and would write given numbers in binary format. Same
would be output on the stdout screen.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
There are several other classes that we 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 directories. You use File object to
create directories, to list down files available in a directory. For complete detail check a list of all
the methods which you can call 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.
The mkdirs() method creates both a directory and all the parents of the directory.
import java.io.File;
Note: Java automatically takes care of path separators on UNIX and Windows as per
conventions. If you use a forward slash (/) on a Windows version of Java, the path will still
resolve correctly.
Listing Directories:
You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows:
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
import java.io.File;
try{
// create new file object
file = new File("/tmp");
This would produce following result based on the directories and files available in your /tmp
directory:
test1.txt
test2.txt
ReadDir.java
ReadDir.class
JDBC
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks commonly associated with database usage:
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executables, such as:
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs)
All of these different executables are able to use a JDBC driver to access a database and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in
general JDBC Architecture consists of two layers:
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application:
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Import the packages . Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
Register the JDBC driver . Requires that you initialize a driver so you can open a
communications channel with the database.
Open a connection . Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the database.
Execute a query . Requires using an object of type Statement for building and
submitting an SQL statement to the database.
Extract data from result set . Requires that you use the appropriate ResultSet.getXXX()
method to retrieve the data from the result set.
Clean up the environment . Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
There are six steps involved in building a JDBC application which I'm going to brief in
this tutorial:
Import the packages:
This requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice as follows:
//STEP 1. Import required packages
import java.sql.*;
Register the JDBC driver:
This requires that you initialize a driver so you can open a communications channel with
the database. Following is the code snippet to achieve this:
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Open a connection:
This requires using the DriverManager.getConnection() method to create a Connection
object, which represents a physical connection with the database as follows:
//STEP 3: Open a connection
// Database credentials
static final String USER = "username";
static final String PASS = "password";
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
Execute a query:
This requires using an object of type Statement or PreparedStatement for building and
submitting an SQL statement to the database as follows:
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Based on the above steps, we can have following consolidated sample code which we can
use as a template while writing our JDBC code:
This sample code has been written based on the environment and database setup done in
Environment chapter.
//STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Now let us compile above example as follows:
C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces following result:
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
SQLException Methods:
A SQLException can occur both in the driver and the database. When such an exception
occurs, an object of type SQLException will be passed to the catch clause.
The passed SQLException object has the following methods available for retrieving
additional information about the exception:
Method Description
getErrorCode( ) Gets the error number associated with the exception.
Gets the JDBC driver's error message for an error
getMessage( ) handled by the driver or gets the Oracle error number
and message for a database error.
Gets the XOPEN SQLstate string. For a JDBC driver
getSQLState( )
error, no useful information is returned from this
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
By utilizing the information available from the Exception object, you can catch an
exception and continue your program appropriately. Here is the general form of a try
block:
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
JDBC - Data Types:
The following table summarizes the default JDBC data type that the Java data type is
converted to when you call the setXXX() method of the PreparedStatement or
CallableStatement object or the ResultSet.updateXXX() method.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The
ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef()
methods that enable you to directly manipulate the respective data on the server.
The setXXX() and updateXXX() methods enable you to convert specific Java types to
specific JDBC data types. The methods, setObject() and updateObject(), enable you to
map almost any Java type to a JDBC data type.
ResultSet object provides corresponding getXXX() method for each data type to retrieve
column value. Each method can be used with column name or by its ordinal position.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Sample Code:
This sample example can serve as a template when you need to create your own JDBC
application in the future.
This sample code has been written based on the environment and database setup done in
previous chapter.
Copy and past following example in FirstExample.java, compile and run as follows:
// Database credentials
static final String USER = "username";
static final String PASS = "password";
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
ResultSet rs = stmt.executeQuery(sql);
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
C:\>javac FirstExample.java
C:\>
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
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:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC requires configuring on your 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.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.
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
manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client
machine.
If we change the Database we have to change the native API as it is specific to a database and
they are mostly obsolete now but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
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.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
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, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
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.
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.
If your 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 your
database.
The type 1 driver is not considered a deployment-level driver and is typically used for
development and testing purposes only.
jntuworldupdates.org Specworld.in