Cb2305 Ajp - Unit 5
Cb2305 Ajp - Unit 5
Introduction:
1. An array is an indexed collection of fixed no of homogeneous data elements. (or)
2. An array represents a group of elements of same data type.
3. The main advantage of array is we can represent huge no of elements by using
single variable. So that readability of the code will be improved.
Example:
Student[] s=new Student[10000];
s[0]=new Student();//valid
s[1]=new Customer();//invalid(compile time error)
Compile time error:
Test.java:7: cannot find symbol
Symbol: class Customer
Location: class Test
s[1]=new Customer();
4) Arrays concept is not implemented based on some data structure hence ready-made
methods support we can't expert. For every requirement we have to write the code
explicitly.
Let us see the hierarchy of Collection framework. The java.util package contains all the
classes and interfaces for the Collection framework.
There are many methods declared in the Collection interface. They are as follows:
No Method Description
.
8 public void clear() It removes the total number of elements from the
collection.
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
runtime type of the returned array is that of the
specified array.
19 public int hashCode() It returns the hash code number of the collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
No Method Description
.
1 public boolean It returns true if the iterator has more elements otherwise it
hasNext() returns false.
2 public Object next() It returns the element and moves the cursor pointer to the
next element.
3 public void remove() It removes the last elements returned by the iterator. It is
less used.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection interface
also implement the Iterable interface.
1. Iterator<T> iterator()
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll
( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.
Differences between Arrays and Collections
Arrays Collections
2) Memory point of view arrays are not 2) Memory point of view collections are highly
recommended to use. recommended to use.
3) Performance point of view arrays are 3) Performance point of view collections are not
recommended to use. recommended to use.
4) Arrays can hold only homogeneous 4) Collections can hold both homogeneous and
data type elements. heterogeneous elements.
Collection framework:
It defines several classes and interfaces to represent a group of objects as a single entity.
List:
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects as a single entity where
"duplicates are allow and insertion order must be preserved" then we should go
for List interface.
Diagram:
Set:
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects as single entity "where
duplicates are not allow and insertion order is not preserved" then we should go
for Set interface.
Diagram:
SortedSet:
1. It is the child interface of Set.
2. If we want to represent a group of individual objects as single entity "where
duplicates are not allow but all objects will be insertion according to some sorting
order then we should go for SortedSet.
(or)
3. If we want to represent a group of "unique objects" according to some sorting
order then we should go for SortedSet.
NavigableSet:
1. It is the child interface of SortedSet.
2. It provides several methods for navigation purposes.
Queue:
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects prior to processing then we
should go for queue concept.
Diagram:
Note: All the above interfaces (Collection, List, Set, SortedSet, NavigableSet, and
Queue) meant for representing a group of individual objects.
If we want to represent a group of objects as key-value pairs then we should go for Map.
Map:
1. Map is not child interface of Collection.
2. If we want to represent a group of objects as key-value pairs then we should go for
Map interface.
3. Duplicate keys are not allowed but values can be duplicated.
Diagram:
SortedMap:
NavigableMap:
1) It is the child interface of SortedMap and defines several methods for navigation
purposes.
Collection interface:
If we want to represent a group of individual objects as a single entity then we
should go for Collection interface. This interface defines the most common general
methods which can be applicable for any Collection object.
The following is the list of methods present in Collection interface.
ArrayList:
1. The underlying data structure is resizable array (or) growable array.
2. Duplicate objects are allowed.
3. Insertion order preserved.
4. Heterogeneous objects are allowed.(except TreeSet , TreeMap every where
heterogenious objects are allowed)
5. Null insertion is possible.
Constructors:
1) ArrayList a=new ArrayList();
Creates an empty ArrayList object with default initial capacity "10" if ArrayList
reaches its max capacity then a new ArrayList object will be created with
New capacity=(current capacity*3/2)+1
2) ArrayList a=new ArrayList(int initialcapacity);
Creates an empty ArrayList object with the specified initial capacity.
3) ArrayList a=new ArrayList(collection c);
Creates an equivalent ArrayList object for the given Collection that is this constructor
meant for inter conversation between collection objects. That is to dance between
collection objects.
Usually we can use collection to hold and transfer objects from one tier to another
tier. To provide support for this requirement every Collection class already
implements Serializable and Cloneable interfaces.
ArrayList and Vector classes implements RandomAccess interface so that any
random element we can access with the same speed. Hence ArrayList is the best
choice of "retrival operation".
RandomAccess interface present in util package and doesn't contain any methods.
It is a marker interface.
Example
Diagram:
LinkedList:
1. The underlying data structure is double LinkedList
2. If our frequent operation is insertion (or) deletion in the middle then LinkedList is
the best choice.
3. If our frequent operation is retrieval operation then LinkedList is worst choice.
4. Duplicate objects are allowed.
5. Insertion order is preserved.
6. Heterogeneous objects are allowed.
7. Null insertion is possible.
8. Implements Serializable and Cloneable interfaces but not RandomAccess.
Diagram:
Example:
import java.util.*;
class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("ashok");
l.add(30);
l.add(null);
l.add("ashok");
System.out.println(l);//[ashok, 30, null, ashok]
l.set(0,"software");
System.out.println(l);//[software, 30, null,ashok]
l.set(0,"venky");
System.out.println(l);//[venky, 30, null, ashok]
l.removeLast();
System.out.println(l);//[venky, 30, null]
l.addFirst("vvv");
System.out.println(l);//[vvv, venky, 30, null]
}
}
HashSet:
1. The underlying data structure is Hashtable.
2. Insertion order is not preserved and it is based on hash code of the objects.
3. Duplicate objects are not allowed.
4. If we are trying to insert duplicate objects we won't get compile time error and
runtime error add() method simply returns false.
5. Heterogeneous objects are allowed.
6. Null insertion is possible.(only once)
7. Implements Serializable and Cloneable interfaces but not RandomAccess.
8. HashSet is best suitable, if our frequent operation is "Search".
Constructors:
1. HashSet h=new HashSet();
Creates an empty HashSet object with default initial capacity 16 and default fill
ratio 0.75(fill ratio is also known as load factor).
2. HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet object with the specified initial capacity and default fill
ratio 0.75.
3. HashSet h=new HashSet(int initialcapacity,float fillratio);
4. HashSet h=new HashSet(Collection c);
Note : After filling how much ratio new HashSet object will be created , The ratio is called
"FillRatio" or "LoadFactor".
Example:
import java.util.*;
class HashSetDemo
{
public static void main(String[] args)
{
HashSet h=new HashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z"));//false
System.out.println(h);//[null, D, B, C, 10, Z]
}
}
LinkedHashSet:
1. It is the child class of HashSet.
2. LinkedHashSet is exactly same as HashSet except the following differences.
HashSet LinkedHashSet
In the above program if we are replacing HashSet with LinkedHashSet the output is [B, C,
D, Z, null, 10].That is insertion order is preserved.
Example:
import java.util.*;
class LinkedHashSetDemo
{
public static void main(String[] args)
{
LinkedHashSet h=new LinkedHashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z"));//false
System.out.println(h);//[B, C, D, Z, null, 10]
}
}
Note: LinkedHashSet and LinkedHashMap commonly used for implementing "cache
applications" where insertion order must be preserved and duplicates are not allowed.
SortedSet:
1. It is child interface of Set.
2. If we want to represent a group of "unique objects" where duplicates are not
allowed and all objects must be inserting according to some sorting order then we
should go for SortedSet interface.
3. That sorting order can be either default natural sorting (or) customized sorting
order.
SortedSet interface define the following 6 specific methods.
1. Object first();
2. Object last();
3. SortedSet headSet(Object obj);
Returns the SortedSet whose elements are <obj.
4. SortedSet tailSet(Object obj);
It returns the SortedSet whose elements are >=obj.
5. SortedSet subset(Object o1,Object o2);
Returns the SortedSet whose elements are >=o1 but <o2.
6. Comparator comparator();
o Returns the Comparator object that describes underlying sorting technique.
o If we are following default natural sorting order then this method returns
null.
Diagram:
TreeSet:
1. The underlying data structure is balanced tree.
2. Duplicate objects are not allowed.
3. Insertion order is not preserved and it is based on some sorting order of objects.
4. Heterogeneous objects are not allowed if we are trying to insert heterogeneous
objects then we will get ClassCastException.
5. Null insertion is possible(only once).
Constructors:
1. TreeSet t=new TreeSet();
Creates an empty TreeSet object where all elements will be inserted according to
default natural sorting order.
2. TreeSet t=new TreeSet(Comparator c);
Creates an empty TreeSet object where all objects will be inserted according to
customized sorting order specified by Comparator object.
3. TreeSet t=new TreeSet(SortedSet s);
4. TreeSet t=new TreeSet(Collection c);
Example 1:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add("A");
t.add("a");
t.add("B");
t.add("Z");
t.add("L");
//t.add(new Integer(10));//ClassCastException
//t.add(null);//NullPointerException
System.out.println(t);//[A, B, L, Z, a]
}
}
Null acceptance:
For the empty TreeSet as the 1st element "null" insertion is possible but after
inserting that null if we are trying to insert any other we will get
NullPointerException.
For the non empty TreeSet if we are trying to insert null then we will get
NullPointerException.
Example 2:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("L"));
t.add(new StringBuffer("B"));
System.out.println(t);
}
}
Output:
Runtime Exception.
Note :
Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuffer
cannot be cast to java.lang.Comparable
If we are depending on default natural sorting order compulsory the objects should
be homogeneous and Comparable otherwise we will get ClassCastException.
An object is said to be Comparable if and only if the corresponding class
implements Comparable interface.
String class and all wrapper classes implements Comparable interface but
StringBuffer class doesn't implement Comparable interface hence in the above
program we are getting ClassCastException.
EnumSet in Java
Enumerations or popularly known as enum serve the purpose of representing a group of
named constants in a programming language. For example, the 4 suits in a deck of playing
cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an
enumerated type named Suit.
The EnumSet is one of the specialized implementations of the Set interface for use with
the enumeration type. A few important features of EnumSet are as follows:
It extends AbstractSet class and implements Set Interface in Java.
EnumSet class is a member of the Java Collections Framework & is not synchronized.
It’s a high-performance set implementation, much faster than HashSet.
All of the elements in an EnumSet must come from a single enumeration type that is
specified when the set is created either explicitly or implicitly.
It does not allow null Objects and throws NullPointerException if we do so.
It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the
collection is modified while iterating.
↳ java.util.AbstractCollection<E>
java.lang.Object
↳ java.util.AbstractSet<E>
↳ java.util.EnumSet<E>
Here, E is the type of elements stored.
Syntax: Declaration
public abstract class EnumSet<E extends Enum<E>>
Here, E specifies the elements. E must extend Enum, which enforces the requirement that
the elements must be of the specified enum type.
Methods of EnumSet
Method Action Performed
Creates an enum set with the same element type as the specified
complementOf
enum set, initially containing all the elements of this type that are
(EnumSet<E> s)
not contained in the specified set.
copyOf
Creates an enum set initialized from the specified collection.
(Collection<E> c)
Method Action Performed
copyOf Creates an enum set with the same element type as the specified
(EnumSet<E> s) enum set, initially containing the same elements (if any).
noneOf(Class<E>
Creates an empty enum set with the specified element type.
elementType)
of(E e1, E e2) Creates an enum set initially containing the specified elements.
of(E first, E… rest) Creates an enum set initially containing the specified elements.
of(E e1, E e2, E e3) Creates an enum set initially containing the specified elements.
// Enum
enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ };
// Main class
// EnumSetExample
public class GFG {
// Creating a set
EnumSet<Gfg> set1, set2, set3, set4;
// Adding elements
set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
Gfg.LEARN, Gfg.CODE);
set2 = EnumSet.complementOf(set1);
set3 = EnumSet.allOf(Gfg.class);
set4 = EnumSet.range(Gfg.CODE, Gfg.CONTRIBUTE);
Output
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]
Set 2: [MCQ]
Set 3: [CODE, LEARN, CONTRIBUTE, QUIZ, MCQ]
Set 4: [CODE, LEARN, CONTRIBUTE]
3 cursors of java:
If we want to get objects one by one from the collection then we should go for cursor.
There are 3 types of cursors available in java. They are:
1. Enumeration
2. Iterator
3. ListIterator
Enumeration:
1. We can use Enumeration to get objects one by one from the legacy collection
objects.
2. We can create Enumeration object by using elements() method.
public Enumeration elements();
Enumeration e=v.elements();
using Vector Object
Example:
import java.util.*;
class EnumerationDemo
{
public static void main(String[] args)
{
Vector v=new Vector();
for(int i=0;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v);//[0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10]
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
if(i%2==0)
System.out.println(i);//0 2 4 6 8 10
}
System.out.print(v);//[0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10]
}
}
Limitations of Enumeration:
1. We can apply Enumeration concept only for legacy classes and it is not a universal
cursor.
2. By using Enumeration we can get only read access and we can't perform remove
operations.
3. To overcome these limitations sun people introduced Iterator concept
in 1.2v.
Iterator:
1. We can use Iterator to get objects one by one from any collection object.
2. We can apply Iterator concept for any collection object and it is a universal cursor.
3. While iterating the objects by Iterator we can perform both read and remove
operations.
Example:
import java.util.*;
class IteratorDemo
{
public static void main(String[] args)
{
ArrayList a=new ArrayList();
for(int i=0;i<=10;i++)
{
a.add(i);
}
System.out.println(a);//[0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10]
Iterator itr=a.iterator();
while(itr.hasNext())
{
Integer i=(Integer)itr.next();
if(i%2==0)
System.out.println(i);//0, 2, 4, 6,
8, 10
else
itr.remove();
}
System.out.println(a);//[0, 2, 4, 6, 8, 10]
}
}
Limitations of Iterator:
1. Both enumeration and Iterator are single direction cursors only. That is we can
always move only forward direction and we can't move to the backward direction.
2. While iterating by Iterator we can perform only read and remove operations and
we can't perform replacement and addition of new objects.
3. To overcome these limitations sun people introduced listIterator concept.
ListIterator:
Example:
import java.util.*;
class ListIteratorDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("balakrishna");
l.add("venki");
l.add("chiru");
l.add("nag");
System.out.println(l);//[balakrishna, venki,
chiru, nag]
ListIterator itr=l.listIterator();
while(itr.hasNext())
{
String s=(String)itr.next();
if(s.equals("venki"))
{
itr.remove();
}
}
System.out.println(l);//[balakrishna, chiru, nag]
}
}
Case 1:
if(s.equals("chiru"))
{
itr.set("chran");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chran, nag]
Case 2:
if(s.equals("nag"))
{
itr.add("chitu");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chiru, nag, chitu]
The most powerful cursor is listIterator but its limitation is it is applicable only for "List
objects".
While using nested for loops it is better to use for-each loop, consider the below code for
better understanding.
import java.util.*;
Output:
In the above code we are calling the next() method again and again for itr1 (i.e., for List l).
Now we are advancing the iterator without even checking if it has any more elements left in
the collection(in the inner loop), thus we are advancing the iterator more than the number of
elements in the collection which leads to NoSuchElementException.
for-each loops are tailor made for nested loops. Replace the iterator code with the below
code.
// Java program to demonstrate working of nested for-each
import java.util.*;
public class Main
{
public static void main(String args[])
{
// Create a link list which stores integer elements
List<Integer> l=new LinkedList<Integer>();
Output:
22233344
for(Customer c : arr)
System.out.println(c);
}
}
getOrDefault(Object key, Returns the value to which the specified key is mapped, or
V defaultValue) defaultValue if this map contains no mapping for the key
import java.util.*;
// Main class
class GFG {
// Printing keys
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
}
Output:
a:100
b:200
c:300
d:400
AutoBoxing
Wrapper class: It is a class that encapsulates, or "wraps," a primitive data type, allowing it to
be treated as an object.
AutoBoxing / Boxing : Boxing refers to the process of converting a primitive data type into
its corresponding wrapper class object.
UnBoxing : Unboxing is the process of extracting the primitive value from a wrapper class
object.
Example Program
public class AutoBoxingExample {
public static void main(String[] args) {
// Auto boxing: int to Integer
int primitiveInt = 42;
Integer wrapperInt = primitiveInt;
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 mentioned below that are commonly associated with
database usage.
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
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 databaseindependent code. For this purpose, we need an API (Application programming
interface) that ODBC (Open Database Connectivity).
The ODBC API was the database API to connect and execute queries with the database. But,
ODBC API uses ODBC driver written in C Language (platform dependent and unsecured).
That is why Java has defined its own API, called JDBC (Java Database Connectivity ), that uses
JDBC drivers ( Written in Java language )
The JDBC drivers are more compatible with Java applications to provide database
Communications.
JDBC is a Java API to connect and execute queries with the database. JDBC API uses JDBC
drivers to connect with the database.
JDBC supports a Wide level of portability, and JDBC is simple and easy to use.
In JDBC API, a programmer needs a specific driver to Connect to a specific database.
RDBMS Driver
Oracle Oracle.jdbc.driver.OracleDriver
MySQL Com.mysql.jdbc.Driver
SyBase Com.microsoft.jdbc.sqlserver
SQLServer Com.microsft.jdbc.Sqlserver
DB2 Com.ibm.db2.jdbc.net.DB2Driver
List of some popular Drivers
JDBC Architecture
The main function of the JDBC is to provide a standard obstruction for Java applications to
communicate with the database.
As shown in the figure, the Java application that wants to communicate with a database has to be
programmed using JDBC API.
The JDBC Driver is required to process the SQL requests and generate the results.
The JDBC driver has to play an essential role in the JDBC architecture. The Driver Manager
uses the same specific drivers to connect with specific databases effectively.
JDBC Driver is a software component that enables Java applications to interact with the database.
The Type-1 driver acts as a bridge between JDBC and other database connectivity mechanisms such
as ODBC.
The JDBC - ODBC bridge driver converts JDBC method calls into the ODBC method calls.
Advantages
Easy to use
Can be easily connected to any database.
Disadvantages
Performance degraded because of a large number of transactions (i.e. JDBC calls to ODBC
calls)
The ODBC driver needs to be installed on the client machine.
The type -2 driver uses the client-side libraries of the database. So, this driver is also called as Native -
API driver.
This driver converts JDBC method calls into native calls of the database API. It is not written entirely
in Java, so it is called as partial JDBC driver.
Native API Driver
Advantages:
Disadvantages:
The type-3 driver is completely implemented in java; hence it is a pure java JDBC driver.
The type-3 driver uses middleware (application server) that converts JDBC calls directly or indirectly
Advantages:
Disadvantages:
The type-4 driver is a pure Java driver, which converts JDBC calls directly into the vendor-specific
database protocol that is why it is known as thin driver
The Java Thin Server
Advantages
Disadvantage
In other words, we use JDBC connectivity code in Java application to communicate with a database.
There are five steps to connect any Java application with the database in java using JDBC. They are as
follows.
In this step, we register the driver class with driver Manager by using forName () method of Class.
Example: Class.forName(“Oracle.jdbc.driver.OracleDriver”);
In this step, we can create a connection with database server by using getConnection() method of
DriverManager class.
After the connection made, we need to create the statement object to execute the SQL statements.
The CreateStatement() method of the connection interface is used to create a statement. This
statement object is responsible for executing SQL statements with the database.
Syntax: CreateStatement()
After the statement object is created, it can be used to execute the SQL Statements by using
executeUpdate() or executeQuery() method of statement interface.
executeUpdate(String query)
Resultset rs = stmt.executeQuery(query);
// using executeUpdate()
Stmt.executeUpdate(query);
After executing all the SQL statements and obtaining the results, we need to close the connection
and release the session.
Syntax: Close()
Example: con.Close();
For connecting java application with the oracle database, we need to know following information to
perform databse connectivity with oracle.
In this example we are using Oracle log as the database, so we need to know following information
for the oracle database.
Where jdbc is the API oracle is the databse, thin is the driver, localhost is the server name on which
Oracle is running, 1521 is the port number and XE is the oracle service name.
To connect java application with the oracle databse “ojdbc14.jar” file is required to be loaded.
There are two ways to load the “ojdbc14.jar” file, we need to follow any one of two ways.
Firstly, search the “ojdbc14.jar” file then go to “java/jre/lib/ext” folder and paste the jar file here.
(Or)
Set class path: To set classpath, goto environment variable then click on new tab, In variable name
write classpath and in variable value paste the path to “ojdbc14.jar” by appending “ojdbc14.jar”; . ;
as
“C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar; . ;”.
Example:
Let’s first create a table and insert two or more records in oracle database.
Program: Connect java application with Oracle database for selecting or retrieving data.
SelectData.java
import java.sql.*
import java.util.*
class SelectData
try
Class.forName(“Oracle.jdbc.driver.OracleDriver”);
while (rs.next())
System.out.println(rs.getInt() + “ “ + rs.getString(2)+rs.getString(3));
con.Close();
Catch(Exception e) { System.out.println(e);}
Program: Connect Java application with Oracle database for inserting data
Insertdata.java
import java.sql.*;
import java.util.*;
class InsertData
{
public static void main(String args[])
try
Class.forName("Oracle.jdbc.driver.OracleDriver");
System.Out.Println("Inserted...");
con.Close();
catch(Exception e)
System.out.println("Exception is : "+e);
Output:
Inserted....
Updatedata.java
import java.sql.*;
import java.util.*;
class Updatedata
{
try
Class.forName("Oracle.jdbc.driver.OracleDriver");
System.out.println("Update...");
con.Close();
catch(Exception e)
System.out.println("Exception is : "+e);
Output:
Updateted....
The driver manager class acts as an interface between users and drivers. It keeps track of available
drivers and establishes a connection between a database and the appropriate driver.
DAO Class in Java
Data Access Object patterns, often known as DAO patterns, are used to
divide high level business services from low level data accessing APIs or
actions. The members of the Data Access Object Pattern are listed below.
Implementation
A student object will be created and used as a model as well as a value
object.
S.java
1. public class S {
2. private String n;
3. private int r;
4.
5. S(String n, int r){
6. this.n = n;
7. this.r = r;
8. }
9.
10. public String getName() {
11. return n;
12. }
13.
14. public void setName(String n) {
15. this.n = n;
16. }
17.
18. public int getRollNo() {
19. return r;
20. }
21.
22. public void setRollNo(int r) {
23. this.r = r;
24. }
25. }
Step 2:
SD.java
1. import java.util.List;
2. public interface SD {
3. public List<S> getAllStudents();
4. public S getStudent(int r);
5. public void updateStudent(S s);
6. public void deleteStudent(S s);
7. }
Step 3:
SDI.java
1. import java.util.ArrayList;
2. import java.util.List;
3. public class SDI implements SD {
4. // list is working as the database
5. List<S> ss;
6. public SDI(){
7. ss = new ArrayList<S>();
8. S s1 = new S("Sonoo",0);
9. S s2 = new S("Jaiswal",1);
10. ss.add(s1);
11. ss.add(s2);
12. }
13. @Override
14. public void deleteStudent(S s) {
15. students.remove(s.getRollNo());
16. System.out.println(" Student: Roll No " + student.getRollN
o() + ", has been deleted from the database");
17. }
18. // traversing list of students from the database
19. @Override
20. public List<S> getAllStudents() {
21. return ss;
22. }
23. @Override
24. public S getStudent(int r) {
25. return ss.get(r);
26. }
27. @Override
28. public void updateStudent(S s) {
29. ss.get(s.getRollNo()).setName(s.getName());
30. System.out.println(" Student: Roll No " + student.getRollN
o() + ", has been updated in the database");
31. }
32. }
Step 4:
Utilize the StudentDao to illustrate how to use the Data Access Object
pattern.
DPDemo.java
Step 5: