Advantages of Java Collections Framework (JCF)
1. Reduces Programming Effort
Provides ready-made data structures like ArrayList, LinkedList, HashSet, and HashMap, so
developers do not need to implement them from scratch.
2. Improves Performance
Offers efficient implementations of common data structures and algorithms, improving speed
and resource usage.
3. Provides Standardized Architecture
Defines common interfaces such as Collection, List, Set, and Map, ensuring consistency and
easy understanding.
4. Reusability and Interoperability
Different collection classes work together easily because they follow the same interfaces.
5. Dynamic Data Handling
Collections can grow or shrink dynamically, unlike arrays which have fixed size.
6. Useful Utility Methods
The Collections utility class provides methods like sort(), reverse(), shuffle(), and max() for
easy data manipulation.
7. Type Safety with Generics
Generics ensure that collections store specific data types, reducing runtime errors.
8. Difference Between List and Set in Java
Feature List Set
A collection that stores elements in A collection that stores unique elements
Definition
a sequence only
Duplicates Allowed Not allowed
Order not guaranteed (except
Order Maintains insertion order
LinkedHashSet/TreeSet)
Elements can be accessed using an
Index No index-based access
index
Examples ArrayList, LinkedList, Vector HashSet, LinkedHashSet, TreeSet
1️⃣ Comparable Interface (Natural Sorting)
Comparable is used when the class itself decides how objects should be sorted.
The class implements Comparable
Uses the method compareTo()
Only one sorting rule
Example: Sort students by age
class Student implements Comparable<Student> {
int age;
public int compareTo(Student s) {
return [Link] - [Link];
}
}
Meaning:
When Java sorts Student objects, it automatically sorts by age.
So the sorting rule is inside the class.
2️⃣ Comparator Interface (Custom Sorting)
Comparator is used when we want different ways to sort objects.
A separate class implements Comparator
Uses the method compare()
Can create multiple sorting rules
class AgeComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return [Link] - [Link];
}
}
Difference Between Array and ArrayList in Java
Feature Array ArrayList
Fixed size (cannot change after
Size Dynamic size (can grow or shrink)
creation)
Package Part of Java language Part of Java Collections Framework ([Link])
Data types Can store primitive and objects Stores objects only
Performance Faster because it has fixed size Slightly slower due to dynamic resizing
Many built-in methods like add(), remove(),
Methods Limited built-in methods
size()
int[] arr = new int[3];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
import [Link];
ArrayList<Integer> list = new ArrayList<>();
[Link](10);
[Link](20);
[Link](30);
1️. Collection Interface
The Collection interface is the root interface of the Java Collections Framework and represents a
group of objects.
Important Methods
Method Description
add(E e) Adds an element to the collection
remove(Object o) Removes a specified element
size() Returns the number of elements
isEmpty() Checks whether the collection is empty
contains(Object o) Checks if the element exists
clear() Removes all elements
iterator() Returns an iterator to traverse elements
2️. List Interface
The List interface extends Collection and represents an ordered collection that allows duplicates.
Important Methods
Method Description
add(E e) Adds an element to the list
add(int index, E element) Inserts element at specific position
get(int index) Returns element at given index
set(int index, E element) Replaces element at given index
remove(int index) Removes element at index
Method Description
indexOf(Object o) Returns index of element
Examples: ArrayList, LinkedList, Vector
3. NavigableSet Interface
The NavigableSet interface extends SortedSet and provides methods to navigate elements in a
sorted set.
Important Methods
Method Description
lower(E e) Returns greatest element less than e
floor(E e) Returns greatest element ≤ e
ceiling(E e) Returns smallest element ≥ e
higher(E e) Returns smallest element greater than e
pollFirst() Removes and returns first element
pollLast() Removes and returns last element
Example implementation: TreeSet
4. Queue Interface
1️⃣ element() and peek() → Check the head (do not remove)
Method What it does If queue is empty
element() Returns head element ❌ Throws exception
peek() Returns head element ✅ Returns null
🧠 Memory trick:
Peek politely, Element aggressively
peek() → safe → returns null
element() → strict → throws error
2️⃣ remove() and poll() → Remove the head
Method What it does If queue is empty
remove() Removes and returns head ❌ Throws exception
poll() Removes and returns head ✅ Returns null
🧠 Memory trick:
Poll politely, Remove aggressively
poll() → safe → returns null
remove() → strict → throws error
3⃣ offer() → Add element
Method What it does
offer(E obj) Adds element to queue and returns true if successful
define comparator mention the methods provided by the comparator interface illustrate its use with
a program that demonstrates sorting elements in treeset in a reverse order
Comparator Interface in Java
The Comparator interface is used to define custom sorting order for objects. It belongs to the
[Link] package and is mainly used when we want to sort elements in a different order than their
natural ordering.
Unlike Comparable, the sorting logic is written in a separate class.
import [Link].*;
class ReverseComparator implements Comparator<Integer> {
public int compare(Integer a, Integer b) {
return b - a; // reverse order
public class TreeSetComparatorExample {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>(new ReverseComparator());
[Link](10);
[Link](50);
[Link](30);
[Link](20);
[Link]("TreeSet in reverse order: " + set);
Legacy class examples
import [Link];
public class VectorExample {
public static void main(String[] args) {
Vector<String> v = new Vector<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");
[Link]("Vector elements: " + v);
[Link]("Banana");
[Link]("After removal: " + v);
[Link]("Element at index 1: " + [Link](1));
}
import [Link];
public class StackExample {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
[Link](10);
[Link](20);
[Link](30);
[Link]("Stack: " + stack);
[Link]("Top element: " + [Link]());
[Link]();
[Link]("After pop: " + stack);
import [Link];
import [Link];
public class DictionaryExample {
public static void main(String[] args) {
Dictionary<Integer, String> d = new Hashtable<>();
[Link](1, "Alice");
[Link](2, "Bob");
[Link]("Value for key 1: " + [Link](1));
[Link]("Value for key 2: " + [Link](2));
import [Link];
public class HashtableExample {
public static void main(String[] args) {
Hashtable<Integer, String> ht = new Hashtable<>();
[Link](101, "John");
[Link](102, "David");
[Link](103, "Emma");
[Link]("Hashtable: " + ht);
[Link]("Value for key 102: " + [Link](102));
[Link](103);
[Link]("After removal: " + ht);
Methods of StringBuffer Class
1️) append()
Definition:
append() is used to add text or other data to the end of a StringBuffer object.
Syntax
StringBuffer append(String str)
Example
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link](sb);
}
}
Output
Hello World
2️) insert()
Definition:
insert() is used to insert a string or character at a specified position in the StringBuffer.
Syntax
StringBuffer insert(int index, String str)
Example
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hlo");
[Link](1,"el");
[Link](sb);
}
}
Output
Hello
3) reverse()
Definition:
reverse() is used to reverse the characters of a StringBuffer.
Syntax
StringBuffer reverse()
Example
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
[Link]();
[Link](sb);
}
}
Output
avaJ
4) replace()
Definition:
replace() is used to replace characters between two index positions with another string.
Syntax
StringBuffer replace(int start, int end, String str)
Example
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
[Link](6,11,"Java");
[Link](sb);
}
}
Output
Hello Java
IA 2
1️. jbutton example
import [Link].*;
public class SimpleButton {
public static void main(String[] args) {
JFrame f = new JFrame("Button Example");
JButton b = new JButton("Click Me");
[Link](100, 100, 100, 40);
[Link](e ->
[Link](f, "Button Clicked")
);
[Link](b);
[Link](300, 300);
[Link](null);
[Link](true);
}
}
[Link] box button
import [Link].*;
public class CheckBoxDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Checkbox Example");
JCheckBox cb1 = new JCheckBox("Option 1");
[Link](100, 80, 150, 30);
JCheckBox cb2 = new JCheckBox("Option 2");
[Link](100, 120, 150, 30);
[Link](e -> {
if ([Link]())
[Link](f, "Option 1 Checked");
else
[Link](f, "Option 1 Unchecked");
});
[Link](e -> {
if ([Link]())
[Link](f, "Option 2 Checked");
else
[Link](f, "Option 2 Unchecked");
});
[Link](cb1);
[Link](cb2);
[Link](300, 300);
[Link](null);
[Link](true);
4. Jradio button
import [Link].*;
public class RadioSimple {
public static void main(String[] args) {
JFrame f = new JFrame();
// Create radio buttons
JRadioButton r1 = new JRadioButton("Male");
JRadioButton r2 = new JRadioButton("Female");
// Set positions manually
[Link](50, 30, 100, 30);
[Link](50, 60, 100, 30);
// Group them
ButtonGroup bg = new ButtonGroup();
[Link](r1);
[Link](r2);
// Create button
JButton b = new JButton("Submit");
[Link](50, 100, 100, 30);
// Action
[Link](e -> {
if ([Link]())
[Link](f, "Male selected");
else if ([Link]())
[Link](f, "Female selected");
else
[Link](f, "Nothing selected");
});
// Add components
[Link](r1);
[Link](r2);
[Link](b);
// IMPORTANT: null layout
[Link](null);
[Link](200, 200);
[Link](true);
5(b) Describe the MVC Connection. How is it implemented in Java Swing?
🔹 MVC Connection
MVC (Model–View–Controller) is a design pattern that separates an application into three
interconnected components:
Model → Manages data and business logic
View → Displays data to the user
Controller → Handles user input and updates the Model or View
🔹 Connection between components
The View gets data from the Model and displays it
The Controller receives user input (clicks, typing)
The Controller updates the Model based on input
The Model notifies the View, and the View updates automatically
👉 This interaction is called the MVC connection
🔹 Implementation in Java Swing
Java Swing follows a loosely coupled MVC architecture:
1️. Model
Stores application data
Examples: TableModel, Document, SpinnerModel
2️. View
GUI components that display data
Examples: JTable, JTextField, JButton
3. Controller
Handles user actions using event listeners
Examples: ActionListener, MouseListener
Example program:
import [Link].*;
public class SimpleMVC {
public static void main(String[] args) {
JFrame f = new JFrame("MVC Example");
// View
JTextField tf = new JTextField();
[Link](50, 40, 150, 30);
JButton b = new JButton("Show");
[Link](80, 90, 80, 30);
// Controller
[Link](e -> {
String data = [Link](); // Model
[Link](f, data);
});
// Add components
[Link](tf);
[Link](b);
// null layout
[Link](null);
[Link](250, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
Example Program: Painting Shapes in Java Swing
import [Link].*;
import [Link].*;
public class SimplePaint extends JPanel {
@Override
protected void paintComponent(Graphics g) {
[Link](g); // clears background
// Draw a string
[Link]("Hello", 40, 40);
// Draw rectangle and fill rectangle
[Link](130, 30, 100, 80);
[Link](130, 130, 100, 80);
// Draw and fill oval
[Link](30, 130, 50, 60);
[Link](130, 130, 50, 60);
// Draw a line
[Link](30, 200, 130, 200);
// Draw and fill arc
[Link](30, 250, 80, 90, 0, 180);
[Link](130, 250, 80, 90, 0, 45);
// Change color and font
[Link]([Link]);
[Link](new Font("Roman", [Link], 20));
[Link]("Swing Drawing Example", 10, 380);
public static void main(String[] args) {
JFrame f = new JFrame();
[Link](new SimplePaint());
[Link](300, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
Explain the key features of Swing with a sample program
import [Link].*;
import [Link].*;
public class SwingDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Swing Demo");
JLabel label = new JLabel("Hello Swing");
JButton button = new JButton("Click Me");
// Action
[Link](e -> [Link]("Clicked!"));
// Add directly (no positions needed in BorderLayout)
[Link](label, [Link]);
[Link](button, [Link]);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
Mqp-2
MVC Architecture in Java Swing
MVC (Model–View–Controller) is a design pattern used to separate an application into three parts so
that the code is clean, organized, and easy to maintain.
🔹 1️. Model
Represents the data and business logic
Stores and manages the data
Notifies when data changes
👉 Example: Text stored in a text field, list data, table data
🔹 2️. View
Represents the user interface (UI)
Displays data to the user
Does not contain logic
👉 Example: Buttons, text fields, labels (Swing components)
🔹 3. Controller
Handles user input and interactions
Updates the model based on user actions
Controls the flow between Model and View
👉 Example: Event listeners like ActionListener
🎯 Mapping the Given Components
1️. JTextField
Represents the View
It is the UI element where users type or see text
2️. ActionListener
Represents the Controller
It handles events like button clicks or text input actions and updates the model
3. Text content stored in the field
Represents the Model
It is the actual data being stored and manipulated
Develop a Java swing application using JFrame that displays a simple form 10 L3 CO2️ with the
following components :
A Label and text field for "Name"
A Label and text field for "Age"
A submit button
When the button is clicked, display the entered information using a
message dialog.
import [Link].*;
import [Link].*;
public class FormDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Form");
JLabel l1 = new JLabel("Name:");
[Link](30, 30, 100, 20);
JTextField t1 = new JTextField();
[Link](100, 30, 150, 20);
JLabel l2 = new JLabel("Age:");
[Link](30, 70, 100, 20);
JTextField t2 = new JTextField();
[Link](100, 70, 150, 20);
JButton b = new JButton("Submit");
[Link](100, 110, 100, 30);
[Link](e ->
[Link](f,
"Name: " + [Link]() + "\nAge: " + [Link]())
);
[Link](l1);
[Link](t1);
[Link](l2);
[Link](t2);
[Link](b);
[Link](300, 200);
[Link](null);
[Link](true);
Create a Java swing application using JApplet to design a simple calculator 10 L3 CO3
that adds two numbers entered by the user. Display the result when a button
is clicked.
import [Link].*;
import [Link].*;
public class SimpleCalculator extends JApplet implements ActionListener {
JTextField t1, t2;
JButton b;
public void init() {
setLayout(null);
add(new JLabel("Number 1:")).setBounds(20, 20, 100, 20);
t1 = new JTextField();
[Link](120, 20, 100, 20);
add(t1);
add(new JLabel("Number 2:")).setBounds(20, 60, 100, 20);
t2 = new JTextField();
[Link](120, 60, 100, 20);
add(t2);
b = new JButton("Add");
[Link](80, 100, 80, 30);
add(b);
[Link](this);
public void actionPerformed(ActionEvent e) {
[Link](this,
"Sum = " + ([Link]([Link]()) + [Link]([Link]())));
Develop a Java swing JApplet that contains a menubar with a "color"
menu. This menu should have three menu items: "Red". "Green" and "Blue". When a user selects
one of the options, the background color of the applet should change according.
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorMenuApplet extends JApplet implements ActionListener {
JMenuBar mb;
JMenu menu;
JMenuItem red, green, blue;
public void init() {
mb = new JMenuBar();
menu = new JMenu("Color");
red = new JMenuItem("Red");
green = new JMenuItem("Green");
blue = new JMenuItem("Blue");
[Link](red);
[Link](green);
[Link](blue);
[Link](menu);
setJMenuBar(mb);
[Link](this);
[Link](this);
[Link](this);
public void actionPerformed(ActionEvent e) {
if ([Link]() == red)
getContentPane().setBackground([Link]);
else if ([Link]() == green)
getContentPane().setBackground([Link]);
else if ([Link]() == blue)
getContentPane().setBackground([Link]);
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 [Link].*;
import [Link].*;
public class TimepieceDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Timepiece Demo");
JLabel label = new JLabel("Select a timepiece");
[Link](50, 20, 200, 30);
// JButton (Clock)
JButton b1 = new JButton("Clock");
[Link](30, 70, 100, 40);
// JToggleButton (Watch)
JToggleButton b2 = new JToggleButton("Watch");
[Link](150, 70, 100, 40);
// Action for JButton
[Link](e -> [Link]("Clock"));
// ItemListener for Toggle Button
[Link](e -> {
if ([Link]())
[Link]("Watch ON");
else
[Link]("Watch OFF");
});
// Add components
[Link](label);
[Link](b1);
[Link](b2);
[Link](null);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
)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.
Foreground event:those events which require direct interaction with users eg: mouse clicks or
buttons
Background event: do not require interaction with user eg: os interrupt
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 [Link].*;
public class EventDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Event Handling");
JButton b = new JButton("Click Me");
[Link](50, 50, 100, 30);
// Event Handling
[Link](e -> {
[Link](f, "Button Clicked");
});
[Link](b);
[Link](null);
[Link](200, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
Java module 4(Mohsin ali)
Here’s a simple Servlet program and a clear deployment explanation using Apache Tomcat.
✅ 1️. Simple Servlet Program
📄 [Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Hello from Servlet!</h2>");
[Link]("</body></html>");
}
}
✅ 2️. [Link] Configuration (Deployment Descriptor)
📄 WEB-INF/[Link]
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
✅ 3. Folder Structure
Your project should look like this:
MyApp/
│
├── WEB-INF/
│ ├── classes/
│ │ └── [Link]
│ └── [Link]
✅ 4. How It Works (Flow)
Browser sends request → [Link]
Tomcat receives request
Tomcat finds mapping in [Link]
Calls HelloServlet
Servlet generates response
Browser displays Hello from Servlet!
✅ 5. Steps to Deploy in Apache Tomcat
🔹 Step 1️: Compile Servlet
Make sure you have servlet API (from Tomcat lib folder)
javac -classpath "C:\Tomcat\lib\[Link]" [Link]
🔹 Step 2️: Place Files
Put .class file inside:
Tomcat/webapps/MyApp/WEB-INF/classes/
Put [Link] inside:
Tomcat/webapps/MyApp/WEB-INF/
🔹 Step 3: Start Tomcat
Go to Tomcat bin folder:
[Link] (Windows)
🔹 Step 4: Run in Browser
Open:
[Link]
👉 Output:
Hello from Servlet!
✅ 6. Important Concepts (Simple Explanation)
Servlet → Java program that runs on server
Tomcat → Web container (handles servlets)
[Link] → Maps URL → Servlet
doGet() → Handles browser GET request
PrintWriter → Sends response to browser
how can you read form data from an html page in servlet? write a code to read request parameters
<!DOCTYPE html>
<html>
<body>
<form action="readData" method="get">
Name: <input type="text" name="username"><br><br>
Age: <input type="text" name="age"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Servlet Code to Read Form Data
import [Link].*;
import [Link].*;
import [Link].*;
public class ReadFormServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
// Reading form parameters
String name = [Link]("username");
String age = [Link]("age");
[Link]("<html><body>");
[Link]("<h2>Form Data Received</h2>");
[Link]("Name: " + name + "<br>");
[Link]("Age: " + age);
[Link]("</body></html>");
explain how sessions and cookies are handled in JSP. write a small JSP code snippet demonstrating
user login using session object
theory of cookies and session read from model paper
📄 [Link]
<!DOCTYPE html>
<html>
<body>
<h2>Login Page</h2>
<form action="[Link]" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
📄 [Link]
<%@ page language="java" %>
<%
String user = [Link]("username");
String pass = [Link]("password");
// Simple validation
if("admin".equals(user) && "1234".equals(pass)) {
// ✅ Create Session
[Link]("user", user);
// ✅ Create Cookie
Cookie c = new Cookie("username", user);
[Link](60*60); // 1 hour
[Link](c);
[Link]("[Link]");
} else {
%>
<h3>Invalid Credentials</h3>
<a href="[Link]">Try Again</a>
<%
}
%>
📄 [Link]
<%@ page language="java" %>
<%
// ✅ Get session data
String user = (String) [Link]("user");
if(user == null) {
[Link]("[Link]");
return;
}
// ✅ Read cookie
String cookieUser = "Not Found";
Cookie[] cookies = [Link]();
if(cookies != null) {
for(Cookie c : cookies) {
if([Link]().equals("username")) {
cookieUser = [Link]();
%>
<h2>Welcome <%= user %>!</h2>
<p>Cookie Value: <%= cookieUser %></p>
<a href="[Link]">Logout</a>
📄 [Link]
<%@ page language="java" %>
<%
// Destroy session
[Link]();
%>
<h3>You are logged out!</h3>
<a href="[Link]">Login Again</a>
what are the major packages in servlet api. differentiate between [Link] and
[Link]
1️. [Link] Package (Core)
📌 From your PDF (Page 126–129)
🔹 Interfaces
Servlet → Defines lifecycle methods that every servlet must implement.
ServletRequest → Represents client request data sent to the servlet.
ServletResponse → Helps send response data back to the client.
ServletConfig → Provides initialization parameters to a servlet.
ServletContext → Allows communication between servlet and container (shared data,
logging, etc.).
🔹 Classes
GenericServlet → Protocol-independent base class for creating servlets.
ServletInputStream → Reads binary data from client request.
ServletOutputStream → Sends binary data to client response.
ServletException → Handles general servlet-related exceptions.
UnavailableException → Indicates servlet is temporarily/permanently unavailable.
✅ 2️. [Link] Package (HTTP-specific)
📌 From your PDF (Page 130–134)
🔹 Interfaces
HttpServletRequest → Provides HTTP-specific request information (headers, parameters,
etc.).
HttpServletResponse → Provides HTTP-specific response features (status codes, cookies,
etc.).
HttpSession → Maintains user session data across multiple requests.
🔹 Classes
HttpServlet → Base class for HTTP servlets (handles GET, POST, etc.).
Cookie → Stores small client-side data sent between browser and server.
HttpSessionEvent → Represents events related to session creation/destruction.
HttpSessionBindingEvent → Represents events when objects are added/removed from
session.
Feature [Link] [Link]
Type Core package HTTP-specific package
Protocol Protocol-independent HTTP only
Main Use General servlet functionality Web-based applications
Key Classes GenericServlet HttpServlet
Request/Response ServletRequest, ServletResponse HttpServletRequest, HttpServletResponse
Session Handling Not included Includes HttpSession
Cookies Not included Includes Cookie
Module 5
Example: CallableStatement with IN, OUT, INOUT
storedProcedure
CREATE PROCEDURE demo(IN a INT, OUT b INT, INOUT c INT)
BEGIN
SET b = a * 2;
SET c = c + 5;
END;
Java program
import [Link].*;
public class Demo {
public static void main(String[] args) throws Exception {
Connection con = [Link](
"jdbc:mysql://localhost:3306/test", "root", "password");
CallableStatement cs = [Link]("{call demo(?, ?, ?)}");
// IN parameter
[Link](1, 10);
// OUT parameter
[Link](2, [Link]);
// INOUT parameter
[Link](3, 20);
[Link](3, [Link]);
// Execute procedure
[Link]();
// Get results
int b = [Link](2);
int c = [Link](3);
[Link]("OUT value (b): " + b);
[Link]("INOUT value (c): " + c);
[Link]();
output
OUT value (b): 20
INOUT value (c): 25
1. Using DriverManager (Simple Method) (connection establishment)
import [Link].*;
public class DriverManagerExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";
try {
// Establish connection
Connection con = [Link](url, username, password);
[Link]("Connection established successfully using DriverManager!");
// Close connection
[Link]();
} catch (SQLException e) {
[Link]();
Using DataSource (Advanced Method)
import [Link].*;
import [Link];
import [Link];
public class DataSourceExample {
public static void main(String[] args) {
try {
// Create DataSource object
MysqlDataSource ds = new MysqlDataSource();
[Link]("jdbc:mysql://localhost:3306/mydatabase");
[Link]("myusername");
[Link]("mypassword");
// Get connection
Connection con = [Link]();
[Link]("Connection established successfully using DataSource!");
// Close connection
[Link]();
} catch (SQLException e) {
[Link]();
what is JDBC? explain the architecture and the need for JDBC in database connectivity
What is JDBC?
Java Database Connectivity (JDBC) is an API in Java that enables Java programs to interact with
databases. It provides a standard interface for connecting to databases, executing SQL queries, and
processing the results.
Using JDBC, a Java application can:
Establish a connection with a database
Send SQL queries (SELECT, INSERT, UPDATE, DELETE)
Retrieve and process results
JDBC ensures that Java programs can work with different databases in a uniform way.
JDBC Architecture
The JDBC architecture consists of two main layers:
1️. JDBC API Layer (Application Side)
This is used by Java applications to interact with databases.
Main components:
DriverManager – Manages database drivers and establishes connections
Connection – Represents a session with the database
Statement / PreparedStatement / CallableStatement – Used to execute SQL queries
ResultSet – Stores data retrieved from the database
2️. JDBC Driver Layer (Database Side)
Drivers act as a bridge between the Java application and the database.
Types of JDBC Drivers:
1. Type 1 – JDBC-ODBC Bridge
2. Type 2 – Native API Driver
3. Type 3 – Network Protocol Driver
4. Type 4 – Thin Driver (most commonly used)
Working Flow (Architecture Overview)
1. Java Application calls JDBC API
2. JDBC API uses DriverManager to load the driver
3. Driver establishes connection with DBMS
4. SQL query is sent to the database
5. Database processes the query
6. Result is returned as a ResultSet
Need for JDBC in Database Connectivity
JDBC is required because:
Platform Independence
Java applications can connect to any database using JDBC drivers
Standardized Interface
Same API works for MySQL, Oracle, PostgreSQL, etc.
Database Flexibility
Easy to switch databases by changing drivers
Efficient Data Handling
Allows execution of queries and retrieval of results
Supports Multiple Data Sources
Can access relational databases, flat files, and tabular data
to retrieve data from the result set and what are its important methods.
For theory refer pdf page 18 module 5 notes
import [Link].*;
public class ResultSetOperations {
public static void main(String[] args) {
try {
// 1. Load driver (optional in modern JDBC)
[Link]("[Link]");
// 2. Establish connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/mydatabase",
"root",
"password"
);
// 3. Create updatable ResultSet
Statement st = [Link](
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
ResultSet rs = [Link]("SELECT * FROM emp");
// ------------------ INSERT ------------------
[Link]();
[Link](1, 105);
[Link](2, "Avinash");
[Link]();
[Link]();
[Link]("Record Inserted!");
// ------------------ UPDATE ------------------
[Link](); // move to first row
[Link](2, "Updated Name");
[Link]();
[Link]("Record Updated!");
// ------------------ DELETE ------------------
[Link](); // move to last row
[Link]();
[Link]("Record Deleted!");
// Close connection
[Link]();
} catch (Exception e) {
[Link]();
}
Program for transaction
import [Link].*;
public class SavepointExample {
public static void main(String[] args) {
try {
Connection conn = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "password"
);
[Link](false); // start transaction
Statement stmt = [Link]();
// Step 1: First insert
[Link]("INSERT INTO emp VALUES (1, 'A')");
// Step 2: Create savepoint
Savepoint sp1 = [Link]("SP1");
// Step 3: Second insert
[Link]("INSERT INTO emp VALUES (2, 'B')");
// Step 4: Release the savepoint
[Link](sp1);
// ❌ Now this will cause error if attempted
// [Link](sp1); // INVALID (savepoint no longer exists)
// Step 5: Commit everything
[Link]();
[Link]("Transaction completed successfully!");
} catch (Exception e) {
[Link]();
[Link]();
Example program for exception handling
import [Link].*;
public class JDBCExceptionExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// Load driver (optional in modern JDBC)
[Link]("[Link]");
// Establish connection
conn = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "password"
);
stmt = [Link]();
// Intentionally wrong query (to generate exception)
[Link]("INSERT INTO emp VALUES ('A', 101)");
[Link]("Query executed successfully");
} catch (SQLException e) {
[Link]("SQLException occurred!");
[Link]("Message: " + [Link]());
[Link]("SQL State: " + [Link]());
[Link]("Error Code: " + [Link]());
} catch (ClassNotFoundException e) {
[Link]("Driver not found!");
} finally {
try {
if (stmt != null) [Link]();
if (conn != null) [Link]();
[Link]("Resources closed");
} catch (SQLException e) {
[Link]();
}
Ia 3 mod 5
develop a java program to connect to database, insert a new student record into the table and
display the confirmation message
import [Link].*;
public class StudentInsert {
public static void main(String[] args) {
try {
// Load JDBC Driver
[Link]("[Link]");
// Establish Connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password");
// SQL Insert Query
String query = "INSERT INTO student VALUES (101, 'Rahul', 85)";
// Create Statement
Statement st = [Link]();
// Execute Query
int rows = [Link](query);
// Display Confirmation Message
if(rows > 0) {
[Link]("Student record inserted successfully.");
// Close Connection
[Link]();
} catch(Exception e) {
[Link](e);
Q1️0 (c) Develop a Java program to retrieve and display all records from an employees table using
ResultSet.
Program
import [Link].*;
public class EmployeeDisplay {
public static void main(String[] args) {
try {
// Load JDBC Driver
[Link]("[Link]");
// Establish Connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/company",
"root",
"password");
// Create Statement
Statement st = [Link]();
// Execute Query
ResultSet rs = [Link](
"SELECT * FROM employees");
// Display Records
while([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
double salary = [Link]("salary");
[Link](
id + " " + name + " " + salary);
}
// Close Connection
[Link]();
} catch(Exception e) {
[Link](e);
}
}
}
Q1️0 (b) Compare Statement and ResultSet Objects in JDBC
Statement ResultSet
Statement is an interface used to execute SQL ResultSet is an interface used to store and process
queries in a database. the data returned by a query.
It is returned by the executeQuery() method of
It is created using the Connection object.
Statement.
Used to execute SQL commands such as SELECT, Used to retrieve records row by row from the
INSERT, UPDATE, and DELETE. database table.
It sends SQL statements to the database. It holds the output produced by the SQL query.
Methods include executeQuery(),
Methods include next(), getInt(), getString(), etc.
executeUpdate(), and execute().
Does not store actual table data. Stores query result data temporarily.
Used before ResultSet in JDBC workflow. Used after executing a SELECT query.
Example: ResultSet rs = [Link]("SELECT *
Example: Statement st = [Link]();
FROM emp");
Mainly responsible for data retrieval and
Mainly responsible for query execution.
navigation.
Can execute any SQL statement. Mostly associated with SELECT queries only.
Example
Statement st = [Link]();
ResultSet rs = [Link](
"SELECT * FROM employee");
Here:
Statement executes the SQL query.
ResultSet stores the records returned by the query.
Conclusion
Statement and ResultSet work together in JDBC.
The Statement object executes SQL queries, while the ResultSet object retrieves and processes the
resulting data from the database.
Objects Used in Establishing JDBC Connection
In JDBC, different objects are used to connect Java applications with databases and perform database
operations.
1️. DriverManager Object
The DriverManager class manages JDBC drivers and establishes connection between Java application
and database.
Use
Loads suitable JDBC driver
Creates database connection
Example
Connection con = [Link](
"jdbc:mysql://localhost:3306/test",
"root",
"password");
2️. Connection Object
Connection is an interface that represents the connection between Java application and database.
Use
Establishes session with database
Creates Statement and CallableStatement objects
Example
Connection con;
3. Statement Object
Used to execute normal SQL queries.
Use
Executes SELECT, INSERT, UPDATE, DELETE queries
Example
Statement st = [Link]();
4. PreparedStatement Object
Used to execute parameterized SQL queries.
Use
Improves security
Prevents SQL Injection
Example
PreparedStatement ps =
[Link](
"INSERT INTO student VALUES(?,?,?)");
5. CallableStatement Object
Used to call stored procedures from Java program.
Use
Executes stored procedures in database
Example
CallableStatement cs =
[Link]("{call procedure_name()}");
Program to Call Stored Procedure
Stored Procedure in MySQL
CREATE PROCEDURE getEmployee()
BEGIN
SELECT * FROM employee;
END;
Java Program
import [Link].*;
public class CallProcedure {
public static void main(String[] args) {
try {
// Load Driver
[Link]("[Link]");
// Establish Connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/company",
"root",
"password");
// Create CallableStatement
CallableStatement cs =
[Link]("{call getEmployee()}");
// Execute Stored Procedure
ResultSet rs = [Link]();
// Display Records
while([Link]()) {
[Link](
[Link](1) + " " +
[Link](2) + " " +
[Link](3));
// Close Connection
[Link]();
} catch(Exception e) {
[Link](e);
Output
101 Rahul 45000
102 Asha 50000
103 Kiran 42000
Conclusion
JDBC uses objects like DriverManager, Connection, Statement, and CallableStatement to establish
database connectivity and execute SQL operations. CallableStatement is specifically used to call
stored procedures from Java applications.