T.Y. [Link].
(Computer Science)
Semester VI — CS-365
OBJECT ORIENTED PROGRAMMING USING JAVA – II
Complete Question Bank with Answers
(2019 Pattern | CBCS | All Previous Year Papers Covered)
Exam Duration 2 Hours Maximum Marks 35
Pattern 2019 (Revised) Paper Paper V
Years Covered 2022 – 2025 Exam Types April & November
Unit Topics Covered
1 Java Collections Framework – List, Set, Map, Iterator, ArrayList, LinkedList, HashSet, TreeSet, Hashtable
2 JDBC – Architecture, Drivers, Connection, Statement, PreparedStatement, ResultSet, Transactions
3 Multithreading – Thread, Runnable, Life Cycle, sleep(), join(), yield(), Synchronization, Inter-thread Comm.
4 Servlets – Life Cycle, doGet, doPost, CGI vs Servlet, Session, Cookies
5 JSP – Components, Directives, Scriptlets, Expressions, Implicit Objects, Life Cycle
6 Spring Framework – Architecture, Modules, Applications
SECTION A — 1 Mark Questions (Short Definitions)
Unit 1: Java Collections Framework
Q. Define Collection / What is Collection?
A Collection is a framework in Java that provides a unified architecture to store and manipulate a group
of objects. It is defined in the [Link] package and includes interfaces like List, Set, Map and classes
like ArrayList, LinkedList, HashSet, TreeSet, HashMap, etc.
Q. Define List Interface.
The List interface extends Collection and allows ordered, duplicate elements. Elements can be
accessed by their index (position). Key implementations: ArrayList, LinkedList, Vector, Stack.
Q. Define Set / Define Set Interface.
The Set interface extends Collection and does not allow duplicate elements. It does not guarantee
insertion order (except LinkedHashSet). Key implementations: HashSet, TreeSet, LinkedHashSet.
Q. Which interface is implemented by HashSet class?
HashSet implements the Set interface (and internally uses a HashMap). It does not allow duplicates
and does not maintain insertion order.
Q. Which interface is implemented by TreeSet class?
TreeSet implements the SortedSet interface (which extends Set). It stores elements in ascending
sorted order and does not allow duplicates.
Q. State constructors of TreeSet class.
TreeSet has four constructors:
1. TreeSet() – creates empty TreeSet sorted in natural order
2. TreeSet(Collection c) – creates TreeSet from a collection
3. TreeSet(Comparator comp) – creates TreeSet with custom comparator
4. TreeSet(SortedSet ss) – creates TreeSet from a SortedSet
Q. Define Map Interface.
The Map interface stores data as key-value pairs. Each key must be unique; values can be duplicate. It
is NOT a child interface of Collection. Key implementations: HashMap, TreeMap, LinkedHashMap,
Hashtable.
Q. Define Hashtable.
Hashtable is a legacy class in [Link] that implements the Map interface. It stores key-value pairs
where neither keys nor values can be null. It is thread-safe (synchronized). Example:
Hashtable<String,Integer> ht = new Hashtable<>();
Q. Define Iterator Interface.
Iterator is an interface in [Link] used to traverse (iterate over) elements of a Collection one by one.
Methods: hasNext() – returns true if more elements exist; next() – returns next element; remove() –
removes current element.
Q. What is ArrayList?
ArrayList is a resizable-array implementation of the List interface. It allows duplicate elements,
maintains insertion order, allows null values, and provides fast random access. Package: [Link].
Example: ArrayList<String> al = new ArrayList<>();
Q. List any two collection interfaces.
1. List – ordered collection allowing duplicates (e.g., ArrayList)
2. Set – unordered collection not allowing duplicates (e.g., HashSet)
(Also: Queue, Map, Deque)
Unit 2: JDBC
Q. What is JDBC? / Define JDBC.
JDBC (Java Database Connectivity) is an API in Java ([Link] package) that provides a standard way
to connect and interact with relational databases. It allows Java programs to execute SQL queries,
update data, and retrieve results from databases like MySQL, Oracle, etc.
Q. Give the name of JDBC API.
The main JDBC API packages and key interfaces/classes are:
Package: [Link] and [Link]
Key interfaces: Connection, Statement, PreparedStatement, CallableStatement, ResultSet,
DatabaseMetaData, ResultSetMetaData
Key class: DriverManager
Q. What is use of getConnection()?
getConnection() is a static method of the DriverManager class used to establish a connection to the
database.
Syntax: Connection con = [Link](url, username, password);
Example: [Link]("jdbc:mysql://localhost:3306/mydb", "root", "1234");
Q. What is use of forName()? / What is purpose of [Link]()?
[Link]() is used to dynamically load the JDBC driver class at runtime.
Example: [Link]("[Link]");
It registers the driver with the DriverManager so that database connections can be established.
Q. What is metadata?
Metadata means 'data about data'. In JDBC:
• DatabaseMetaData – provides info about the database (name, version, tables, etc.)
• ResultSetMetaData – provides info about columns in a ResultSet (column count, name, type, etc.)
Q. Define ResultSet Interface.
ResultSet is an interface in [Link] that holds the data returned by a SELECT query. It maintains a
cursor pointing to rows. Key methods: next() – moves to next row; getString(col), getInt(col) – fetch
column values; close() – releases resources.
Q. What is use of callable Statement?
CallableStatement is used to execute stored procedures in the database.
Syntax: CallableStatement cs = [Link]("{call procedureName(?,?)}");
It can handle IN, OUT, and INOUT parameters.
Q. What is use of commit() method?
commit() is a method of the Connection interface. It is used to permanently save all changes made in
the current transaction to the database. It is used when auto-commit is disabled:
[Link](false); ... [Link]();
Unit 3: Multithreading
Q. Define Multithreading. / What is multithreading?
Multithreading is a feature of Java that allows concurrent execution of two or more threads. A thread is
the smallest unit of a process. Multithreading enables CPU utilization, faster execution, and better
performance for tasks like animations, games, and server applications.
Q. What is a Thread?
A Thread is a lightweight sub-process and the smallest unit of execution in a Java program. The Thread
class is in the [Link] package. Every Java program has at least one thread (the main thread).
Threads share the process memory.
Q. How to start a Thread? / How to create a thread?
Two ways to create a thread:
1. Extend Thread class: class MyThread extends Thread { public void run(){...} }
Start: new MyThread().start();
2. Implement Runnable interface: class MyRun implements Runnable { public void run(){...} }
Start: new Thread(new MyRun()).start();
Q. What is interthread communication?
Inter-thread communication is a mechanism that allows synchronized threads to communicate with
each other. It uses three methods defined in the Object class:
• wait() – releases lock and waits
• notify() – wakes up one waiting thread
• notifyAll() – wakes up all waiting threads
Q. What is use of wait()?
wait() is a method of the Object class. It causes the current thread to release the object's lock and enter
the WAITING state until another thread calls notify() or notifyAll() on the same object. Must be called
inside a synchronized block.
Q. Write the purpose of join().
join() is a method of the Thread class. It causes the currently running thread to wait until the thread on
which join() is called finishes its execution. Example: [Link](); – the main thread waits for t1 to
complete.
Q. Write the use of yield().
yield() is a static method of the Thread class. It causes the currently executing thread to pause
temporarily and allow other threads of the same or higher priority to execute. It is a hint to the thread
scheduler.
Q. Define Thread Priority. / What is default priority in multithreading?
Thread priority is an integer value (1 to 10) that determines the order of thread execution.
• MIN_PRIORITY = 1
• NORM_PRIORITY = 5 (default)
• MAX_PRIORITY = 10
Methods: setPriority(int p), getPriority()
Unit 4: Servlets
Q. What is servlet?
A Servlet is a server-side Java program that handles HTTP requests and generates dynamic web
responses. It runs on a web/application server (e.g., Tomcat). Servlets are more efficient than CGI as
they run inside the JVM and handle multiple requests using threads.
Q. List the types of Servlets.
Two main types:
1. GenericServlet – protocol-independent servlet (service() method)
2. HttpServlet – HTTP-specific servlet (doGet(), doPost(), doPut(), doDelete() methods)
Q. Give syntax of doGet() method.
Syntax:
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException { ... }
Q. What are the parameters of doPost()?
doPost() takes two parameters:
1. HttpServletRequest request – contains client request data
2. HttpServletResponse response – used to send data back to client
Q. Define Session. / What is session?
A session is a mechanism to maintain state (user data) across multiple HTTP requests from the same
user. Since HTTP is stateless, sessions allow the server to remember users. Created using:
HttpSession session = [Link]();
Q. Define cookie. / What is cookie?
A cookie is a small piece of information stored on the client's browser by the server. It is used for
session tracking. Created using: Cookie c = new Cookie("name", "value");
[Link](c);. Retrieved using: [Link]();
Q. How to activate Session in Servlet?
Use the getSession() method of HttpServletRequest:
HttpSession session = [Link](true); – creates new session if not exists
HttpSession session = [Link](false); – returns existing session or null
Unit 5: JSP (JavaServer Pages)
Q. What is JSP?
JSP (JavaServer Pages) is a server-side technology used to create dynamic web content by embedding
Java code into HTML pages. JSP files are automatically compiled into Servlets by the JSP container.
File extension: .jsp.
Q. How to represent expression in JSP?
A JSP Expression is written as: <%= expression %>
It evaluates the expression and outputs its result directly into the HTML page.
Example: <%= new [Link]() %> displays the current date.
Q. What is scriplet?
A JSP Scriptlet contains Java code that is executed when the page is processed. Syntax: <% Java
code %>
Example: <% int x = 10; [Link](x); %>
Scriptlet code goes inside the _jspService() method.
Q. What is purpose of JSP directives?
JSP Directives provide global information about an entire JSP page. They are processed at translation
time (when JSP is converted to Servlet). Syntax: <%@ directive attribute="value" %>
Three types: page, include, taglib
Q. List any two implicit objects in JSP.
1. request – HttpServletRequest object; used to get request parameters
2. response – HttpServletResponse object; used to send response
3. out – JspWriter; used to write output to browser
4. session – HttpSession object for session management
Q. Write syntax of comment in JSP.
JSP Comment: <%-- comment --%> (not sent to client)
HTML Comment: <!-- comment --> (sent to client)
Java Comment inside scriptlet: <% // single line or /* multi-line */ %>
Unit 6: Spring Framework
Q. What is Spring Framework? / Define spring framework.
Spring is an open-source, lightweight Java framework used to build enterprise-level applications. It
provides features like Dependency Injection (DI), Aspect-Oriented Programming (AOP), MVC
architecture, JDBC abstraction, and transaction management. It simplifies Java development.
Q. List modules in Spring.
Key Spring modules:
1. Spring Core – Dependency Injection and IoC container
2. Spring MVC – Web MVC framework
3. Spring JDBC – Database access simplified
4. Spring AOP – Aspect-Oriented Programming
5. Spring ORM – Integration with Hibernate, JPA
6. Spring Security – Authentication and authorization
7. Spring Boot – Rapid application development
Q. Write any one application of Spring.
1. Web Applications – Spring MVC is used to build RESTful and traditional web apps
2. Microservices – Spring Boot helps build microservice-based architectures
3. Enterprise Applications – Banking, insurance, e-commerce backends
SECTION B — 2 Mark Questions
Unit 1: Collections
Q. Differentiate between List and Set interface.
Feature List Interface Set Interface
Duplicates Allowed Not Allowed
Order Maintains insertion order No guaranteed order (TreeSet is sorted)
Index Access Yes (get(index)) No
Null Values Multiple nulls allowed At most one null
Implementations ArrayList, LinkedList HashSet, TreeSet
Q. Differentiate between Iterator and ListIterator.
Feature Iterator ListIterator
Direction Forward only Both forward & backward
Applicable to Any Collection List only
Add element Not possible add() method available
Index No index methods nextIndex(), previousIndex()
Q. Write any two differences between ArrayList and LinkedList.
Feature ArrayList LinkedList
Internal Structure Dynamic array Doubly linked list
Access Speed Fast (O(1) random access) Slow (O(n) sequential)
Insert/Delete Slow (shifting needed) Fast (pointer update)
Memory Less (no extra pointers) More (stores prev/next pointers)
Q. What is Map interface and how to implement it?
Map stores data as key-value pairs. Keys must be unique.
Implementation example:
import [Link].*;
HashMap<String,Integer> map = new HashMap<>();
[Link]("Alice", 90);
[Link]("Bob", 85);
[Link]([Link]("Alice")); // 90
for([Link]<String,Integer> e : [Link]())
[Link]([Link]()+" = "+[Link]());
Unit 2: JDBC
Q. What is ResultSet Interface? List any two methods / fields.
ResultSet holds the result of a SELECT query. Cursor starts before first row.
Important methods:
1. next() – moves cursor to next row; returns true if row exists
2. getString(columnName) – returns column value as String
3. getInt(columnIndex) – returns column value as int
4. close() – releases ResultSet resources
Fields (constants): TYPE_FORWARD_ONLY, TYPE_SCROLL_SENSITIVE, CONCUR_READ_ONLY
Q. Differentiate between PreparedStatement and Statement.
Feature Statement PreparedStatement
Query Type Static SQL Pre-compiled SQL with parameters
Performance Slower (compiled each time) Faster (compiled once)
SQL Injection Vulnerable Safe (parameterized)
Usage Simple queries Repeated queries with parameters
Syntax createStatement() prepareStatement(sql)
Q. List JDBC drivers.
Four types of JDBC drivers:
1. Type 1 – JDBC-ODBC Bridge Driver: Uses ODBC driver; platform dependent
2. Type 2 – Native API Driver: Uses database client library; partially Java
3. Type 3 – Network Protocol Driver: Uses middleware; pure Java
4. Type 4 – Thin Driver: Direct database connection; pure Java; most widely used
Q. What is use of commit() in transactions in Java?
When autoCommit is set to false, changes are not saved until commit() is called.
Steps:
1. [Link](false);
2. Execute INSERT/UPDATE/DELETE statements
3. [Link](); – permanently save changes
4. If error: [Link](); – undo all changes
Q. What is DatabaseMetaData?
DatabaseMetaData provides information about the database as a whole.
Obtained via: DatabaseMetaData dbmd = [Link]();
Key methods: getDatabaseProductName(), getDriverName(), getTables(), getUserName()
Unit 3: Multithreading
Q. State any two methods of inter-thread communication.
1. wait() – The current thread releases the lock and enters WAITING state. It waits until notified.
2. notify() – Wakes up one thread that is waiting on the same object's lock.
3. notifyAll() – Wakes up all threads waiting on the same object's lock.
Note: These methods must be called from a synchronized block/method.
Q. Differentiate between Thread class and Runnable interface.
Feature Thread Class Runnable Interface
Type Class (extend) Interface (implement)
Inheritance Cannot extend another class Can extend another class
Method Override run() Implement run()
Object sharing Each thread is an object Same Runnable can be shared
Preferred Simple cases Preferred approach
Q. What are thread priorities?
Java thread priority is an integer from 1 to 10:
• Thread.MIN_PRIORITY = 1
• Thread.NORM_PRIORITY = 5 (default for all threads)
• Thread.MAX_PRIORITY = 10
Set priority: [Link](Thread.MAX_PRIORITY);
Get priority: int p = [Link]();
Q. Differentiate between sleep() and interrupt().
Feature sleep() interrupt()
Purpose Pauses thread for specified time Interrupts a sleeping/waiting thread
Throws InterruptedException Sets interrupt flag
Syntax [Link](ms) [Link]()
Effect Thread goes to timed waiting state Wakes interrupted thread
Unit 4: Servlets
Q. What are the advantages of servlet over CGI?
1. Performance: Servlets use threads; CGI creates a new process per request (slower)
2. Platform Independent: Servlets are pure Java; CGI may depend on OS
3. Persistent: Servlets stay in memory between requests; CGI restarts
4. Session Management: Servlets have built-in session/cookie support
5. Security: Servlets benefit from Java security model
Q. State any two methods for session tracking.
1. Cookies – Small text files stored on client browser; sent with each request
2. HttpSession – Server-side session object; stores user data on server
3. URL Rewriting – Session ID appended to every URL
4. Hidden Form Fields – Session data stored in hidden HTML inputs
Q. List the parameters of doPost() in servlet.
doPost() has two parameters:
1. HttpServletRequest request – Contains all client request data (form data, headers, parameters)
2. HttpServletResponse response – Used to build and send the HTTP response to the client
Syntax: protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException { }
Q. Write a syntax of getCookies() method in servlet.
To retrieve all cookies from a request:
Cookie[] cookies = [Link]();
if(cookies != null) {
for(Cookie c : cookies) {
[Link]([Link]() + " = " + [Link]());
}
}
Unit 5: JSP
Q. List any two implicit objects in JSP.
JSP provides 9 implicit objects (created automatically):
1. request – HttpServletRequest; access form data: [Link]("name")
2. response – HttpServletResponse; send response
3. out – JspWriter; print to browser: [Link]("Hello");
4. session – HttpSession; manage sessions
5. application – ServletContext; application-wide data
Q. What are advantages of JSP over servlet?
1. Easy to code: HTML and Java mixed; no need to write println() for HTML
2. Auto compilation: JSP is automatically compiled on first request
3. Separation of concern: Designers handle HTML; developers handle Java
4. Tag libraries: JSTL tags simplify development
5. Implicit objects: No need to create request/response objects manually
Q. Give the name of directives in JSP. / Write a general syntax of include directive.
Three JSP directives:
1. Page directive: <%@ page language="java" contentType="text/html" %>
2. Include directive: <%@ include file="[Link]" %>
3. Taglib directive: <%@ taglib uri="..." prefix="c" %>
Q. Write purpose of setContentType().
setContentType() is a method of HttpServletResponse. It sets the MIME type of the response being
sent to the client.
Example: [Link]("text/html"); – tells browser to render as HTML
Other values: "application/json", "text/plain", "application/pdf"
Unit 6: Spring Framework
Q. What are the applications of Spring?
1. Web Development: Spring MVC for building web applications
2. RESTful APIs: Spring Boot for creating REST services quickly
3. Database Access: Spring JDBC / Spring Data for DB operations
4. Security: Spring Security for login, authentication, authorization
5. Microservices: Spring Cloud for building microservice-based systems
6. Batch Processing: Spring Batch for large-scale data processing
Q. Write any two methods of HTTP_session.
Key HttpSession methods:
1. setAttribute(String name, Object value) – stores data in session
2. getAttribute(String name) – retrieves data from session
3. getId() – returns unique session ID
4. invalidate() – destroys the session
5. setMaxInactiveInterval(seconds) – sets session timeout
SECTION C — 3 Mark Questions
Unit 4: Servlets
Q. What is Spring framework? Explain its advantages.
Spring Framework is a lightweight, open-source Java framework for enterprise application
development. It is based on the principles of Dependency Injection (DI) and Aspect-Oriented
Programming (AOP).
Advantages of Spring:
1. Lightweight: Spring is a POJO-based framework; no heavy container needed
2. Dependency Injection: Reduces coupling between components; easy to test
3. Modular: Use only needed modules (Core, MVC, JDBC, AOP, etc.)
4. Spring MVC: Robust Model-View-Controller web framework
5. Transaction Support: Declarative transaction management
6. Integration: Easily integrates with Hibernate, JPA, JSF, Struts
Q. Explain execution process of servlet application.
Steps in Servlet Execution:
1. Client Request: User sends HTTP request from browser
2. Web Server: Web container (e.g., Tomcat) receives the request
3. Load Servlet: Container checks if servlet is loaded; if not, loads and instantiates it
4. init(): Called once; servlet is initialized
5. service(): Handles each request; calls doGet() or doPost()
6. doGet()/doPost(): Business logic executed; response written
7. Response: HTML/data sent back to client browser
8. destroy(): Called when servlet is removed from service
Q. Explain any three applications of Spring.
1. Web Application Development: Spring MVC provides a complete MVC architecture for building web
applications. Controllers handle HTTP requests, views display data, and models represent business
data.
2. RESTful Web Services: Spring Boot makes it very easy to build REST APIs. Annotations like
@RestController, @GetMapping, @PostMapping simplify REST development.
3. Database Integration: Spring JDBC and Spring Data JPA simplify database operations, handling
connections, transactions, and CRUD operations with minimal code.
4. Security: Spring Security provides authentication, authorization, CSRF protection for web apps and
APIs.
Q. Differentiate between JSP and Servlet.
Feature JSP Servlet
Extension .jsp files .java files
Coding HTML with embedded Java Pure Java class
Compilation Auto-compiled on 1st request Compiled manually
MVC Role View (presentation) Controller (logic)
Readability Easy for designers Hard for non-Java developers
Performance Slightly slower (first request) Faster (pre-compiled)
Q. Explain JDBC architecture.
JDBC Architecture has two layers:
1. JDBC API Layer: Java application interacts with JDBC API ([Link] package). It provides interfaces
like Connection, Statement, ResultSet.
2. JDBC Driver Layer: JDBC Driver Manager manages different JDBC drivers. Drivers communicate
with actual database.
Components:
• DriverManager: Loads drivers; creates Connection objects
• Connection: Represents DB connection
• Statement/PreparedStatement: Executes SQL queries
• ResultSet: Holds query results
Flow: Java App → JDBC API → DriverManager → JDBC Driver → Database
Q. Explain the architecture of Spring.
Spring Architecture is layered and modular:
1. Core Container: Foundation of Spring; provides IoC and DI. Modules: spring-core, spring-beans,
spring-context
2. Data Access/Integration: JDBC, ORM (Hibernate), JMS, Transaction management
3. Web Layer: Spring MVC (Model-View-Controller) for web development
4. AOP Module: Aspect-Oriented Programming for cross-cutting concerns (logging, security)
5. Test Module: Supports unit testing with JUnit and TestNG
All modules are built on top of the Core Container.
Q. Explain the components of JSP.
JSP Components:
1. Directives (<%@ %>): Provide instructions to JSP container about page settings (page, include,
taglib)
2. Declarations (<%! %>): Declare variables and methods at class level
3. Scriptlets (<% %>): Contain Java code executed on each request
4. Expressions (<%= %>): Evaluate expressions and output results directly
5. Implicit Objects: Pre-defined objects (request, response, out, session, etc.)
6. Actions (<jsp:include>, <jsp:forward>): Standard JSP actions
7. HTML/CSS: Static content mixed with dynamic Java code
SECTION D — 4 Mark Questions (Programs & Explanations)
Unit 1: Collections — Programs
Q. Write a java program to accept N integers from user, store in collection and display only
even integers.
import [Link].*;
public class EvenNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<Integer> list = new ArrayList<>();
[Link]("Enter N: ");
int n = [Link]();
[Link]("Enter " + n + " integers:");
for(int i = 0; i < n; i++)
[Link]([Link]());
[Link]("Even Numbers:");
for(int x : list)
if(x % 2 == 0)
[Link](x);
}
}
Q. Write a Java Program to accept n characters from user, store them into LinkedList, remove
duplicate characters and display in sorted order.
import [Link].*;
public class UniqueChars {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
LinkedList<Character> list = new LinkedList<>();
[Link]("Enter n: ");
int n = [Link]();
[Link]("Enter " + n + " characters:");
for(int i = 0; i < n; i++)
[Link]([Link]().charAt(0));
// Remove duplicates using TreeSet (also sorts)
TreeSet<Character> set = new TreeSet<>(list);
[Link]("Unique sorted chars: " + set);
}
}
Q. Write a java program to accept 'N' student names, store them in LinkedList and display in
reverse order.
import [Link].*;
public class ReverseNames {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
LinkedList<String> list = new LinkedList<>();
[Link]("Enter N: ");
int n = [Link]();
for(int i = 0; i < n; i++) {
[Link]("Enter name: ");
[Link]([Link]());
}
[Link](list);
[Link]("Reverse order: " + list);
}
}
Q. Write a java program to accept 'n' Employee names through command line, store them into
ArrayList and display them (use iterator interface).
import [Link].*;
public class EmpNames {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
// args[] contains command line arguments
for(String name : args)
[Link](name);
[Link]("Employee Names:");
Iterator<String> it = [Link]();
while([Link]())
[Link]([Link]());
}
}
// Run: java EmpNames Alice Bob Charlie
Q. Write a java program to accept 'n' numbers from user, store them in LinkedList, display
only negative integers.
import [Link].*;
public class NegativeNums {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
LinkedList<Integer> list = new LinkedList<>();
[Link]("Enter n: ");
int n = [Link]();
for(int i = 0; i < n; i++)
[Link]([Link]());
[Link]("Negative Numbers:");
for(int x : list)
if(x < 0) [Link](x);
}
}
Q. Write a java program to accept 'n' names, store in ArrayList, sort in ascending order and
display it.
import [Link].*;
public class SortNames {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<String> list = new ArrayList<>();
[Link]("Enter n: ");
int n = [Link]();
for(int i = 0; i < n; i++) {
[Link]("Name: ");
[Link]([Link]());
}
[Link](list);
[Link]("Sorted: " + list);
}
}
Unit 2: JDBC — Programs
Q. Write a Java program to accept details of employee (eno, ename, salary), store into
database and display it.
import [Link].*;
import [Link];
public class EmpDB {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "1234");
// INSERT
[Link]("Eno: "); int eno = [Link]();
[Link]("Ename: "); String ename = [Link]();
[Link]("Salary: "); double sal = [Link]();
PreparedStatement ps = [Link](
"INSERT INTO emp VALUES(?,?,?)");
[Link](1, eno);
[Link](2, ename);
[Link](3, sal);
[Link]();
[Link]("Record inserted!");
// DISPLAY
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM emp");
[Link]("Eno\tEname\tSalary");
while([Link]())
[Link]([Link](1)+"\t"+[Link](2)+"\t"+[Link](3));
[Link]();
}
}
Q. Write a Java program to update the salary of a given employee (use PreparedStatement
interface). Assume Emp table (Eno, Ename, Esal) is already created.
import [Link].*;
import [Link];
public class UpdateSalary {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "1234");
[Link]("Enter Employee No to update: ");
int eno = [Link]();
[Link]("Enter new Salary: ");
double newSal = [Link]();
PreparedStatement ps = [Link](
"UPDATE emp SET Esal=? WHERE Eno=?");
[Link](1, newSal);
[Link](2, eno);
int rows = [Link]();
if(rows > 0) [Link]("Salary updated successfully!");
else [Link]("Employee not found!");
[Link]();
}
}
Q. Write a java program to accept details of student (Rno, Name, Percentage) and store into
database using PreparedStatement interface.
import [Link].*;
import [Link];
public class StudentDB {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "1234");
[Link]("Roll No: "); int rno = [Link]();
[Link]("Name: "); String name = [Link]();
[Link]("Percentage: "); double per = [Link]();
PreparedStatement ps = [Link](
"INSERT INTO student(rno,name,percentage) VALUES(?,?,?)");
[Link](1, rno);
[Link](2, name);
[Link](3, per);
[Link]();
[Link]("Student record stored successfully!");
[Link]();
}
}
Q. Write a java program to delete the details of given teacher and display remaining records
from Teacher Table. Assume teacher table (tid, tname, subject) already created.
import [Link].*;
import [Link];
public class DeleteTeacher {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "1234");
[Link]("Enter Teacher ID to delete: ");
int tid = [Link]();
PreparedStatement ps = [Link](
"DELETE FROM teacher WHERE tid=?");
[Link](1, tid);
int r = [Link]();
[Link](r > 0 ? "Deleted!" : "Not found.");
// Display remaining
ResultSet rs = [Link]().executeQuery(
"SELECT * FROM teacher");
[Link]("Remaining Teachers:");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}
}
Unit 3: Multithreading — Programs & Concepts
Q. Write a java program to display even numbers between 1 to 100. Each number should
display after 5 seconds. [use sleep()]
public class EvenWithSleep {
public static void main(String[] args) throws InterruptedException {
for(int i = 1; i <= 100; i++) {
if(i % 2 == 0) {
[Link](i);
[Link](5000); // 5 seconds
}
}
}
}
Q. Write a java program in multithreading to display all the alphabets between 'A' to 'Z'. Each
alphabet should display after two seconds.
public class AlphabetThread extends Thread {
public void run() {
for(char c = 'A'; c <= 'Z'; c++) {
[Link](c);
try { [Link](2000); }
catch(InterruptedException e) { [Link](); }
}
}
public static void main(String[] args) {
new AlphabetThread().start();
}
}
Q. Write a program using Multi Threading to blink a text on frame.
import [Link].*;
public class BlinkText extends Frame implements Runnable {
boolean visible = true;
BlinkText() {
setSize(300, 200); setVisible(true);
new Thread(this).start();
}
public void paint(Graphics g) {
if(visible) { [Link](new Font("Arial",[Link],30));
[Link]("Blinking!", 80, 100); }
}
public void run() {
try {
while(true) {
visible = !visible;
repaint();
[Link](500);
}
} catch(InterruptedException e) {}
}
public static void main(String[] a) { new BlinkText(); }
}
Q. Explain Synchronization with an example.
Synchronization is a mechanism that prevents multiple threads from accessing a shared resource
simultaneously, avoiding data inconsistency.
Without synchronization, two threads might read-modify-write the same variable at the same time
causing race conditions.
Keyword: synchronized – only one thread can execute the synchronized block/method at a time.
class Counter {
int count = 0;
synchronized void increment() { // synchronized method
count++;
}
}
class MyThread extends Thread {
Counter c;
MyThread(Counter c) { this.c = c; }
public void run() {
for(int i = 0; i < 1000; i++) [Link]();
}
}
public class SyncDemo {
public static void main(String[] args) throws Exception {
Counter c = new Counter();
MyThread t1 = new MyThread(c);
MyThread t2 = new MyThread(c);
[Link](); [Link]();
[Link](); [Link]();
[Link]("Count: " + [Link]); // Always 2000
}
}
Unit 4: Servlet — Life Cycle & Programs
Q. Explain the Life Cycle of Servlet.
Servlet Life Cycle has 5 stages:
1. Loading: When first request arrives, Servlet container loads the servlet class
2. Instantiation: Container creates one instance of the servlet using default constructor
3. Initialization – init(): Called once; used to initialize resources (DB connection, config). Signature:
public void init(ServletConfig config) throws ServletException
4. Request Handling – service(): Called for every request. Dispatches to doGet() or doPost() based on
HTTP method. Signature: public void service(HttpServletRequest req, HttpServletResponse res)
5. Destruction – destroy(): Called once before servlet is removed. Used to release resources.
Signature: public void destroy()
Q. Write a Servlet program to count the number of times a servlet has been invoked [use
cookies].
import [Link].*;
import [Link].*;
import [Link].*;
public class CountServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
int count = 0;
Cookie[] cookies = [Link]();
if(cookies != null) {
for(Cookie c : cookies)
if([Link]().equals("visitCount"))
count = [Link]([Link]());
}
count++;
Cookie c = new Cookie("visitCount", [Link](count));
[Link](60*60*24); // 1 day
[Link](c);
[Link]("<h2>You have visited this page " + count + " times.</h2>");
}
}
Unit 5: JSP — Life Cycle & Programs
Q. Explain Life Cycle of JSP.
JSP Life Cycle stages:
1. Translation: JSP file (.jsp) is converted into a Servlet Java file by the JSP container
2. Compilation: The generated Java file is compiled into a .class file
3. Loading: The compiled class is loaded into memory
4. Instantiation: An instance of the Servlet is created
5. Initialization – jspInit(): Called once; initializes the JSP
6. Request Processing – _jspService(): Called for every request; contains the JSP page logic
7. Destruction – jspDestroy(): Called when JSP is removed; cleanup operations
Q. Write a JSP program to accept user name and greet the user according to time of system.
<!-- [Link] -->
<form action='[Link]' method='post'>
Name: <input type='text' name='uname'>
<input type='submit' value='Submit'>
</form>
<!-- [Link] -->
<%@ page import='[Link]' %>
<%
String name = [Link]("uname");
Calendar cal = [Link]();
int hour = [Link](Calendar.HOUR_OF_DAY);
String greeting;
if(hour < 12) greeting = "Good Morning";
else if(hour < 17) greeting = "Good Afternoon";
else greeting = "Good Evening";
%>
<h2><%= greeting %>, <%= name %>!</h2>
Q. Write a JSP program to accept a number from user and convert it into words (e.g. 123 →
One Two Three).
<!-- [Link] -->
<form action='[Link]' method='post'>
Enter Number: <input type='text' name='num'>
<input type='submit' value='Convert'>
</form>
<!-- [Link] -->
<%
String num = [Link]("num");
String[] words = {"Zero","One","Two","Three","Four",
"Five","Six","Seven","Eight","Nine"};
[Link]("<b>" + num + " in words: </b>");
for(char ch : [Link]()) {
int d = ch - '0';
[Link](words[d] + " ");
}
%>
Q. Write a JSP program to accept student name, address and class and display it on next page
in tabular format.
<!-- [Link] -->
<form action='[Link]' method='post'>
Name: <input type='text' name='sname'><br/>
Address: <input type='text' name='addr'><br/>
Class: <input type='text' name='cls'><br/>
<input type='submit' value='Submit'>
</form>
<!-- [Link] -->
<%
String name = [Link]("sname");
String addr = [Link]("addr");
String cls = [Link]("cls");
%>
<table border='1'>
<tr><th>Field</th><th>Value</th></tr>
<tr><td>Name</td><td><%= name %></td></tr>
<tr><td>Address</td><td><%= addr %></td></tr>
<tr><td>Class</td><td><%= cls %></td></tr>
</table>
Q. Write a JSP script to check whether given number is perfect or not and display result in
yellow colour.
<!-- [Link] -->
<form action='[Link]' method='post'>
Enter Number: <input type='text' name='n'>
<input type='submit' value='Check'>
</form>
<!-- [Link] -->
<%
int n = [Link]([Link]("n"));
int sum = 0;
for(int i = 1; i < n; i++)
if(n % i == 0) sum += i;
String result = (sum == n) ? n + " is a Perfect Number!"
: n + " is NOT a Perfect Number.";
%>
<p style='color:black; background-color:yellow; font-size:18px;'>
<%= result %>
</p>
Q. Write a JSP program to display all the perfect numbers between 1 to n in blue color.
<!-- [Link] -->
<form action='[Link]' method='post'>
Enter N: <input type='text' name='n'>
<input type='submit' value='Find'>
</form>
<!-- [Link] -->
<%
int n = [Link]([Link]("n"));
%>
<h3 style='color:blue;'>Perfect Numbers from 1 to <%= n %>:</h3>
<%
for(int num = 1; num <= n; num++) {
int sum = 0;
for(int i = 1; i < num; i++)
if(num % i == 0) sum += i;
if(sum == num)
[Link]("<p style='color:blue;'>" + num + "</p>");
}
%>
Q. Write a JSP program to accept username and password; display Login Successful or Login
Failed.
<!-- [Link] -->
<form action='[Link]' method='post'>
Username: <input type='text' name='user'><br/>
Password: <input type='password' name='pass'><br/>
<input type='submit' value='Login'>
</form>
<!-- [Link] -->
<%
String user = [Link]("user");
String pass = [Link]("pass");
if([Link](pass)) {
%>
<h2 style='color:green;'>Login Successful!</h2>
<% } else { %>
<h2 style='color:red;'>Login Failed!</h2>
<% } %>
Q. Write a JSP program to display all prime numbers between 1 to n in Red colour.
<!-- [Link] -->
<form action='[Link]' method='post'>
Enter N: <input type='text' name='n'>
<input type='submit' value='Find Primes'>
</form>
<!-- [Link] -->
<%
int n = [Link]([Link]("n"));
%>
<h3>Primes from 1 to <%= n %>:</h3>
<%
for(int num = 2; num <= n; num++) {
boolean prime = true;
for(int i = 2; i <= [Link](num); i++)
if(num % i == 0) { prime = false; break; }
if(prime)
[Link]("<span style='color:red;'>" + num + " </span>");
}
%>
Q. Write a JSP script to check the given number is prime or not. Display the result in blue
color.
<!-- [Link] -->
<%
int n = [Link]([Link]("n"));
boolean prime = true;
if(n < 2) prime = false;
for(int i = 2; i <= [Link](n); i++)
if(n % i == 0) { prime = false; break; }
String msg = prime ? n+" is PRIME" : n+" is NOT PRIME";
%>
<p style='color:blue; font-size:20px;'><b><%= msg %></b></p>
Q. Write a Servlet program to get information about the server such as name, port number and
version of server.
import [Link].*;
import [Link].*;
import [Link].*;
public class ServerInfo extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
ServletContext sc = getServletContext();
[Link]("<h2>Server Information</h2>");
[Link]("Server Name: " + [Link]() + "<br/>");
[Link]("Server Port: " + [Link]() + "<br/>");
[Link]("Servlet Info: " + [Link]() + "<br/>");
[Link]("Context Path: " + [Link]() + "<br/>");
}
}
Q. Explain JDBC process with an example.
JDBC Process (6 Steps):
1. Import packages: import [Link].*;
2. Register Driver: [Link]("[Link]");
3. Create Connection: Connection con = [Link](url, user, pass);
4. Create Statement: Statement st = [Link]();
5. Execute Query: ResultSet rs = [Link]("SELECT * FROM emp");
6. Process Results & Close: while([Link]()) { ... } [Link]();
import [Link].*;
public class JDBCExample {
public static void main(String[] a) throws Exception {
[Link]("[Link]"); // Step 2
Connection con = [Link]( // Step 3
"jdbc:mysql://localhost/testdb", "root", "1234");
Statement st = [Link](); // Step 4
ResultSet rs = [Link]("SELECT * FROM emp"); // Step 5
while([Link]()) // Step 6
[Link]([Link](1)+" "+[Link](2));
[Link]();
}
}
Q. Explain the life cycle of thread.
Thread Life Cycle has 5 states:
1. New: Thread object is created but start() not called yet. Thread t = new Thread();
2. Runnable: start() is called; thread is ready to run but scheduler hasn't given it CPU yet
3. Running: Thread scheduler picks the thread; run() method executes
4. Blocked/Waiting: Thread is waiting for I/O, sleep(), wait(), or another thread to finish (join())
5. Terminated/Dead: run() method has finished execution; thread cannot be restarted
Transitions: New → Runnable → Running → Blocked/Waiting → Running → Dead
Q. What is session tracking? How to implement it.
Session Tracking is the ability to maintain state about a client across multiple requests. HTTP is
stateless, so session tracking is needed to remember users.
Methods of Session Tracking:
1. Cookies: Small data stored on client browser
2. HttpSession: Server-side session management
3. URL Rewriting: Session ID in URL
4. Hidden Form Fields: Data in hidden input tags
Implementation using HttpSession:
// Store data in session
HttpSession session = [Link]();
[Link]("username", "Alice");
// Retrieve data from session (on next page)
HttpSession session = [Link](false);
String user = (String) [Link]("username");
// Destroy session
[Link]();
Q. Write a java program to display odd numbers between 1 to 100. Each number should
display after 5 seconds. (Use sleep())
public class OddWithSleep {
public static void main(String[] args) throws InterruptedException {
for(int i = 1; i <= 100; i++) {
if(i % 2 != 0) {
[Link](i);
[Link](5000); // 5 seconds
}
}
}
}
Quick Reference — Topic-wise Important Questions
Topic Most Repeated Questions (High Priority)
Collections Define List/Set/Map, ArrayList vs LinkedList, Iterator vs ListIterator, Programs with LinkedList/ArrayList
JDBC JDBC Architecture, Steps of JDBC, PreparedStatement vs Statement, Programs: Insert/Update/Delete
Multithreading Life Cycle of Thread, Synchronization with example, sleep()/join()/yield(), Inter-thread Communication
Servlets Life Cycle of Servlet, doGet/doPost syntax, Session Tracking, Cookies, Servlet vs CGI
JSP Life Cycle of JSP, JSP Components, Implicit Objects, Programs: Greet/Number/Prime/Perfect
Spring Spring Framework definition, Modules, Architecture, Applications
All the best for your examination!