0% found this document useful (0 votes)
37 views

Advance Java

This document outlines the key concepts of Java Database Connectivity (JDBC), including its four main components, architecture, driver types, and basic steps for connecting to a database. JDBC provides a standard interface for connecting Java applications to various database systems, and uses driver managers and drivers to dynamically connect to the appropriate database. The document discusses the two-tier and three-tier JDBC architectures, and the four main types of JDBC drivers.

Uploaded by

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

Advance Java

This document outlines the key concepts of Java Database Connectivity (JDBC), including its four main components, architecture, driver types, and basic steps for connecting to a database. JDBC provides a standard interface for connecting Java applications to various database systems, and uses driver managers and drivers to dynamically connect to the appropriate database. The document discusses the two-tier and three-tier JDBC architectures, and the four main types of JDBC drivers.

Uploaded by

Jaimin Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

B.C.A.

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:

1. It helps us to connect to a data source, like a database.


2. It helps us in sending queries and updating statements to the database
3. Retrieving and processing the results received from the database in terms of answering query.

2). JDBC has four Components:


1. The JDBC API: The JDBC API provides programmatic access to relational data from the Java
programming language.
The JDBC API is part of the Java platform, which includes the Java Standard Edition (Java
SE) and the Java Enterprise Edition (Java EE). The JDBC 4.0 API is divided into two
packages: java.sqland javax.sql. Both packages are included in the Java SE and Java EE
platforms.
2. JDBC Driver Manager: The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver.
3. JDBC Test Suite — The JDBC driver test suite helps you to determine that JDBC drivers will
run your program
4. JDBC-ODBC Bridge — The Java Software bridge provides JDBC access via ODBC drivers. Note
that you need to load ODBC binary code onto each client machine that uses this driver. As a
result, the ODBC driver is most appropriate on a corporate network where client
installations are not a major problem, or for application server code written in Java in a
three-tier architecture.

3). JDBC Architecture

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.

3.1). JDBC two-tier Architecture

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.

3.2). JDBC three-tier Architecture

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)

4). Java Database Connectivity Steps

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.

3). Open a connection: Requires using the DriverManager.getConnection()method to create a


Connection object, which represents a physical connection 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.

5). JDBC Driver


Driver types are used to categorize the technology used to connect to the database. A JDBC driver
vendor uses these types to describe how their product operates. Some JDBC driver types are better
suited for some applications than others. The driver class can be load by calling Class.forName()
with the Driver class name as an argument. Once loaded, the Driver class creates an instance of
itself. A client can connect to Database Server through JDBC Driver. Since most of the Database
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in
java.lang package.
try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
}
catch(Exception x){
System.out.println( “Unable to load the driver class!” );
}
Types of JDBC drivers
1. JDBC-ODBC bridge plus ODBC driver, also called Type 1.
2. Native-API, partly Java driver, also called Type 2.
3. JDBC-Net, pure Java driver, also called Type 3.
4. Native-protocol, pure Java driver, also called Type 4.

5.1). TYPE – 1: JDBC-ODBC Bridge


 This driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java
2 SDK, Standard Edition. Type 1 is the simplest of all but platform specific i.e only to Microsoft
platform.
 This driver converts JDBC method calls into ODBC function calls. Type 1 drivers are written in
Native code.
 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.

5.2). TYPE – 2 JDBC-Native API or Native 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.
 This type of driver converts JDBC calls into calls to the client API for that database.
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)
 The native API should change if the Database is changed because it is specific to a database.
Some speed increase and provides more functionality and performance than the type 1 with a
Type 2 driver, because it eliminates ODBC's overhead.
 The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

5.3). Type 3: JDBC-Net pure Java or Middleware Driver


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

5.4). TYPE – 4: Native-protocol or Pure Java driver or Pure Driver

 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)

6). JDBC Connection


The JDBC DriverManager class defines objects which can connect Java applications to a JDBC
driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class
manages the JDBC drivers that are installed on the system. Its getConnection() method is used to
establish a connection to a database. It uses a username, password, and a jdbc url to establish a
connection to the database and returns a connection object. A jdbc Connection represents a
session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL
statements are executed and results are returned. An application can have one or more
connections with a single database, or it can have many connections with different databases. A
Connection object provides metadata i.e. information about the database, tables, and fields. It also
contains methods to deal with transactions.

JDBC URL Example:: jdbc: <subprotocol>: <subname>

• Each driver has its own subprotocol


• Each subprotocol has its own syntax for the source. We’re using the jdbc odbc subprotocol,
so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.
try{
Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}
catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}

7). JDBC Statement object


Once a connection is obtained we can interact with the database. Connection interface defines
methods for interacting with the database via the established connection. To execute SQL
statements, you need to instantiate a Statement object from your connection object by using the
createStatement() method.
Statement statement = dbConnection.createStatement();
A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements


 They also define methods that help bridge data type differences between Java and SQL data
types used in a database.
 Following table provides a summary of each type of statements.
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)

Interfaces Recommended Use

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.

Statement st=con.createStatement(); // con is Connection object

 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.

9). JDBC Result Sets


 The SQL statements that read data from a database query return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a result
set.
 A ResultSet object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.
 The next() method is used to successively step through the rows of the tabular results.

9.1). Type of ResultSet:


 The possible result set type are given below, If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.

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.

10.1). Operations on List:


List Interface extends Collection, hence it supports all the operations of Collection Interface, along
with following additional operations:
1. Positional Access:
List allows add, remove, get and set operations based on numerical positions of elements in
List. List provides following methods for these operations:
void add(int index, This method adds given element at specified index.
Object O):
boolean addAll(int This method adds all elements from specified collection to list. First
index, Collection c): element gets inserted at given index. If there is already an element at
that position, that element and other subsequent elements(if any) are
shifted to the right by increasing their index.
Object remove(int This method removes an element from the specified index. It shifts
index): subsequent elements(if any) to left and decreases their indexes by 1.
Object get(int index): This method returns element at the specified index
Object set(int index, This method replaces element at given index with new element. This
Object new): function returns the element which was just replaced by new
element.

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). Java ArrayList class


Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.

The important points about Java ArrayList class are:


 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 occur if any
element is removed from the array list.

11
B.C.A. Semester – V
US05CBCA25 : Object Oriented Programming –III
(Syllabus Effective from June 2020)

11.1). Constructors of Java ArrayList


Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection<? extends E> c) It is used to build an array list that is initialized with the
elements of the collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial
capacity.

11.2). Declaration of ArrayList


ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

Java ArrayList Example


import java.util.*;
class ArrayList1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("ABC"); //Adding object in arraylist
list.add("PQR");
list.add("XYZ");
System.out.println(list); //Invoking arraylist object
} } }

12). Java Iterator interface


 An iterator is an interface that is used in place of Enumerations in the Java Collection
Framework. Moreover, an iterator differs from the enumerations in two ways:
 Iterator interface is a member connected with Java Collections Framework.
 Iterator permits the caller to remove the given elements from the specified collection
during the iteration of the elements.
Methods Description
forEachRemaining(Consumer<? Performs the given action on each of the element
super E>action)
hasNext() Returns a true value if the more number of elements are
encountered during iteration.
next() Returns the next specified element during the iteration.
remove() Removes the last element from the collection as provided by
the iterator.

13). Ways to iterate the elements of the collection in java


There are various ways to traverse the collection elements:

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.

13.1). Iterating Collection through Iterator interface


Let's see an example to traverse ArrayList elements using the Iterator interface.
import java.util.*;

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);
}
}

14). Java Vector Class


Java Vector class comes under the java.util package. The vector class implements a growable array
of objects. Like an array, it contains the component that can be accessed using an integer index.

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

14.1). Java Vector Class Constructors


Vector class supports four types of constructors. These are:
SN Constructor Description
1 vector() It constructs an empty vector with the default
size as 10.
2 vector(int initialCapacity) It constructs an empty vector with the
specified initial capacity and with its capacity
increment equal to zero.
3 vector(int initialCapacity, int It constructs an empty vector with the

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

15). Difference between ArrayList and Vector

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 is not synchronized. Vector is synchronized.

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 is not a legacy class. It is Vector is a legacy class.


introduced in JDK 1.2.

ArrayList is fast because it is non- Vector is slow because it is synchronized, i.e., in


synchronized. a multithreading environment, it holds the other
threads in runnable or non-runnable state until
current thread releases the lock of the object.

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

boolean Boolean int Integer

char Character long Long

byte Byte float Float

short Short double Double

 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.

Wrapper class Example: Wrapper to Primitive (Converting Integer to int)


//Java program to convert object into primitives //Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}

17

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy