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

Java MQP Solution

Uploaded by

chavanakshay1812
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Java MQP Solution

Uploaded by

chavanakshay1812
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Java MQP Solution

1)
a) Explain any four legacy classes of Java’s Collection
Framework.
I. Vector
- Vector implements a dynamic array that grows as needed to
accommodate new elements.
- It is similar to ArrayList, but with two differences: Vector is
synchronized, and it contains many legacy methods that are
not part of the Collections.
- It implements the List interface.

Vector is declared like this: class Vector<E>


Here, E specifies the type of element that will be stored.

- Operations: add, remove, get, set

- Constructors:
Vector( ): creates a default vector, which has an initial
size of 10.
Vector(int size): creates a vector whose initial capacity
is specified by size.
Vector(int size, int incr): creates a vector whose
initial capacity is specified by size and whose increment is
specified by incr. The increment specifies the number of
elements to allocate each time that a vector is resized
upward.
Vector(Collection c): creates a vector that contains the
elements of collection c.

II. Stack
- Stack is a subclass of Vector that implements a standard
LIFO data structure.
- Stack only defines the default constructor, which creates an
empty stack.
- Stack includes all the methods defined by Vector

It is declared as: class Stack<E>


Here, E specifies the type of element stored in the stack.

- Operations: push, pop, peek, empty

III. Dictionary
- Dictionary is an abstract class that represents a key/value
storage repository.
- Given a key and value, you can store the value in a
Dictionary object.
- Once the value is stored, you can retrieve it by using its key.
Thus, like a map, a dictionary can be thought of as a list of
key/value pairs.

It is declared as: class Dictionary <E>


Here, K specifies the type of keys, and V specifies the type
of values.

IV. Hashtable
- Hashtable was part of the original java.util and is a concrete
implementation of a Dictionary.
- HashMap, Hashtable stores key/value pairs in a hash table.
- However, neither keys nor values can be null.
- When using a Hashtable, you specify an object that is used
as a key, and the value that you want linked to that key.
- The key is then hashed, and the resulting hash code is used
as the index at which the value is stored within the table.

It is declared like this: class Hashtable<K,V>

- Constructors:
Hashtable( ): default constructor
Hashtable(int size): creates a hash table that has an
initial size specified by size.
Hashtable(int size, float fillRatio): creates a hash
table that has an initial size specified by size and a fill
ratio specified by fillRatio. If you do not specify a fill ratio,
then 0.75 is used
Hashtable(Map m): creates a hash table that is
initialized with the elements in m. The capacity of the
hash table is set to twice the number of elements in m.

b) Create a class STUDENT with two private members: USN,


Name using LinkedList class in Java. Write a program to add
at least 3 objects of the above STUDENT class and display the
data.
import java.util.LinkedList;

class STUDENT {
private String USN;
private String Name;

public STUDENT(String USN, String Name) {


this.USN = USN;
this.Name = Name;
}

@Override
public String toString() {
return "USN: " + USN + ", Name: " + Name;
}
}

public class StudentLinkedListExample {


public static void main(String[] args) {
LinkedList<STUDENT> studentList = new
LinkedList<>();

studentList.add(new STUDENT("USN001", "Alice"));


studentList.add(new STUDENT("USN002", "Bob"));
studentList.add(new STUDENT("USN003",
"Charlie"));

for (STUDENT student : studentList) {


System.out.println(student);
}
}
}

2)
a) Explain the methods of NavigableSet class with a sample
program.
- The NavigableSet interface in Java is part of the Java
Collections Framework.
- It extends the SortedSet interface.
- It provides additional methods to navigate and manipulate
the elements in a sorted set.

Methods:
- lower(E e): returns the greatest element in the set that is
strictly less than the specified element.
- floor(E e): returns the greatest element in the set that is
less than or equal to the specified element.
- ceiling(E e): returns the least element in the set that is
greater than or equal to the specified element.
- higher(E e): returns the least element in the set that is
strictly greater than the specified element.
- pollFirst(): retrieves and removes the first (lowest) element
of the set.
- pollLast(): retrieves and removes the last (highest) element
of the set.

import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetExample {


public static void main(String[] args) {
NavigableSet<Integer> set = new TreeSet<>();
set.add(1);
set.add(3);
set.add(5);
set.add(7);

System.out.println("Original set: " + set);


System.out.println("Lower than 5: " +
set.lower(5));
System.out.println("Floor of 5: " + set.floor(5));
System.out.println("Ceiling of 5: " +
set.ceiling(5));
System.out.println("Higher than 5: " +
set.higher(5));
System.out.println("Poll first: " +
set.pollFirst());
System.out.println("Set after pollFirst: " + set);
System.out.println("Poll last: " + set.pollLast());
System.out.println("Set after pollLast: " + set);
}
}

b) What is a Collection Framework? Explain the methods defined


by Collections Framework.
- The Java Collections Framework standardizes the way in
which groups of objects are handled by your programs
- The Collections Framework defines several collection
interfaces - Collection, Deque, List, NavigableSet, Queue, Set
and SortedSet.

Methods in collection interface:


I. add
addAll boolean add(E obj): adds obj to the invoking
collection. Returns true if obj was added to the collection.
Returns false if obj is already a member of the collection and
the collection does not allow duplicates.

II. addAll
boolean addAll(Collection <? extends E>c): Adds all the
elements of c to the invoking collection. Returns true if the
operation succeeded (i.e., the elements were added).
Otherwise, returns false.

III. clear
void clear(): Removes all elements from the invoking
collection.

IV. contains
boolean contains(Object obj): Returns true if obj is an
element of the invoking collection. Otherwise, it returns false.

V. containsAll
boolean containsAll(Collection c): Returns true if the
invoking collection contains all elements of c. Otherwise, it
returns false.

VI. equals
boolean equals(Object obj): Returns true if the invoking
collection and obj are equal. Otherwise, returns false.

VII. hashCode
int hashCode(): Returns the hash code for the invoking
collection.

VIII. isEmpty
boolean isEmpty(): Returns true if the invoking collection is
empty. Otherwise, it returns false.

IX. iterator
Iterator iterator(): Returns an iterator for the invoking
collection.

X. remove
boolean remove(Object obj): Removes one instance of obj
from the invoking collection. Returns true if the element was
removed. Otherwise, it returns false.

3)
a) List and explain the various String comparison methods.
I. equals( ):
- To compare two strings for equality, use equals( ).
- It has this general form: boolean equals(Object str)
- Here, str is the String object being compared with the
invoking String object.
- It returns true if the strings contain the same characters in
the same order, and false otherwise.
- The comparison is case-sensitive.

II. equalsIgnoreCase( ):
- To perform a comparison that ignores case differences, call
equalsIgnoreCase( ).
- It has this general form: boolean equalsIgnoreCase(String
str)
- Here, str is the String object being compared with the
invoking String object.
- It, too, returns true if the strings contain the same characters
in the same order, and false otherwise.

III. startsWith():
- The startsWith( ) method determines whether a given String
begins with a specified string.
- Syntax: boolean startsWith(String str)

IV. endsWith():
- endsWith( ) determines whether the String in question ends
with a specified string.
- Syntax: boolean endsWith(String str)
V. == :
- The == operator compares two object references to see
whether they refer to the same instance.

VI. compareTo( ):
- It has this general form: int compareTo(String str)
- Here, str is the String being compared with the invoking
String.

- The result of the comparison is returned and is interpreted:


Less than zero when invoking string is less than str.
Greater than zero when invoking string is greater than str.
Zero The two strings are equal.

b) Write a program to remove duplicate characters from a given


String and display the String.
import java.util.*;

class RemoveDuplicatesExample4 {
public static void removeDuplicates(String str) {
String newstr = new String();
int length = str.length();

for (int i = 0; i < length; i++) {


char charAtPosition = str.charAt(i);

if (newstr.indexOf(charAtPosition) < 0) {
newstr += charAtPosition;
}
}
System.out.println(newstr);
}

public static void main(String[] args) {


String str = "JavaTpoint is the best learning
website";
removeDuplicates(str);
}
}
4)
a) What is String in Java? Write a Java program that
demonstrates any six constructors of String class.
In Java a string is a sequence of characters. But, unlike many
other languages that implement strings as character arrays.

import java.io.UnsupportedEncodingException;

public class Program4 {


public static void main(String[] args) throws
UnsupportedEncodingException {
char c[] = {'j', 'a', 'v', 'a'};
String s1 = new String();
System.out.println("Default constructor: " + s1);

String s2 = new String(c);


String s3 = new String(s2);
System.out.println("String object: " + s2);
System.out.println("String object: " + s3);

byte ascii[] = {65, 66, 67, 68, 69, 70};


String s4 = new String(ascii);
System.out.println(s4);
String s5 = new String(ascii, 2, 3);
System.out.println(s5);

StringBuilder s6 = new StringBuilder("Hello");


System.out.println(s6.toString());
s6.append(" World!");
System.out.println(s6.toString());

StringBuffer s7 = new StringBuffer("Hello ");


s7.insert(1, "Java");
System.out.println("Now original string is: " +
s7);

}
}
b) Explain the following methods of StringBuffer class:
i) append(): concatenates the string representation of any
other type of data to the end of the invoking StringBuffer
object. It has several overloaded versions.

Here are a few of its forms:


StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)

ii) insert(): inserts one string into another. It is overloaded to


accept values of all the simple types, plus Strings, Objects,
and CharSequences. It calls String.valueOf( )to obtain the
string representation of the value it is called with. This string
is then inserted into the invoking StringBuffer object.

These are a few of its forms:


StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

iii) reverse(): You can reverse the characters within a


StringBuffer object using reverse( ), shown here: StringBuffer
reverse( )
This method returns the reversed object on which it was
called.

iv) replace(): You can replace one set of characters with


another set inside a StringBuffer object by calling replace( ).
Its signature is shown here: StringBuffer replace(int
startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes
startIndex and endIndex. The replacement string is passed in
str. The resulting StringBuffer object is returned.
5)
a) Explain the key features of Swing with a sample program.
Swing offers following key features:
i. Platform Independent: Swing applications can run on any
operating system without modification. This is achieved
through Swing’s pluggable look and feel (PLAF) system.

ii. Customizable: Swing allows you to change the appearance


of your application by using different "look and feel" styles.

iii. Extensible: Swing is designed to be extensible, allowing


developers to create new components by extending existing
ones or by combining multiple components.

iv. Configurable: Swing components are highly configurable.


You can set a variety of properties on each component, such
as size, layout, visibility, and behavior.

v. Lightweight: Swing components are written entirely in Java


and are therefore lightweight.

vi. Built on AWT: Swing provides a more advanced and flexible


set of components by using AWT’s basic functionality and
adding its own enhancements.

vii. Event Handling: Swing components support event


handling to respond to user actions such as button clicks,
mouse movements, or keyboard inputs.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingDemo {


static class CustomButton extends JButton {
public CustomButton(String text) {
super(text);
setBackground(Color.GREEN);
setFont(new Font("Serif", Font.ITALIC, 14));
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent
e) {
setText("Clicked!");
}
});
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Swing Features
Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON
_CLOSE);
frame.setSize(300, 200);

JPanel panel = new JPanel(new


BorderLayout());
JLabel label = new JLabel("This is a JLabel",
SwingConstants.CENTER);
panel.add(label, BorderLayout.NORTH);
JButton button = new CustomButton("Click
Me");
panel.add(button, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
});
}
}

b) Write a program to demonstrate icons representing


timepiece using JButton and JToggleButton. When the button
is pressed, name of that timepiece in the label.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TimepieceDemo {

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Timepiece Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON
_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new BorderLayout());

JPanel panel = new JPanel(new GridLayout(2,


2));

ImageIcon analogIcon = new


ImageIcon(createIcon(Color.BLUE, "Analog"));
ImageIcon digitalIcon = new
ImageIcon(createIcon(Color.GREEN, "Digital"));

JButton analogButton = new JButton("Analog",


analogIcon);
JButton digitalButton = new
JButton("Digital", digitalIcon);
JToggleButton analogToggleButton = new
JToggleButton("Analog Toggle", analogIcon);
JToggleButton digitalToggleButton = new
JToggleButton("Digital Toggle", digitalIcon);

panel.add(analogButton);
panel.add(digitalButton);
panel.add(analogToggleButton);
panel.add(digitalToggleButton);

JLabel label = new JLabel("Select a


timepiece", SwingConstants.CENTER);
label.setPreferredSize(new Dimension(300,
50));
ActionListener buttonListener = e ->
label.setText(((JButton) e.getSource()).getText());

analogButton.addActionListener(buttonListener);

digitalButton.addActionListener(buttonListener);

analogToggleButton.addActionListener(buttonListener);

digitalToggleButton.addActionListener(buttonListener);

frame.add(panel, BorderLayout.CENTER);
frame.add(label, BorderLayout.SOUTH);
frame.setVisible(true);
});
}

private static Image createIcon(Color color, String


text) {
int size = 40;
BufferedImage image = new BufferedImage(size,
size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setColor(color);
g.fillOval(0, 0, size, size);
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.BOLD, 12));
g.drawString(text, 10, size / 2);
g.dispose();
return image;
}
}

6)
a) Write a program to create a frame for a simple arithmetic
calculator using swing components and layout managers.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.script.ScriptEngineManager;

public class SimpleCalculator {

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Calculator");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
frame.setLayout(new BorderLayout());

JTextField display = new JTextField();

display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
frame.add(display, BorderLayout.NORTH);

JPanel panel = new JPanel(new GridLayout(4,


4, 5, 5));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};

for (String text : buttons) {


JButton button = new JButton(text);
button.addActionListener(new
CalculatorListener(display));
panel.add(button);
}

frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
});
}
}

class CalculatorListener implements ActionListener {


private JTextField display;
private StringBuilder input = new StringBuilder();

public CalculatorListener(JTextField display) {


this.display = display;
}

@Override
public void actionPerformed(ActionEvent e) {
String text = ((JButton)
e.getSource()).getText();

if (text.equals("C")) {
input.setLength(0);
display.setText("");
} else if (text.equals("=")) {
try {
ScriptEngineManager manager = new
ScriptEngineManager();

display.setText(String.valueOf(manager.getEngineByName("J
avaScript").eval(input.toString())));
input.setLength(0);
} catch (Exception ex) {
display.setText("Error");
}
} else {
input.append(text);
display.setText(input.toString());
}
}
}

b) Explain the event handling mechanism used by Swing with an


example program.

Swing's event handling mechanism is designed to manage user


interactions with GUI components.

1. Event Sources: Components like buttons and text fields that


generate events (e.g., button clicks, key presses).
2. Event Listeners: Interfaces that define methods for handling
specific events (e.g., ActionListener for button clicks and
MouseListener for mouse actions).
3. Event Objects: Contain information about the event, such as
the source component and event details.
4. Event Registration: To handle events, you register an event
listener with a component using methods like
addActionListener or addMouseListener.
5. Event Dispatch Thread (EDT): Swing processes events and
updates the GUI on a single thread called the EDT to ensure
thread safety.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class EventDemo {
JLabel jlab;

EventDemo() {
JFrame jfrm = new JFrame("An Event Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton jbtnAlpha = new JButton("Alpha");


JButton jbtnBeta = new JButton("Beta");

jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed.");
}
});

jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed.");
}
});
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);

jlab = new JLabel("Press a button.");


jfrm.add(jlab);
jfrm.setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EventDemo();
}
});
}
}

7)
a) List and explain the core classes and interfaces in
javax.servlet package.
The javax.servlet package provides the core classes and
interfaces required for building Java web applications.
Interfaces:
- Servlet: Defines methods that all servlets must implement.
- ServletRequest: Defines an object to provide client request
information to a servlet.
- ServletResponse: Defines an object to assist a servlet in
sending a response to the client.
- ServletConfig: A servlet configuration object used by a servlet
container to pass information to a servlet during
initialization.
- ServletContext: Defines a set of methods that a servlet uses to
communicate with its servlet container, for example, to get the
MIME type of a file, dispatch requests, or write to a log file
Classes:
- GenericServlet: Defines a generic, protocol-independent
servlet.
- ServletInputStream: Provides an input stream for reading
binary data from a client request, including an efficient
readLine method for reading data one line at a time.
- ServletOutputStream: Provides an output stream for sending
binary data to the client.
- ServletException: Defines a general exception a servlet can
throw when it encounters difficulty.
- UnavailableException: Defines an exception that a servlet or
filter throws to indicate that it is permanently or temporarily
unavailable.

b) Write a java servlet program to accept two parameters from


the webpage, find the sum of them and display the result in
the webpage. Also give necessary html script to create
webpage.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/SumServlet")
public class SumServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int num1 =
Integer.parseInt(request.getParameter("num1"));
int num2 =
Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Result</h1>");
response.getWriter().println("<p>Sum: " + sum +
"</p>");
response.getWriter().println("</body></html>");
}
}

<!DOCTYPE html>
<html>
<head>
<title>Sum Calculator</title>
</head>
<body>
<form action="SumServlet" method="get">
<label for="num1">Number 1:</label>
<input type="text" id="num1" name="num1"
required>
<br>
<label for="num2">Number 2:</label>
<input type="text" id="num2" name="num2"
required>
<br>
<input type="submit">
</form>
</body>
</html>

8)
a) Explain different JSP tags with a program to demonstrate all
tags.
JSP tags define java code that is to be executed before the
output of the jsp program is sent to the browser. They are
embedded into the HTML component of a jsp program.

i. Comment tag: A comment tag opens with <%-- and closes


with --%> and is followed by a comment that usually describes
the functionality of statements.
ii. Declaration statement tags: A declaration statement tag
opens with <%! And is followed by declaration statements that
define the variables, objects, and methods.

iii. Directive tags: A directive tag opens with <%@ and are
commonly used in directives import, include and taglib
commands.

iv. Expression tags: An expression tag opens with <%= and is


used for an expression statement whose result page replaces
the expression tag when the jsp virtual engine resolves JSP
tags.

v. Scriptlet tag: A scriptlet tag opens with <% and contains


commonly used java control statements and loops.

<%@ page language="java" contentType="text/html;


charset=UTF-8" pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html>
<head>
<title>JSP Tag Demo</title>
</head>
<body>
<!-- Declaration -->
<%! int counter = 1; %>

<!-- Scriptlet -->


<%
String message = "Hello from JSP!";
counter++;
%>

<!-- Expression -->


<p>Message: <%= message %></p>

<!-- Directive: Include -->


<jsp:include page="footer.jsp" />
</body>
</html>

b) Explain the Life Cycle of Servlets with a neat diagram.

There are three states of servlet: new, ready, end.


- The servlet instance is created when it is in new state.
- After invoking the init() method, the servlet comes to the
ready state.
- When the ready state servlet invokes the destroy() method it
comes to the end state.

i. Servlet class is loaded: The Servlet class is loaded when the


first request to the web container.

ii. Servlet instance is created: Web container creates the


instance of servlet class only once.

iii. init method is invoked: It calls the init() method when the
servlet instance is loaded. It is used to initialize servlets.
Syntax: public void init(ServletConfig config) throws
ServletException

iv. Service method is invoked: Web container calls service


method each time when request for the servlet is received. If
the servlet is not initialized it calls init then it calls the service
method.
Syntax: public void service(Servlet request,
ServletResponse response) throws ServletException,
IOException
v. Destroy method is invoked: The web container calls the
destroy method before it removes the servlet from service. It
gives servlet an opportunity to clean up memory, resources
etc.
Syntax: public void destroy()

c) What are cookies? Write a program to create a cookie with


name “User name” and value: “xyz”. Also display stored
cookies in the webpage.
Cookie is a small piece of information created by a JSP
program that is stored on the client’s hard disk by the
browser. They are used to store various kinds of information,
such as user preference.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieExample extends HttpServlet {


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie = new Cookie("User name", "xyz");
cookie.setMaxAge(60);
response.addCookie(cookie);

Cookie[] cookies = request.getCookies();

response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Stored
Cookies</h1>");

if (cookies != null) {
for (Cookie c : cookies) {
response.getWriter().println("<p>Cookie
Name: " + c.getName() + " | Cookie Value: " +
c.getValue() + "</p>");
}
} else {
response.getWriter().println("<p>No cookies
found.</p>");
}

response.getWriter().println("</body></html>");
}
}

9)
a) What is a statement object in JDBC? Explain the following
statement objects i) Callable statement object ii) Prepared
statement object
Statement object executes query immediately without
precompiling. It contains the executeQuery() method, which
accepts query as argument. Then the query is transmitted for
processing and returns ResultSet as object.

i) Callable statement object:


- The callableStatement object is used to call a stored
procedure from within the J2EE object.
- Stored procedure is executed by invoking by the name of
procedure.
- The callableStatement uses three types of parameters when
calling stored procedures.
- The parameters are IN, OUT, INOUT.
- The IN parameter contains data that needs to be passed to
the stored procedure whose value is assigned using setxxx()
method, where xxx represents the datatype.
- OUT parameter contains value returned by stored
procedure whose value is retrieved using getxxx() method.
- INOUT parameter is used to both pass information to the
stored procedure and retrieve the information from the
procedure.

ii) Prepared statement object


- A SQL query must be compiled before DBMS processes the
query. Query is precompiled and executed using Prepared
statements.
- The SQL statement is predefined and can be executed
multiple times with different parameter values.
- The PreparedStatement uses various setXXX() methods to
set the values of parameters in the SQL statement.
- Results from the SQL query or update can be retrieved
using methods such as executeQuery() for SELECT
statements or executeUpdate() for INSERT, UPDATE, and
DELETE statements.

b) Explain transaction processing in JDBC.


- A transaction involves a series of SQL statements that must
all complete successfully for the transaction to be considered
finished.
- If any statement fails, all the successfully executed
statements in that transaction must be rolled back.
- Until you call commit(), any SQL statements executed as part
of the transaction can be rolled back if needed.
- A transaction is not finalized until you explicitly call the
commit() method on the connection object.
- By default, many DBMSs have Auto-Commit enabled. This
means that every SQL statement is automatically committed
right after it executes.
- If you are handling multiple SQL statements as part of a
single transaction, you need to turn off Auto-Commit. To do
this, set Auto-Commit to false using

c) Write any two syntax of establishing a connection to the


database.
Using DataSource:
public class DatabaseConnectionExample {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";

try {
Connection conn =
DriverManager.getConnection(url, username, password);
System.out.println("Connection established
successfully!");
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Using DriverManager:
public class DriverManagerExample {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";

try {
Connection connection =
DriverManager.getConnection(url, username, password);
System.out.println("Connection established
successfully!");
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

10)
a) Explain the four types of JDBC drivers.

Type 1 Driver (JDBC-ODBC Bridge):

- Also known as the JDBC/ODBC Bridge, developed by


Microsoft.
- Receives JDBC calls and translates them into ODBC calls.
- Acts as a bridge between JDBC and ODBC, making it
DBMS-independent but reliant on ODBC drivers.

Type 2 Driver (JDBC-Native Driver):

- Generates platform-specific code that translates JDBC calls


into database-specific calls.
- Requires native code for each DBMS, provided by the
database vendor.
- Offers good performance but lacks portability across
different DBMS systems.

Type 3 Driver (JDBC-Net Driver):

- Converts JDBC calls into a database-independent protocol.


- The protocol is then translated into the database-specific
format by a middle-tier server.
- Provides a more flexible and DBMS-independent solution
compared to Type 1 and Type 2.

Type 4 Driver (Pure Java Driver):

- Directly converts JDBC calls into the database-specific


protocol.
- Communicates directly with the database without any
intermediate steps.
- Offers the fastest performance and is written entirely in Java,
making it highly portable.

b) Explain connection pooling with neat diagram and code


snippets.

- Clients frequently interacting with the database either need


to keep connections open or repeatedly open and close
connections. Keeping connections open can block other
clients, while reconnecting each time is inefficient.

- A connection pool is a collection of pre-established database


connections maintained in memory. These connections are
reused, eliminating the need to reconnect to the database for
each interaction.
- The DataSource interface is used to access the connection
pool. Connection pooling is typically implemented by the
application server.

- Types of Connections:

Logical Connection: A handle to a physical connection


managed by the pool.
Physical Connection: The actual database connection
managed by the pool.
Context context = new InitialContext();
DataSource dataSource = (DataSource)
context.lookup("java:comp/env/jdbc/pool");
Connection connection = dataSource.getConnection();

You might also like