1-Mark Questions
Q1. List down the primary interfaces provided by Java Collections Framework?
The Java Collections Framework provides a set of interfaces that define various operations that can be performed on collections of data. These interfaces include the following:
- Collection: The root interface in the collection hierarchy. A collection represents a group of objects,
known as elements.
- List: An ordered collection (also known as a sequence). Lists may contain
duplicate elements.
- Set: A collection that cannot contain duplicate elements.
- Map: An object
that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
The Java Collections Framework also provides a set of implementations of these interfaces. These implementations include the following:
- ArrayList: A resizable array implementation of the List interface.
- HashSet: A hash table
implementation of the Set interface.
- HashMap: A hash table implementation of the Map interface.
The Java Collections Framework offers a number of benefits, including the following:
- It provides a standard set of interfaces that can be used to access and manipulate collections of
data.
- It provides a set of implementations of these interfaces that offer a wide range of
functionality.
- It enhances the interoperability of collections by allowing them to be used with a
variety of other frameworks and libraries.
Q2. What is Set in Java Collections framework?
A Set is a collection that cannot contain duplicate elements. It models the mathematical set abstraction and is used to represent a finite set of distinct objects.
There are two main implementations of the Set interface: the HashSet class and the TreeSet class. The HashSet class provides an unsorted, unordered set, whereas the TreeSet class provides an ordered set.
The Set interface contains various methods for adding, removing, and testing for the presence of elements in the set. Theadd() method adds an element to the set, if it is not already present, and returns true if the set changed as a result of the call. The remove() method removes an element from the set, if it is present, and returns true if the set changed as a result of the call. The contains() method returns true if the set contains the specified element.
The Set interface also provides a {@link #iterator()} method that returns an {@link java.util.Iterator Iterator} over the elements in the set. This iterator does not guarantee any particular order of the elements in the set.
One example of a Set is a group of people. Each person in the group is distinct, so there are no duplicates. Another example is a deck of cards, where each card is distinct and there are no duplicates.
Q3. In which situation linkedlist is preferred over arraylist.
There are a few key situations when a linked list is the preferred data structure over an array list. First, when you need to insert or delete elements from the middle of the list frequently, linked list outperforms array list because with an array list you would need to shift all subsequent elements over by one index. This can be costly in terms of both time and memory. Linked list simply reassign the pointers in order to insert or delete an element from the middle of the list, so it is much more efficient.
Another reason to choose a linked list over an array list is when you need a data structure that can grow and shrink dynamically. Array lists have a fixed size, so if you need to add an element and the array list is already full, you would need to create a new, larger array list and copy all of the elements over. With a linked list, you can simply add a new node to the end of the list without having to worry about whether there is enough space.
Finally, linked lists use less memory overall than array lists because they don't need to store all of the elements contiguously in memory. Each node in a linked list only needs to store a reference to the next node, so the total memory used is equal to the number of nodes multiplied by the size of a pointer. Array lists, on the other hand, need to store every element in contiguous memory, so the total memory used is equal to the number of elements multiplied by the size of each element. For this reason, linked lists are generally more efficient when working with large amounts of data.
Q4. Write the syntax to execute stored procedures.
A stored procedure is a set of SQL commands that can be stored in a database. They are often used to perform repetitive or complex tasks. stored procedures can take one or more input parameters and return one or more output parameters.
The syntax for executing a stored procedure varies depending on the database server you are using. For example, on Microsoft SQL Server, the syntax is:
EXEC sp_name [parameter1, parameter2, …]
On MySQL, the syntax is:
CALL sp_name([parameter1, parameter2, …])
On Oracle, the syntax is:
EXECUTE sp_name [parameter1, parameter2, …]
On PostgreSQL, the syntax is:
SELECT * FROM sp_executesql ('sp_name', [parameter1, parameter2, …])
So, as you can see, the syntax can vary quite a bit depending on the database server you are using. If you are unsure of the syntax for your particular database server, you can consult the documentation or ask a database administrator.
2-Mark Questions
Q1. List and explain all the JDBC components.
JDBC is a set of Java programming language APIs that provide access to relational databases. JDBC is the Java Database Connectivity. It enables Java applications to connect to any relational database, from which the data can be retrieved, manipulated, and updated.
The JDBC components can be divided into four main groups:
1. The JDBC Driver Manager: This component is responsible for managing the communication between the Java application and the database. It is the first component that needs to be initialized when starting to work with JDBC.
2. The JDBC Drivers: There are different JDBC drivers available, each one designed to work with a specific database management system. The most common ones are the JDBC-ODBC bridge driver and the Native-API driver.
3. The Java Application: This is the component that interacts with the user and manipulates the data stored in the database.
4. The Database: This is where the data is actually stored and manipulated.
Q2. Describe Servlet Architecture.
Servlet architecture refers to the structure of a servlet container, which is the software that runs servlets. A servlet container typically has a hierarchical structure, with a main servlet that dispatches requests to other servlets. The main servlet may be configured to dispatch requests to servlets based on the URL of the request, or it may use other criteria.
Servlets are often organized into groups, with each group responsible for a different task. For example, one group of servlets may handle requests for static content, while another group may handle requests for dynamic content. The main servlet may dispatch requests to servlets in different groups based on the type of request.
Servlets can also be chained together, with each servlet in the chain processing the request and then passing it on to the next servlet in the chain. Chaining is often used to process requests that need to be handled by multiple servlets.
The main servlet is responsible for initializing the servlet container and for loading servlets into the container. The main servlet also handles requests that are not dispatched to any other servlet.
Servlet containers are typically implemented as part of a web server, and they use the server's facilities to handle requests. For example, a servlet container may use the web server's logging facility to log request and response information.
Servlet containers typically provide a way for servlets to share data. For example, a servlet container may provide a global variable that all servlets can access. Servlet containers may also provide a way for servlets to access databases or other external resources.
Q3. Explain Queue Interface.
The Queue Interface is a subtype of the java.util.Collection interface. It defines the basic operations that are required for a data structure to be classified as a queue. In a FIFO (First In First Out) queue, the element that is inserted first is also the first one to be removed.
The Queue interface contains the following methods:
- boolean offer(E e)
- E peek()
- E poll()
- E element()
The offer(E e) method inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
The peek() method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
The poll() method retrieves and removes the head of this queue, or returns null if this queue is empty.
The element() method retrieves, but does not remove, the head of this queue. This method differs from peek only in that it throws an exception if this queue is empty.
A queue may be capacity restricted. When a bounded queue is full, any offer operation will fail. Any attempt to add an element to a full queue will result in the operation throwing an IllegalStateException.
Queue implementations generally do not define element-based versions of the offer and poll methods, but each implementation must document whether it does or not. An unbounded queue may have an arbitrary capacity limit, which means that it may grow to accommodate an arbitrary number of elements.
Q4. What are the benefits of PreparedStatement over Statement?
As a Java programmer, you’ve probably used Statement objects to execute SQL statements. But did you know that there’s another class called PreparedStatement that offers some advantages over Statement? In this article, we’ll take a look at the benefits of PreparedStatement and how it can make your life as a programmer easier.
What is a PreparedStatement?
A PreparedStatement is a special type of Statement that allows you to pre-compile your SQL statement, which can then be executed multiple times with different parameter values. This can be more efficient than using a Statement, since the SQL statement only needs to be compiled once.
Why Use a PreparedStatement?
There are several reasons why you might want to use a PreparedStatement over a Statement. First, as we mentioned before, it can be more efficient since the SQL statement only needs to be compiled once. Second, a PreparedStatement can help protect against SQL injection attacks.
With a Statement, you simply concatenate your SQL statement with the values of your parameters. For example, let’s say you want to insert a new row into a table, and your SQL statement looks like this:
INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)
If you use a Statement object to execute this SQL statement, you would concatenate the values of your parameters into the statement before executing it. So if your parameters were 1, 2, and 3, your resulting SQL statement would look like this:
INSERT INTO table_name (column1, column2, column3) VALUES (1, 2, 3)
However, if one of your parameters was maliciously set to something like “1 OR 1=1”, your resulting SQL statement would look like this:
INSERT INTO table_name (column1, column2, column3) VALUES (1 OR 1=1, 2, 3)
which would insert a row into your table whether or not column1 already had a value of 1. This is how SQL injection attacks work.
But with a PreparedStatement, the parameter values are set separately from the SQL statement. So even if one of the parameter values is maliciously set to “1 OR 1=1”, the resulting SQL statement would still look like this:
INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)
which wouldn’t insert a row into the table unless all three parameters had values of 1.
How to Use a PreparedStatement
Using a PreparedStatement is actually very similar to using a Statement. The main difference is that you use the prepareStatement() method of the Connection object instead of the createStatement() method. For example, the following code creates a PreparedStatement object for our INSERT statement from earlier:
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO
table_name (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement pstmt =
conn.prepareStatement(sql);
Once you have a PreparedStatement object, you can set the values of the parameters using the setXXX() methods. For example, the following code sets the first parameter to 1:
pstmt.setInt(1, 1);
Then you can execute the statement using the executeUpdate() or executeQuery() methods, just as you would with a Statement object.
And that’s all there is to using PreparedStatements! As you can see, they offer some advantages over regular Statements, and they’re not that difficult to use. So next time you need to execute an SQL statement in your Java code, consider using a PreparedStatement instead of a Statement.
4-Mark Questions
Q1. Describe briefly ResultSetMetaData object methods.
ResultSetMetaData is an object that contains information about the data in a ResultSet object. It can be used to get information about the data, such as the data type of each column, the name of the column, and whether or not the column is nullable.
There are several methods that can be used to get information from a ResultSetMetaData object. The most commonly used methods are:
getColumnCount(): This method returns the number of columns in the ResultSet object.
getColumnName(): This method returns the name of the column at the given index.
getColumnType(): This method returns the data type of the column at the given index.
isNullable(): This method returns a boolean value that indicates whether or not the column at the given index is nullable.
Q2. Write a program to demonstrate the List interface using ArrayList classs.
Lists are a very common data structure in programming, and the ArrayList class is one of the most common ways to implement a list in Java. In this post, we'll take a look at how to use the ArrayList class to create and manipulate lists in Java.
ArrayLists are created with a specific initial capacity, which is the number of elements that the ArrayList can hold without having to resize itself. This initial capacity is simply the point at which the ArrayList will have to resize itself to accommodate more elements. The capacity of an ArrayList is the number of elements it can hold without having to resize itself.
You can explicitly set the initial capacity of an ArrayList when you create it, using the ArrayList(int initialCapacity) constructor. If you don't specify an initial capacity, the ArrayList will have a default capacity of 10.
Once an ArrayList has been created, you can add elements to it using the add(E element) method. This method adds the specified element to the end of the ArrayList. You can also add elements at a specific index using the add(int index, E element) method. This method inserts the specified element at the specified index. Note that this shifts any subsequent elements to the right (adds one to their indices).
You can access an element at a specific index using the get(int index) method. This method returns the element at the specified index. You can also use the set(int index, E element) method to replace the element at the specified index with a new element.
The size() method returns the number of elements in the ArrayList, and the isEmpty() method returns true if the ArrayList is empty.
You can remove an element from the ArrayList using the remove(int index) or remove(Object o) methods. The remove(int index) method removes the element at the specified index, while the remove(Object o) method removes the first occurrence of the specified element from the ArrayList. Note that these methods return the removed element.
Finally, the clear() method removes all of the elements from the ArrayList.
That's a quick overview of some of the most common methods in the ArrayList class. In the next section, we'll take a look at an example of how to use an ArrayList in a Java program.
Q3. Create a class Employee with following private members- EmpId, EmpName, Designation, Salary. Insert the details in the Employee table using jdbc. The EmpId will be the combination of three letters from his name in uppercase and 3 digits generated using sequence in sql(Ex. RAK101, MAN102) and rest all the details can be taken from the user or can be passed implicitly. Display the details inserted in the table.
class Employee{
private int EmpId;
private String EmpName;
private String Designation;
private int Salary;
public Employee(int EmpId, String EmpName, String Designation, int Salary){
this.EmpId = EmpId;
this.EmpName = EmpName;
this.Designation = Designation;
this.Salary =
Salary;
}
public int getEmpId(){
return EmpId;
}
public void setEmpId(int EmpId){
this.EmpId = EmpId;
}
public String getEmpName(){
return EmpName;
}
public void setEmpName(String EmpName){
this.EmpName = EmpName;
}
public String getDesignation(){
return Designation;
}
public void setDesignation(String Designation){
this.Designation = Designation;
}
public int getSalary(){
return Salary;
}
public void setSalary(int Salary){
this.Salary = Salary;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee e1 = new Employee(1,"Rakesh","Manager",50000);
Employee e2 = new
Employee(2,"Manish","Developer",40000);
Employee e3 = new Employee(3,"Rahul","Tester",30000);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql1 = "insert into Employee values (?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
ps1.setInt(1,e1.getEmpId());
ps1.setString(2,e1.getEmpName());
ps1.setString(3,e1.getDesignation());
ps1.setInt(4,e1.getSalary());
int i1 = ps1.executeUpdate();
String sql2 = "insert into Employee values (?,?,?,?)";
PreparedStatement ps2 = con.prepareStatement(sql2);
ps2.setInt(1,e2.getEmpId());
ps2.setString(2,e2.getEmpName());
ps2.setString(3,e2.getDesignation());
ps2.setInt(4,e2.getSalary());
int i2 = ps2.executeUpdate();
String sql3 = "insert into Employee values (?,?,?,?)";
PreparedStatement ps3 = con.prepareStatement(sql3);
ps3.setInt(1,e3.getEmpId());
ps3.setString(2,e3.getEmpName());
ps3.setString(3,e3.getDesignation());
ps3.setInt(4,e3.getSalary());
int i3 = ps3.executeUpdate();
if(i1 > 0 && i2 > 0 && i3 > 0){
System.out.println("Details inserted in Employee table");
}
else{
System.out.println("Insertion Failed");
}
}catch(Exception e){e.printStackTrace();}
}
}
Q4. Explain various types of JDBC driver types
JDBC drivers are the software components that enable communication between a database and a Java application. There are four different types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native API driver
3. Network Protocol driver
4. Thin driver
JDBC-ODBC bridge driver:
The JDBC-ODBC bridge driver is the oldest and most widely used type of JDBC driver. It uses an ODBC driver to connect to a database. The JDBC-ODBC bridge driver is not written entirely in Java and, as a result, is not platform independent. In addition, the JDBC-ODBC bridge driver is not suitable for use in a production environment because of its lack of performance and scalability.
Native API driver:
A native API driver uses the database's native application programming interface (API) to connect to a database. The advantage of a native API driver is that it is usually more efficient than a JDBC-ODBC bridge driver. The disadvantage is that it is not written entirely in Java and, as a result, is not platform independent. In addition, a native API driver typically requires more effort to develop than a JDBC-ODBC bridge driver.
Network Protocol driver:
A network protocol driver uses a middleware layer to connect to a database. The advantage of a network protocol driver is that it is platform independent. The disadvantage is that it is typically less efficient than a native API driver. In addition, a network protocol driver typically requires more effort to develop than a JDBC-ODBC bridge driver.
Thin driver:
A thin driver is a fully written in Java driver that uses a database's network protocol to connect to a database. The advantage of a thin driver is that it is platform independent and typically more efficient than a network protocol driver. The disadvantage is that it requires more effort to develop than a JDBC-ODBC bridge driver.
6-Mark Question
Q1. Explain the following statement objects with examples:
a) PreparedStatement Object
b)
CallableStatement Object
A PreparedStatement object is an SQL statement that has been precompiled by the database server. This means that the statement can be executed faster than if it was a regular SQL statement.
PreparedStatement objects can be used to execute SQL statements that take parameters. The parameters can be set using the setXXX() methods of the PreparedStatement object.
Here is an example of a PreparedStatement object that inserts a new row into a table:
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "value1");
pstmt.setString(2,
"value2");
pstmt.setString(3, "value3");
pstmt.executeUpdate();
A CallableStatement object is used to execute stored procedures that are written in languages such as C or Java.
A CallableStatement object can return one or more ResultSet objects. It can also return a single value, such as an int or a String.
Here is an example of a CallableStatement object that calls a stored procedure that inserts a new row into a table:
String sql = "{call insert_row (?, ?, ?)}";
CallableStatement cstmt =
conn.prepareCall(sql);
cstmt.setString(1, "value1");
cstmt.setString(2,
"value2");
cstmt.setString(3, "value3");
cstmt.executeUpdate();
Q2. Write a program to connect to database with following information:
Driver: JDBC/ODBC driver or
MySQL driver
User Name: XYZ
Password: 123
Retrieve all rows with marks>60 using prepared
statement object. Assume following table:
Table Name: Student
Fields: RollNo, Name, Marks
It is always a good idea to use a prepared statement when querying a database. This is especially true when you are retrieving rows based on some criteria. In this case, we want to retrieve all rows where the marks are greater than 60.
Prepared statements help to protect against SQL injection attacks. They also help to improve performance because the database can cache the query plan and reuse it for future executions.
Here is the code to retrieve all rows with marks greater than 60:
PreparedStatement ps = conn.prepareStatement("SELECT * FROM Student WHERE Marks > ?");
ps.setInt(1,
60);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int rollNo = rs.getInt("RollNo");
String name = rs.getString("Name");
int
marks = rs.getInt("Marks");
// do something with the retrieved data...
}
rs.close();
ps.close();