MODULE 1
Java Collection Framework – Key Interfaces and Classes
Introduction
The Java Collection Framework (JCF) is a set of interfaces, classes, and
algorithms that provides a standard way to store, manage, and manipulate groups
of objects efficiently. It offers ready-made data structures and improves code
reusability, flexibility, and performance.
Key Interfaces of Java Collection Framework
1. Collection Interface
Root interface of the collection hierarchy.
Represents a group of objects.
Provides basic methods such as:
add(), remove(), contains(), size(), isEmpty(), iterator().
2. List Interface
Represents an ordered collection.
Allows duplicate elements.
Supports positional access.
Examples: ArrayList, LinkedList, Vector.
3. Set Interface
Represents a collection that does not allow duplicate elements.
Used to store unique values.
Examples: HashSet, LinkedHashSet, TreeSet.
4. Queue Interface
Stores elements for processing.
Follows FIFO (First In First Out) principle.
Examples: PriorityQueue, LinkedList.
5. Deque Interface
Double-ended queue.
Allows insertion and deletion from both ends.
Example: ArrayDeque, LinkedList.
6. Map Interface
Stores key-value pairs.
Each key must be unique.
Examples: HashMap, TreeMap, Hashtable.
Key Classes of Java Collection Framework
1. ArrayList
Dynamic array implementation of List.
Fast retrieval of elements.
Slower insertion/deletion in middle.
2. LinkedList
Doubly linked list implementation.
Efficient insertion and deletion.
• Suitable for scenarios requiring frequent insertion/removal at the beginning/end.
3. HashSet
Stores unique elements using hashing.
No guaranteed order.
Implements the Set interface using a hash table.
Provides constant-time performance for basic operations on average.
4. TreeSet
Stores unique elements in sorted order.
5. HashMap
Stores key-value pairs.
Fast searching and retrieval.
Provides key-value mapping with constant-time performance for basic
operations on average.
Does not guarantee order of key-value pairs.
Algorithms:
• The Collections class provides various static methods for operating on collections.
• Includes algorithms for sorting (sort()), searching (binarySearch()), shuffling
(shuffle()), reversing (reverse()), etc.
• These methods are useful for manipulating collections without the need for writing
custom code.
METHODS IN COLLECTIONS
For all use Object obj
of add method use E e
List Interface (Extends Collection):
Represents ordered collection of elements (duplicates allowed).
Important Methods:
void add(int index, E element) – Adds element at specified index.
E get(int index) – Returns element at given index.
E set(int index, E element) – Replaces element at index.
E remove(int index) – Removes element at index.
int indexOf(Object o) – First occurrence index.
int lastIndexOf(Object o) – Last occurrence index.
ListIterator<E> listIterator() – Iterator for forward and backward traversal.
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
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);
Important Methods of Spliterator Interface
Rest study from model paper
1. tryAdvance()
Processes the next available element and performs the specified action.
It returns true if an element is processed, otherwise false.
2. trySplit()
Splits the spliterator into two parts for parallel processing.
It returns a new spliterator if splitting is possible.
3. estimateSize()
Returns the estimated number of elements remaining to be traversed.
4. characteristics()
Returns the characteristics of the spliterator such as
ORDERED, SORTED, DISTINCT, SIZED, etc.
5. hasCharacteristics(int characteristics)
Checks whether the spliterator has a specific characteristic.
Returns true if present, otherwise false.
6. getComparator()
Returns the comparator used for sorting elements.
It is applicable only when the spliterator has the SORTED characteristic.
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.
Difference between list and set
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
Difference Between Array and ArrayList in Java
Feature Array ArrayList
Fixed size (cannot change
Size Dynamic size (can grow or shrink)
after creation)
Part of Java Collections Framework
Package Part of Java language
([Link])
Can store primitive and
Data types Stores objects only
objects
Slightly slower due to dynamic
Performance Faster because it has fixed size
resizing
Many built-in methods like add(),
Methods Limited built-in methods
remove(), 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);
create a student class with fields age, name, and roll number. Develop a Java code
snippet to store multiple student objects in the ArrayList. Use iterator to display
details of each student.
import [Link].*;
class Student {
int age;
String name;
int rollNo;
Student(int age, String name, int rollNo) {
[Link] = age;
[Link] = name;
[Link] = rollNo;
public class StudentDemo {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
[Link](new Student(20, "Mahira", 101));
[Link](new Student(21, "Arun", 102));
[Link](new Student(19, "Sneha", 103));
Iterator<Student> itr = [Link]();
while([Link]()) {
Student s = [Link]();
[Link]("Age: " + [Link] +
", Name: " + [Link] +
", Roll No: " + [Link]);
Develop a Java program that stores a list of integers in a linked list and apply
reverse order comparator to sort it in descending order. Then use appropriate
methods from the collections class to reverse shuffle and find the minimum and
maximum value in the list.
import [Link].*;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
[Link](10);
[Link](40);
[Link](20);
[Link](50);
[Link](30);
[Link]("Original List: " + list);
// Sort in descending order using reverse order comparator
[Link](list, [Link]());
[Link]("Descending Order: " + list);
// Reverse the list
[Link](list);
[Link]("Reversed List: " + list);
// Shuffle the list
[Link](list);
[Link]("Shuffled List: " + list);
// Find minimum value
[Link]("Minimum Value: " + [Link](list));
// Find maximum value
[Link]("Maximum Value: " + [Link](list));
}
}
Difference between Comparator and Comparable Interface
Comparable Interface Comparator Interface
Used to define natural/default sorting
Used to define custom sorting order
order
Present in [Link] package Present in [Link] package
Contains compareTo() method Contains compare() method
Comparable Interface Comparator Interface
Sorting logic is written inside the class Sorting logic is written in a separate
itself class/object
Used for single sorting sequence Used for multiple sorting sequences
Modifies original class Does not modify original class
1. Comparable Interface
Used when an object has a default natural ordering
Implemented by the class whose objects are being compared
Method:
compareTo(Object obj)
Example:
Sorting students by roll number
class Student implements Comparable<Student> {
public int compareTo(Student s) {
return [Link] - [Link];
}
}
2. Comparator Interface
Used for custom sorting
Implemented in a separate class or using lambda expression
Method:
compare(Object o1, Object o2)
Example:
Sorting students by age
Comparator<Student> comp = (s1, s2) -> [Link] - [Link];
Key Difference (easy to remember)
Comparable → Inside class → One default sorting
Comparator → Outside class → Many custom sorting
Exam-ready answer
The Comparable interface is used for defining the natural ordering of objects and
contains the compareTo() method. It is present in the [Link] package.
The Comparator interface is used for custom ordering of objects and contains the
compare() method. It is present in the [Link] package and allows multiple sorting
sequences.
Module 2
What is string in java
Definition (Exam-Ready)
A String is an object of the String class that represents a sequence of characters.
Strings in Java are immutable, meaning their contents cannot be changed after
creation.
Data Conversion Using [Link]() (Exam-Ready Answer)
Definition
[Link]() is a static method of the String class used to convert different data
types into their String representation (human-readable form).
Key Points
1. valueOf() is overloaded for all Java primitive data types such as int, double,
long, float, boolean, and char.
2. It is also overloaded for the Object type, allowing any object to be converted
to a String.
3. When an object is passed to valueOf(), it internally calls the object's toString()
method.
4. It is commonly used when a String representation of another data type is
required, such as during string concatenation.
Syntax
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[])
Special Form
static String valueOf(char chars[], int startIndex, int numChars)
Where:
chars → character array
startIndex → starting position in the array
numChars → number of characters to include
This version creates a String from a specified portion of a character array.
Program
public class SimpleValueOfExample {
public static void main(String[] args) {
// Integer to String
int intValue = 100;
String intString = [Link](intValue);
[Link]("Integer to String: " + intString);
// Double to String
double doubleValue = 50.25;
String doubleString = [Link](doubleValue);
[Link]("Double to String: " + doubleString);
// Boolean to String
boolean boolValue = false;
String boolString = [Link](boolValue);
[Link]("Boolean to String: " + boolString);
// Char to String
char charValue = 'Z';
String charString = [Link](charValue);
[Link]("Char to String: " + charString);
}
}
Output
Integer to String: 100
Double to String: 50.25
Boolean to String: false
Char to String: Z
Why is String Immutable in Java? Explain its Benefits. (5 Marks)
A String is immutable in Java, which means once a String object is created, its
contents cannot be changed. Any operation that appears to modify a String actually
creates a new String object.
Example
String s = "Hello";
s = s + " Java";
Here, a new String object "Hello Java" is created, while the original "Hello" remains
unchanged.
Benefits of String Immutability
1. Security
o Strings are widely used for storing sensitive information such as
usernames, passwords, file paths, and network connections.
o Immutability prevents unauthorized modification of these values.
2. Memory Efficiency
o Java uses a String Pool to store string literals.
o Multiple references can share the same String object safely because its
contents cannot change.
3. Thread Safety
o Since Strings cannot be modified, multiple threads can access the
same String object without synchronization.
4. Reliable Hash Codes
o Strings are commonly used as keys in collections such as HashMap.
o Because a String's value never changes, its hash code remains
constant, ensuring correct retrieval of data.
5. Simpler and More Reliable Programs
o Immutability avoids accidental modifications and makes programs
easier to understand, debug, and maintain.
Conclusion
String immutability improves security, memory management, thread safety,
reliability, and performance, making Strings safe and efficient for use in Java
applications.
Compare == and equals() Method When Comparing String Objects in Java (5
Marks)
In Java, both == and equals() are used to compare strings, but they compare
different things.
== Operator equals() Method
Compares the references (memory Compares the contents (character
locations) of two String objects. sequences) of two String objects.
Returns true only if both references point Returns true if the contents of both strings
to the same object. are identical.
Used for reference comparison. Used for content comparison.
Example Program
public class StringComparison {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
[Link](str1 == str2);
[Link](str1 == str3);
[Link]([Link](str2));
[Link]([Link](str3));
}
Output
true
false
true
true
Explanation
str1 == str2 returns true because both refer to the same string literal stored in
the String Pool.
str1 == str3 returns false because str3 is a new object created using new
String(), so it has a different memory location.
[Link](str2) returns true because both strings contain "Hello".
[Link](str3) returns true because the contents of both strings are the
same.
Explain How append() Works in StringBuffer and How It Differs from Using + in
String (5 Marks)
The append() method of the StringBuffer class is used to add characters, strings, or
other data to the end of an existing StringBuffer object. Since StringBuffer is
mutable, the contents of the same object are modified without creating a new object.
Example
StringBuffer sb = new StringBuffer("Hello");
[Link](" Java");
[Link](sb);
Output:
Hello Java
In contrast, Strings are immutable. When the + operator is used for concatenation, a
new String object is created every time.
Example
String s = "Hello";
s = s + " Java";
[Link](s);
Output:
Hello Java
Although the output is the same, the original String "Hello" is not modified; a new
String object "Hello Java" is created.
Difference Between append() and +
append() (StringBuffer) + Operator (String)
Modifies the existing object. Creates a new String object.
Works on mutable objects. Works on immutable objects.
Faster and more efficient. Slower for repeated concatenations.
Uses more memory due to creation of multiple
Uses less memory.
objects.
Suitable for frequent string
Suitable for simple string concatenation.
modifications.
toString() Method (Simple Explanation)
1. toString() is a method defined in the Object class, so every Java class
automatically gets it.
2. By default, toString() returns information like the class name and memory
address, which is usually not very useful.
3. Therefore, we often override toString() to return a meaningful, human-
readable description of an object.
Syntax:
String toString()
4. To override toString(), simply return a String containing the information you
want to display.
5. Once overridden, the object can be printed directly using [Link]()
and used in string concatenation.
class Box
double width; double height; double depth;
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
public String toString()
return "Dimensions are " + width + " by " + depth + " by " + height + "."; }
class toStringDemo
{
public static void main(String args[])
Box b = new Box(10, 12, 14);
String s = "Box b: " + b;
[Link](b);
[Link](s);
The output of this program is shown here:
Dimensions are 10.0 by 14.0 by 12.0
Box b: Dimensions are 10.0 by 14.0 by 12.0
.
Java Program to Sort an Array of String Objects Using Bubble Sort and compareTo()
public class BubbleSortStrings {
public static void main(String[] args) {
String[] names = {
"Mango",
"Apple",
"Banana",
"Orange",
"Grapes"
};
int n = [Link];
// Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (names[j].compareTo(names[j + 1]) > 0) {
// Swap the strings
String temp = names[j];
names[j] = names[j + 1];
names[j + 1] = temp;
}
[Link]("Strings in Ascending Order:");
for (String name : names) {
[Link](name);
Module 3
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 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);
}
Key features of swing using example and event handling program
import [Link].*;
import [Link].*;
public class SwingDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Swing Demo");
JLabel l = new JLabel("Welcome to Swing");
[Link](50, 30, 150, 30);
JButton b = new JButton("Click");
[Link](50, 80, 100, 30);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked");
}
});
[Link](l);
[Link](b);
[Link](300, 200);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
Build a program to demonstrate an icon-based button. Each button will display an
icon that represents the flag of a country. When a button is pressed, the name of that
country is displayed in the label.
import [Link].*;
import [Link].*;
public class FlagButtonDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Country Flags");
JLabel label = new JLabel("Select a Country");
[Link](120, 150, 150, 30);
// Load flag images
ImageIcon indiaIcon = new ImageIcon("[Link]");
ImageIcon usaIcon = new ImageIcon("[Link]");
ImageIcon ukIcon = new ImageIcon("[Link]");
JButton india = new JButton(indiaIcon);
JButton usa = new JButton(usaIcon);
JButton uk = new JButton(ukIcon);
[Link](20, 30, 80, 50);
[Link](120, 30, 80, 50);
[Link](220, 30, 80, 50);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("India");
});
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("USA");
});
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("United Kingdom");
});
[Link](india);
[Link](usa);
[Link](uk);
[Link](label);
[Link](350, 250);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Develop a Java Swing application using JFrame that displays a simple form
with the following components:
1. A Label and Text Field for Name
2. A Label and Text Field for Age
3. A Submit button
When the Submit button is clicked, display the entered Name and Age using a
message dialog box
import [Link].*;
import [Link].*;
public class FormDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Student Form");
JLabel l1 = new JLabel("Name:");
JLabel l2 = new JLabel("Age:");
JTextField t1 = new JTextField();
JTextField t2 = new JTextField();
JButton b = new JButton("Submit");
[Link](50, 50, 100, 30);
[Link](150, 50, 120, 30);
[Link](50, 100, 100, 30);
[Link](150, 100, 120, 30);
[Link](100, 150, 100, 30);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = [Link]();
String age = [Link]();
[Link](
f,
"Name: " + name + "\nAge: " + age
);
}
});
[Link](l1);
[Link](t1);
[Link](l2);
[Link](t2);
[Link](b);
[Link](350, 250);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
Develop a Java Swing program that contains two text fields for entering numbers, a
button labeled 'Add', and a text field to display the result. When the user clicks the
Add button, the program should add the two numbers and display the sum.
import [Link].*;
import [Link].*;
public class SimpleCalculator {
public static void main(String[] args) {
JFrame f = new JFrame("Calculator");
JTextField t1 = new JTextField();
JTextField t2 = new JTextField();
JTextField t3 = new JTextField();
JButton b = new JButton("Add");
[Link](50, 30, 100, 30);
[Link](50, 70, 100, 30);
[Link](50, 150, 100, 30);
[Link](50, 110, 100, 30);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
int a = [Link]([Link]());
int b = [Link]([Link]());
int sum = a + b;
[Link]([Link](sum));
});
[Link](t1);
[Link](t2);
[Link](t3);
[Link](b);
[Link](250, 250);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
Develop a Java Swing JApplet that contains a menu bar with a 'Color' menu. The
menu should contain three menu items: Red, Green, and Blue. When the user
selects a menu item, the background color of the applet should change accordingly
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorMenuDemo extends JApplet {
public void init() {
JMenuBar mb = new JMenuBar();
JMenu color = new JMenu("Color");
JMenuItem red = new JMenuItem("Red");
JMenuItem green = new JMenuItem("Green");
JMenuItem blue = new JMenuItem("Blue");
[Link](red);
[Link](green);
[Link](blue);
[Link](color);
setJMenuBar(mb);
[Link](e -> getContentPane().setBackground([Link]));
[Link](e ->
getContentPane().setBackground([Link]));
[Link](e -> getContentPane().setBackground([Link]));
}
Module 4
JSP Tags
JSP Tags are special tags used to insert Java code into HTML pages. They help
create dynamic web applications. JSP scripting elements are processed by the JSP
engine during page execution.
1. JSP Scriptlet Tag
Used to write and execute Java code in a JSP page.
Code is placed inside the _jspService() method.
Syntax:
<% Java code %>
Example:
<html>
<body>
<% [Link]("Welcome to JSP"); %>
</body>
</html>
2. JSP Declaration Tag
Used to declare variables and methods.
Code is placed outside the _jspService() method.
Syntax:
<%! declaration %>
Example:
<%! int data = 50; %> //variable declaration
<%!
int cube(int n){ //method declaraiton
return n*n*n;
%>
<%= cube(3) %>
3. JSP Expression Tag
Used to display the value of an expression directly in the browser.
Syntax:
<%= expression %>
Example:
<%= 2*5 %>
4. JSP Directive Tag
Provides instructions to the JSP container on how the jsp page should be processed
Syntax:
<%@ directive attribute="value" %>
Types:
Page Directive: Imports packages.
<%@ page import="[Link]" %>
Include Directive: Includes another file.
<%@ include file="[Link]" %>
Taglib Directive: Uses custom tags.
<%@ taglib uri="uri" prefix="mytag" %>
5. JSP Comment Tag
Used for comments that are ignored by the JSP container.
Syntax:
<%-- This is a JSP comment --%>
Conclusion
The main JSP tags are Scriptlet, Declaration, Expression, Directive, and
Comment Tags. They allow Java code to be embedded in HTML, making JSP
suitable for developing dynamic web pages.
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
ServletRequest, HttpServletRequest,
Request/Response
ServletResponse HttpServletResponse
Session Handling Not included Includes HttpSession
Cookies Not included Includes Cookie
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>
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>");
develop a java servlet program to accept two parameters from webpage find the sum
of them and display the result on the webpage. Also give necessary html script to
create a web page
HTML Page ([Link])
<html>
<body>
<h2>Add Two Numbers</h2>
<form action="SumServlet" method="post">
First Number:
<input type="text" name="num1"><br><br>
Second Number:
<input type="text" name="num2"><br><br>
<input type="submit" value="Find Sum">
</form>
</body>
</html>
Servlet Program ([Link])
import [Link].*;
import [Link].*;
import [Link].*;
public class SumServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
int n1 = [Link](
[Link]("num1"));
int n2 = [Link](
[Link]("num2"));
int sum = n1 + n2;
[Link]("<html>");
[Link]("<body>");
[Link]("<h2>Sum = " + sum + "</h2>");
[Link]("</body>");
[Link]("</html>");
}
}
[Link]
<web-app>
<servlet>
<servlet-name>SumServlet</servlet-name>
<servlet-class>SumServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SumServlet</servlet-name>
<url-pattern>/SumServlet</url-pattern>
</servlet-mapping>
</web-app>
Develop a Java servlet program that accepts a username and password from an
HTML form and displays a welcome message if the credential matches predefined
values.
HTML Page ([Link])
<html>
<body>
<h2>Login Form</h2>
<form action="LoginServlet" 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>
Servlet Program ([Link])
import [Link].*;
import [Link].*;
import [Link].*;
public class LoginServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String user = [Link]("username");
String pass = [Link]("password");
if([Link]("admin") && [Link]("1234"))
{
[Link]("<h2>Welcome " + user + "</h2>");
}
else
{
[Link]("<h2>Invalid Username or Password</h2>");
}
}
}
[Link]
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
The jsp page that accepts a username and age stores them in a session attribute
and displays the personalized message using those attributes.
HTML Page ([Link])
<html>
<body>
<form action="[Link]">
Username:
<input type="text" name="username"><br><br>
Age:
<input type="text" name="age"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
[Link]
<%
String username = [Link]("username");
String age = [Link]("age");
// Store values in session
[Link]("username", username);
[Link]("age", age);
[Link]("[Link]");
%>
[Link]
<%
String username = (String)[Link]("username");
String age = (String)[Link]("age");
%>
<h2>Welcome <%= username %>!</h2>
<p>Your age is <%= age %>.</p>
What is a Java Servlet? Explain its Role in Web Development. (5 Marks)
A Java Servlet is a server-side Java program used to create dynamic web pages
and web applications. It runs inside a web container such as Apache Tomcat and
processes requests from clients (web browsers), then sends responses back to
them.
Role of Servlets in Web Development
1. Handles Client Requests – Receives and processes requests from web
browsers.
2. Generates Dynamic Content – Creates dynamic web pages based on user
input.
3. Processes Form Data – Reads data submitted through HTML forms.
4. Manages Sessions – Maintains user information across multiple requests.
5. Interacts with Databases – Retrieves and stores data using JDBC.
Module 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);
Q10 (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);
}
}
}
Q10 (b) Compare Statement and ResultSet Objects in JDBC
Statement ResultSet
Statement is an interface used to ResultSet is an interface used to store
execute SQL queries in a database. and process the data returned by a query.
It is returned by the executeQuery()
It is created using the Connection object.
method of Statement.
Used to execute SQL commands such
Used to retrieve records row by row from
as SELECT, INSERT, UPDATE, and
the database table.
DELETE.
It sends SQL statements to the It holds the output produced by the SQL
database. query.
Methods include executeQuery(), Methods include next(), getInt(),
executeUpdate(), and execute(). getString(), etc.
Does not store actual table data. Stores query result data temporarily.
Used before ResultSet in JDBC
Used after executing a SELECT query.
workflow.
Example: ResultSet rs =
Example: Statement st =
[Link]("SELECT * FROM
[Link]();
emp");
Mainly responsible for data retrieval and
Mainly responsible for query execution.
navigation.
Statement ResultSet
Mostly associated with SELECT queries
Can execute any SQL statement.
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.
Significance of JDBC (5 Marks)
JDBC (Java Database Connectivity) is a Java API that enables communication
between Java applications and databases. It provides a standard interface for
connecting to different database management systems (DBMS) and executing SQL
statements.
Significance of JDBC:
1. Provides database connectivity between Java applications and various
databases.
2. Offers a standard API, allowing Java programs to work with different SQL
databases in a uniform way.
3. Supports multiple databases through JDBC drivers, making it possible to
connect to heterogeneous database environments.
4. Enables execution of SQL queries such as SELECT, INSERT, UPDATE,
and DELETE.
5. Retrieves and processes results returned by the database for further
application processing.
Transactions
• A transaction is a set of actions to be carried out as a single, atomic action. Either
all of the
actions are carried out, or none of them are.
• Transaction is successfully completed only if each task is comleted successfully. If
one of task is
fail, the entire transaction is fail.
• If one of sql is failed, the sql statement that is executed successfully upto the point
in the
transaction must be rollback.
• Different methods of Transaction processing are:
• setAutoCommit(boolean)-setAutoCommit() pass the parameter as false intial once
all
the transcation is completed. As soon as it invokes the commit() ,the
setAutoCommit()
method is set as true.
• setSavePoint(String);-set the save point to the sql statement .
• releaseSavePoint(String);-it realse the save point assing to the sql statement if and
only
if all sql statement are executed successfully.
• commit();-once all sql statement are executed successfully,rollback is not possible.
• rollback();-if one of the sql statement is failed,then rollback() method is invoked and
control goes back to the fail sql statement for further execution.
Program:
import [Link].*;
class A
A()
try
{
[Link](“[Link]”);
Connection c=[Link](“JDBC:ODBC:CSB”);
Statement s=[Link]();
[Link](false);
[Link](“csb”);
ResultSet r=[Link](“Select *from emp where usn=2”);
r=[Link](“Select *from emp”);
[Link](“csb”);
[Link]();
[Link]();
catch(Exception e)
S.o.p(e);
[Link]();
public static void main(String ar[])
A a1=new A();
}
Prepared and callable statements
PreparedStatement Object (5 Marks)
PreparedStatement is a JDBC interface that extends the Statement interface. It is
used to execute parameterized SQL queries, where values can be supplied
dynamically at runtime.
Features
Allows dynamic input using placeholders (?) in SQL queries.
More flexible and efficient than a normal Statement.
Values are assigned to placeholders using setXXX() methods.
Syntax
PreparedStatement p =
[Link]("SELECT name FROM emp WHERE usn=?");
setXXX() Method
[Link](1, "12CS001");
The first parameter represents the position (index) of the ?.
The second parameter represents the value that replaces the ?.
XXX represents the Java data type, such as setString(), setInt(), etc.
Execution Methods
executeQuery() – Executes SELECT statements.
executeUpdate() – Executes INSERT, UPDATE, and DELETE statements.
execute() – Executes any SQL statement.
Example:
import [Link].*;
class A
{
public static void main(String ar[])
try
[Link]("[Link]");
Connection c =
[Link]("JDBC:ODBC:CSB");
PreparedStatement p =
[Link](
"select * from emp where usn=?");
[Link](1, "12cs001");
ResultSet r = [Link]();
while([Link]())
{
String name = [Link](1);
String usn = [Link](2);
[Link]("name = " + name);
[Link]("USN = " + usn);
[Link]();
catch(Exception e)
[Link](e);
}
}
CallableStatement Object (5 Marks)
CallableStatement is a JDBC object used to call and execute stored procedures in
a database. It is created using the Connection object through the prepareCall()
method.
Types of Parameters
1. IN Parameter
o Used to pass input values to the stored procedure.
o Values are set using setXXX() methods.
2. OUT Parameter
o Used to receive values returned by the stored procedure.
o Values are retrieved using getXXX() methods.
3. INOUT Parameter
o Used for both input and output.
o Values are set using setXXX() and retrieved using getXXX() methods.
Important Methods
prepareCall() – Creates a CallableStatement object.
registerOutParameter() – Registers an OUT or INOUT parameter and
specifies its data type.
setXXX() – Sets input values for parameters.
getXXX() – Retrieves output values returned by the stored procedure.
CREATE PROCEDURE getEmpName
IN empId INT,
OUT empName VARCHAR(50)
import [Link].*;
class A
public static void main(String args[])
try
{
[Link]("[Link]");
Connection c =
[Link]("JDBC:ODBC:CSB");
CallableStatement cs =
[Link]("{call getEmpName(?, ?)}");
[Link](1, 101); // IN parameter
[Link](2, [Link]); // OUT parameter
[Link]();
String name = [Link](2);
[Link]("Employee Name = " + name);
[Link]();
catch(Exception e)
[Link](e);
}
}