Advance Java
Advance Java
Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
Unit – 1
1). Java Database Connectivity
2). JDBC has four Components:
3). JDBC Architecture
3.1). JDBC two-tier Architecture
3.2). JDBC three-tier Architecture
4). Java Database Connectivity Steps
5). JDBC Driver
5.1). TYPE – 1: JDBC-ODBC Bridge
5.2). TYPE – 2 JDBC-Native API or Native Driver
5.3). Type 3: JDBC-Net pure Java or Middleware Driver
5.4). TYPE – 4: Native-protocol or Pure Java driver or Pure Driver
6). JDBC Connection
7). JDBC Statement object
8). Executing a SQL statement
9). JDBC Result Sets
9.1). Type of ResultSet:
Program – 1
10). List Interface in Java
10.1). Operations on List:
11). Java ArrayList class
11.1). Constructors of Java ArrayList
11.2). Declaration of ArrayList
12). Java Iterator interface
13). Ways to iterate the elements of the collection in java
13.1). Iterating Collection through Iterator interface
13.2). Iterating Collection through the for-each loop
14). Java Vector Class
14.1). Java Vector Class Constructors
Program – 2
Program – 3
15). Difference between ArrayList and Vector
16). wrapper clas
16.1). Autoboxing
16.2). Unboxing
1
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
1). Java Database Connectivity
JDBC (Java Database Connectivity) is a java API which enables the java programs to execute SQL
statements. It is an application programming interface that defines how a java programmer can
access the database in tabular format from Java code using a set of standard interfaces and
classes written in the Java programming language.
JDBC has been developed under the Java Community Process (JCP) that allows multiple
implementations to exist and be used by the same application. JDBC provides methods for
querying and updating the data in Relational Database Management system such as SQL, Oracle
etc.
The Java application programming interface provides a mechanism for dynamically loading the
correct Java packages and drivers and registering them with the JDBC Driver Manager that is
used as a connection factory for creating JDBC connections which supports creating and executing
statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc
architecture.
In short JDBC helps the programmers to write java applications that manage these three
programming activities:
The primary function of the JDBC API is to provide a means for the developer to issue SQL
statements and process the results in a consistent, database-independent manner. JDBC provides
rich, object-oriented access to databases by defining classes and interfaces.
2
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
The JDBC API supports both two-tier and three-tier processing models for database access.
In the two-tier model, a Java application talks directly to the data source. This requires a JDBC
driver that can communicate with the particular data source being accessed. A user's commands
are delivered to the database or other data source, and the results of those statements are sent
back to the user. The data source may be located on another machine to which the user is
connected via a network. This is referred to as a client/server configuration, with the user's
machine as the client, and the machine housing the data source as the server. The network can be
an intranet, which, for example, connects employees within a corporation, or it can be the Internet.
In the three-tier model, commands are sent to a "middle tier" of services, which then sends the
commands to the data source. The data source processes the commands and sends the results back
to the middle tier, which then sends them to the user. MIS directors find the three-tier model very
attractive because the middle tier makes it possible to maintain control over access and the kinds
of updates that can be made to corporate data. Another advantage is that it simplifies the
deployment of applications. Finally, in many cases, the three-tier architecture can provide
performance advantages.
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
Before you can create a java jdbc connection to the database, you must first import the
java.sql package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be
imported.
There are following six steps involved in building a JDBC application:
1). 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.
2). Register the JDBC driver: Requires that you initialize a driver so you can open a
communications channel with the database.
4). Execute a query: Requires using an object of type Statement for building and submitting an
SQL statement to the database.
5). Extract data from result set: Requires that you use the appropriate
ResultSet.getXXX() method to retrieve the data from the result set.
6). Clean up the environment: Requires explicitly closing all database resources versus relying
on the JVM's garbage collection.
The type 4 driver is written completely in Java and is hence platform independent. It is
installed inside the Java Virtual Machine of the client.
It 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.
MySQL's Connector driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers. Oracle thin driver -
oracle.jdbc.driver. OracleDriver which connect to jdbc:oracle:thin URL format.
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
Statement Use for general-purpose access to your database. Useful when you are using
static SQL statements at runtime. The Statement interface cannot accept
parameters.
This statement will allow to move in only one direction (From BOF to
EOF), you cannot move reverse in records. Means once you are on 5th
record, you cannot move back to record number 4,2,1 or 3.
To make it possible pass following static parameters to method
st=con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
PreparedStatement Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use when you want to access database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
8). Executing a SQL statement with the Statement object, and returning a jdbc resultSet
Statement interface defines methods that are used to interact with database via the execution of
SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is
executeQuery . For statements that create or modify tables, the method to use is executeUpdate.
Note: Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
8
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forwards and backwards, and the
result set is not sensitive to changes made by others to
the database that occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forwards and backwards, and the
result set is sensitive to changes made by others to the
database that occur after the result set was created.
Program 1: This program will use the table Mark which is created in Microsoft Access. It has fields
like Roll Number (Numeric), Student Name (Text), Mark 1 (Numeric), Mark 2 (Numeric) and Mark
3 (Numeric). This program will continue throughout this chapter with addition of facilities and
functionality.
// import the package that contains all classes and packages for JDBC
import java.sql.*;
class Student
{
Connection con;
Statement st;
PreparedStatement ps;
ResultSet rs;
String sNo,sNm,sM1,sM2,sM3;
Student() throws Exception
{
// Load the JDBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Create connection using myDSN
con=DriverManager.getConnection("jdbc:odbc:myDSN");
// Create statement on above connection
st=con.createStatement();
}
void disp() throws Exception
{
// Fetch all the data into result set from table Mark
rs=st.executeQuery("select * from Mark");
// Traverse in data until rs.next() returns false (means upto EOF)
while(rs.next())
{
// Read first Integer field using getInt(Field Number) method
// Convert numeric integer data into String member
sNo = new Integer(rs.getInt(1)).toString();
// Read second Text data using getString(Field Number) method
sNm = rs.getString(2);
// Read Integer field mark 1 using getInt(Field Number) method
9
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
sM1 = new Integer(rs.getInt(3)).toString();
// Read Integer field mark 2 using getInt(Field Number) method
sM2 = new Integer(rs.getInt(4)).toString();
// Read Integer field mark 3 using getInt(Field Number) method
sM3 = new Integer(rs.getInt(5)).toString();
// Displaying first Record
System.out.println("RollNO : "+sNo);
System.out.println("Name : "+sNm);
System.out.println("Mark 1 :"+sM1);
System.out.println("Mark 2 :"+sM2);
System.out.println("Mark 3 :"+sM3);
System.out.println();
}
}
}
class dbDemo
{ public static void main(String args[]) throws Exception
{ Student s = new Student();
s.disp();
}
}
This program will display following output (as per the data entered). It will generate
java.sql.SQLException if anything goes wrong with code.
Output:
RollNO : 1
Name : abcd
Mark 1 :25
Mark 2 :30
Mark 3 :35
RollNO : 2
Name : xyz
Mark 1 :39
Mark 2 :31
Mark 3 :30
RollNO : 3
Name : pqr
Mark 1 :24
Mark 2 :29
Mark 3 :28
10
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
10). List Interface in Java
The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which
duplicate values can be stored. Since List preserves the insertion order, it allows positional access
and insertion of elements. List Interface is implemented by the classes of ArrayList, LinkedList,
Vector and Stack.
2. Search:
List provides methods to search element and returns its numeric position. Following two
methods are supported by List for this operation:
int indexOf(Object o): This method returns first occurrence of given element or -1 if
element is not present in list.
int lastIndexOf(Object o): This method returns the last occurrence of given element or -
1 if element is not present in list
3. Iteration:
ListIterator(extends Iterator) is used to iterate over List element. List iterator is
bidirectional iterator. For more details about ListIterator refer Iterators in Java.
4. Range-view:
List Interface provides a method to get the List view of the portion of given List between
two indices.
11
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
5. By forEach() method.
6. By forEachRemaining() method.
12
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
class ArrayList2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
13.2). Iterating Collection through the for-each loop
Let's see an example to traverse the ArrayList elements using the for-each loop
import java.util.*;
class ArrayList3{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing list through for-each loop
for(String obj:al)
System.out.println(obj);
}
}
Vector is very useful if we don't know the size of an array in advance or we need one that can
change the size over the lifetime of a program.
Vector implements a dynamic array that means it can grow or shrink as required. It is similar to
the ArrayList, but with two differences-
Vector is synchronized.
The vector contains many legacy methods that are not the part of a collections framework
13
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
capacityIncrement) specified initial capacity and capacity
increment.
4 Vector( Collection<? extends E> c) It constructs a vector that contains the
elements of a collection c.
Example:
import java.util.*;
public class VectorExample1 {
public static void main(String args[]) {
//Create an empty vector with initial capacity 4
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
System.out.println("Vector element is: "+vec);
}
}
Program 2: to Add element, check size, capacity and element present or not in Vector.
import java.util.*;
public class VectorExample1 {
public static void main(String args[]) {
//Create an empty vector with initial capacity 4
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Check size and capacity
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
//Display Vector elements
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Again check size and capacity after two insertions
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
//Display Vector elements again
System.out.println("Elements are: "+vec);
//Checking if Tiger is present or not in this vector
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
14
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
}
}
Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer
Program 3: Remove first occurrence of element, remove indexed element in vector. Also
display Hash Code of Vector and get element from specific index.
import java.util.*;
public class VectorExample2 {
public static void main(String args[]) {
//Create an empty Vector
Vector < Integer > in = new Vector < > ();
//Add elements in the vector
in.add(100);
in.add(200);
in.add(300);
in.add(200);
in.add(400);
in.add(500);
in.add(600);
in.add(700);
//Display the vector elements
System.out.println("Values in vector: " +in);
//use remove() method to delete the first occurence of an element
System.out.println("Remove first occourence of element 200:
"+in.remove((Integer)200));
//Display the vector elements afre remove() method
System.out.println("Values in vector: " +in);
//Remove the element at index 4
System.out.println("Remove element at index 4: " +in.remove(4));
System.out.println("New Value list in vector: " +in);
//Remove an element
in.removeElementAt(5);
//Checking vector and displays the element
System.out.println("Vector element after removal: " +in);
//Get the hashcode for this vector
System.out.println("Hash code of this vector = "+in.hashCode());
15
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
//Get the element at specified index
System.out.println("Element at index 1 is = "+in.get(1));
}
}
Output:
Values in vector: [100, 200, 300, 200, 400, 500, 600, 700]
Remove first occourence of element 200: true
Values in vector: [100, 300, 200, 400, 500, 600, 700]
Remove element at index 4: 500
New Value list in vector: [100, 300, 200, 400, 600, 700]
Vector element after removal: [100, 300, 200, 400, 600]
Hash code of this vector = 130123751
Element at index 1 is = 300
ArrayList and Vector both implements List interface and maintains insertion order.
However, there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
ArrayList increments 50% of current array Vector increments 100% means doubles the
size if the number of elements exceeds from array size if the total number of elements
its capacity. exceeds than its capacity.
ArrayList uses the Iterator interface to A Vector can use the Iterator interface
traverse the elements. or Enumeration interface to traverse the
elements.
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
16). wrapper class:
Each of Java's eight primitive data types has a class dedicated to it.
These are known as wrapper classes, because they "wrap" the primitive data type into an
object of that class.
The wrapper classes are part of the java.lang package, which is imported by default into all
Java programs.
The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.
Primitive Type Wrapper class Primitive Type Wrapper class
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is
known as autoboxing and vice-versa unboxing.
16.1). Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and short to Short.
Wrapper class Example: Primitive to Wrapper (Converting int into Integer )
//Java program to convert primitive into objects //Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}
16.2). Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue()
method of wrapper classes to convert the wrapper type into primitives.
17