Java II CS365 QnA
Java II CS365 QnA
1. Collections Collection Framework, List, Set, Map, Iterator, ArrayList, LinkedList, HashSet, TreeSet, HashTable
4. Servlets & JSP Servlet lifecycle, Session Tracking, Cookies, HttpSession, JSP lifecycle, Implicit Objects, Directive
Map interface ([Link]) represents a collection of key-value pairs where each key maps to exactly one
value. Keys are unique; values can be repeated. Common implementations: HashMap, TreeMap,
LinkedHashMap.
wait() causes the calling thread to release the lock and enter a waiting state until another thread calls notify() or
notifyAll() on the same object. It is used for inter-thread communication. Syntax: public final void wait(long
timeout)
getConnection() is a method of DriverManager class used to establish a connection to the database. Syntax:
Connection con = [Link](url, username, password);
A scriptlet is a fragment of Java code embedded inside a JSP page using the tags <% ... %>. Any valid Java
statements (loops, conditions, variable declarations) can be written inside scriptlets.
JSP directives provide special instructions to the JSP container about how to handle aspects of JSP processing.
Syntax: <%@ directive attribute='value' %>. Types: page, include, taglib.
Spring Framework is an open-source, lightweight Java application framework that provides Inversion of Control
(IoC) and Dependency Injection (DI). It simplifies enterprise Java development with modular architecture.
JDBC API interfaces and classes include: DriverManager, Connection, Statement, PreparedStatement,
CallableStatement, ResultSet, ResultSetMetaData, DatabaseMetaData.
Iterator is an interface in [Link] package that allows sequential access to elements of a collection. Key
methods: hasNext() — returns true if more elements exist; next() — returns the next element; remove() —
removes the current element.
ArrayList is a resizable array implementation of the List interface ([Link]). It maintains insertion order,
allows duplicates, and permits null values. It is non-synchronized and provides O(1) random access.
A cookie is a small piece of information (key-value pair) passed between server and client in HTTP headers. It is
used for session tracking. In Servlet: Cookie c = new Cookie('name','value'); [Link](c);
Q2) Attempt any FOUR of the following [4 × 2 = 8]
// Method 1
class MyThread extends Thread {
public void run() { [Link]("Thread running"); }
}
MyThread t = new MyThread();
[Link]();
// Method 2
class MyRun implements Runnable {
public void run() { [Link]("Thread running"); }
}
Thread t = new Thread(new MyRun());
[Link]();
• setAttribute(String name, Object value): Binds an object to the session using the given name.
• getAttribute(String name): Returns the object bound with the given name in the session, or null.
• invalidate(): Destroys the session and removes all bound attributes.
• getId(): Returns the unique session identifier string assigned to the session.
Qa. Write a JDBC program to accept details of Book (B_id, B_name, B_cost) from
[4 Marks]
user and display it.
import [Link].*;
import [Link];
[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:library", "postgres", "");
// Insert
PreparedStatement pst = [Link](
"INSERT INTO Book VALUES(?,?,?)");
[Link](1, bid);
[Link](2, bname);
[Link](3, bcost);
[Link]();
[Link]("Record inserted.");
// Display
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM Book");
[Link]("B_id\tB_name\tB_cost");
while([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3));
}
[Link]();
}
}
Qb. Write a Java program in multithreading to display all alphabets from 'A' to 'Z'.
[4 Marks]
Each alphabet should display after two seconds.
class AlphabetThread extends Thread {
public void run() {
for(char c = 'A'; c <= 'Z'; c++) {
[Link](c);
try {
[Link](2000); // 2 seconds delay
} catch(InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
}
Qc. Write a JSP script to check whether a given number is perfect or not and
[4 Marks]
display the result in yellow colour.
[Link]:
<html>
<body>
<form method="post" action="[Link]">
Enter Number: <input type="text" name="num">
<input type="submit" value="Check">
</form>
<%
String s = [Link]("num");
if(s != null && ![Link]()) {
int n = [Link](s);
int sum = 0;
for(int i = 1; i < n; i++) {
if(n % i == 0) sum += i;
}
if(sum == n) {
%>
<p style="color:yellow; background:black;">
<%= n %> is a PERFECT number.
</p>
<% } else { %>
<p style="color:yellow; background:black;">
<%= n %> is NOT a perfect number.
</p>
<% } } %>
</body>
</html>
Qa. Write a Servlet program to count the number of times a servlet has been
[4 Marks]
invoked [use cookies].
import [Link].*;
import [Link].*;
import [Link].*;
A thread passes through the following 5 states during its life cycle:
• New: Thread object created but start() not yet called. Thread is born.
• Runnable: After start() is called, thread is ready to run. Thread scheduler has not yet selected it.
• Running: Thread scheduler has selected the thread. The run() method is executing.
• Non-Runnable (Blocked): Thread is alive but not eligible to run. Caused by sleep(), wait(), blocked on I/O,
or suspend().
• Terminated (Dead): run() method has completed. Thread cannot be restarted.
Transitions: New →start()→ Runnable →scheduler picks→ Running →run() ends→ Terminated. Running
can go to Blocked via sleep/wait and back to Runnable when condition clears.
Statement PreparedStatement
SQL query is compiled each time it executes SQL query is precompiled once
Cannot use parameters; static queries only Uses '?' placeholders for parameters
Less efficient for repeated queries More efficient for repeated execution
Suitable for DDL statements (CREATE, DROP) Suitable for DML with varying values (INSERT, UPDATE)
Qb. Write a Java program to accept 'n' numbers, store in LinkedList, display only
[3 Marks]
odd numbers.
import [Link].*;
A Collection is an object (container) that groups multiple elements into a single unit. It is used to store, retrieve,
manipulate and communicate aggregate data. Defined in [Link] package.
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. Higher priority thread gets CPU first. Set using
setPriority(int).
JDBC (Java Database Connectivity) is a Java API that provides standard interfaces to connect Java
applications with relational databases. It enables executing SQL queries, updates, and stored procedures from
Java code.
A session is a server-side mechanism to maintain state between multiple HTTP requests from the same user.
Since HTTP is stateless, HttpSession is used to store user-specific data across requests. Created via
[Link]().
The request object (HttpServletRequest) provides information about the client's HTTP request. Methods:
getParameter(name) — gets form data; getServerName() — server name; getServerPort() — port number;
getProtocol() — protocol.
Spring MVC is used to develop web applications by separating concerns into Model, View, and Controller
layers. It handles HTTP requests via DispatcherServlet and supports form handling, validation, and view
resolution.
join() method causes the current thread to wait until the thread on which join() is called terminates. Syntax:
[Link](). Used to ensure one thread completes before another starts. Belongs to Thread class.
HashTable is a legacy class in [Link] that implements a hash table mapping keys to values. It is synchronized
(thread-safe), does not allow null keys or null values. Similar to HashMap but synchronized.
commit() method in JDBC is used to save all changes made in the current transaction permanently to the
database. Syntax: [Link](). It is called after auto-commit is disabled using [Link](false).
Qa. Write any two differences between ArrayList and LinkedList. [2 Marks]
ArrayList LinkedList
Less memory (stores data only) More memory (stores data + two pointers)
sleep() interrupt()
Pauses thread for specified milliseconds Sends interrupt signal to a sleeping/waiting thread
getCookies() is a method of HttpServletRequest that returns all cookies sent by the client as an array.
// Syntax:
Cookie[] getCookies()
// Usage:
Cookie[] cookies = [Link]();
if(cookies != null) {
for(Cookie c : cookies) {
String name = [Link]();
String value = [Link]();
}
}
import [Link].*;
import [Link];
[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:college","postgres","");
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM Student");
[Link]("RN\tName\tPercentage");
while([Link]())
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3));
[Link]();
}
}
Qc. Write a JSP script to check whether the given number is prime or not. Display
[4 Marks]
result in blue colour.
Qa. Write a Servlet program to get information about the server such as name,
[4 Marks]
port number and version.
import [Link].*;
import [Link].*;
import [Link].*;
A JSP lifecycle has 4 phases (similar to Servlet but with an extra compilation step):
• 1. Compilation Phase: When browser requests a JSP, the JSP engine checks if the page needs
compilation. It parses the JSP → translates to Servlet (.java) → compiles to bytecode (.class).
• 2. Initialization Phase: Container calls jspInit() method once (similar to Servlet's init()). Used for one-time
setup like DB connections or file opening.
• 3. Execution Phase: For every request, _jspService(HttpServletRequest, HttpServletResponse) is called. It
generates the dynamic HTML response. This method runs for every request.
• 4. Cleanup / Destruction Phase: jspDestroy() is called before JSP is removed from service. Used for
resource cleanup (closing connections, releasing handles).
When two or more threads access a shared resource simultaneously, it may cause data inconsistency.
Synchronization ensures only one thread accesses the critical section at a time using a monitor/lock.
Syntax: synchronized void methodName() { ... } or synchronized(object) { ... }
class MyThread extends Thread {
String msg[] = {"Java","Supports","Multithreading"};
MyThread(String name) { super(name); }
class SyncDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread("T1: ");
MyThread t2 = new MyThread("T2: ");
[Link](); [Link]();
}
}
// Without sync: output interleaved. With sync: T1 completes, then T2.
• Step 1 – Client Request: Browser sends HTTP request to the Web Server for a servlet URL.
• Step 2 – Web Server forwards: Server detects it is a servlet request (from [Link] mapping) and forwards
to Servlet Container.
• Step 3 – Class Loading: If servlet is not loaded, container loads the servlet class into memory.
• Step 4 – Instantiation: Container creates one instance of the Servlet class.
• Step 5 – Initialization: init() method is called once to initialize the servlet.
• Step 6 – Request handling: For each request, a new thread is spawned; service() → doGet()/doPost() is
called.
• Step 7 – Response: Servlet generates dynamic HTML response sent back to client via HTTP.
• Step 8 – Destroy: When container shuts down, destroy() is called to clean up resources.
Qb. Write a Java program to accept 'n' names, store in ArrayList, sort in
[3 Marks]
ascending order and display.
import [Link].*;
CallableStatement is used to call stored procedures from a Java application. It extends PreparedStatement.
Parameters: IN (input), OUT (output), INOUT (both). Created using [Link]('{call procName(?)}').
A thread is the smallest unit of execution within a process. It is a lightweight sub-process that runs
independently. Java supports multithreading — multiple threads executing concurrently within one program,
sharing memory.
Servlet creates one instance; CGI creates a new process per request. Servlets are persistent (stay in memory);
CGI processes terminate after each request. Servlets are faster, platform-independent, and support session
management.
Set is an interface in [Link] that represents a collection of unique elements (no duplicates). Order depends on
implementation: HashSet (no order), TreeSet (sorted), LinkedHashSet (insertion order). Implements Collection
interface.
In a JSP Scriptlet, request parameters can be accessed using: 1. [Link]('name') — gets single
value. 2. [Link]('name') — gets array of values. Example: String uname =
[Link]('username');
Spring is an open-source, lightweight Java framework based on IoC (Inversion of Control) and DI (Dependency
Injection) principles. It simplifies Java enterprise development with modular architecture covering web, data,
security, and more.
TreeSet implements the SortedSet interface (which extends Set). It also implements NavigableSet, Cloneable,
and Serializable. TreeSet stores elements in natural sorted order (ascending) using a Red-Black tree internally.
yield() is a static method of Thread class that causes the currently running thread to pause and give other
threads of same priority a chance to execute. Syntax: [Link](). It is a hint to the thread scheduler.
Map interface represents key-value pairs. Each key is unique. Common implementations: HashMap, TreeMap,
LinkedHashMap, HashTable. Implements using HashMap:
import [Link].*;
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "Apple");
[Link](2, "Banana");
[Link]([Link](1)); // Apple
for([Link]<Integer,String> e : [Link]())
[Link]([Link]()+" : "+[Link]());
DatabaseMetaData provides information about the database structure — table names, column types,
primary/foreign keys, JDBC version, etc. Created using: DatabaseMetaData dmd = [Link]();
• getTables() — retrieves table information.
• getColumns() — retrieves column details.
• getPrimaryKeys() — returns primary key info.
• getDatabaseProductName() — returns DB product name.
• <%@ page ... %> (Page Directive): Defines page-level attributes like language, contentType, import,
errorPage, session, isThreadSafe.
• <%@ include ... %> (Include Directive): Includes a file (HTML/JSP) at translation time (static inclusion).
• <%@ taglib ... %> (Taglib Directive): Declares a custom tag library used in the page.
Syntax: <%@ directive attribute='value' %>
Thread priority determines the order in which threads are scheduled. Range: 1 (MIN) to 10 (MAX).
• Thread.MIN_PRIORITY = 1 — Lowest priority.
• Thread.NORM_PRIORITY = 5 — Default priority for every thread.
• Thread.MAX_PRIORITY = 10 — Highest priority.
Set using: [Link](Thread.MAX_PRIORITY); Get using: [Link]();
Qa. Write a Java program to accept 'N' student names, store in LinkedList and
[4 Marks]
display in reverse order.
import [Link].*;
Qb. Write a Java program to accept details of Student (rollno, name, percentage).
[4 Marks]
Store into database and display.
(See Paper 2, Q3-a for complete JDBC program — same logic with Student table. Replace table name and
columns accordingly.)
import [Link].*;
import [Link];
[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:college","postgres","");
PreparedStatement pst = [Link](
"INSERT INTO student VALUES(?,?,?)");
[Link](1, rn); [Link](2, nm);
[Link](3, perc);
[Link]();
ResultSet rs = [Link]()
.executeQuery("SELECT * FROM student");
while([Link]())
[Link]([Link](1)+" "+
[Link](2)+" "+[Link](3));
[Link]();
}
}
Qc. Write a JSP program to accept username and password; if same display
[4 Marks]
'Login successful' else 'Login failed'.
<%
String uname = [Link]("uname");
String pwd = [Link]("pwd");
if(uname != null && pwd != null) {
if([Link](pwd)) {
%>
<h3 style="color:green;">Login Successful!</h3>
<% } else { %>
<h3 style="color:red;">Login Failed!</h3>
<% } } %>
</body></html>
Q4) Attempt any TWO of the following [2 × 4 = 8]
(Refer to Paper 1 Q4-b for complete answer — 5 states: New, Runnable, Running, Blocked, Terminated.)
• New: Thread object created; start() not called yet.
• Runnable: start() called; ready to run, waiting for CPU.
• Running: CPU is assigned; run() is executing.
• Non-Runnable/Blocked: Thread paused due to sleep(), wait(), I/O block, or suspend().
• Terminated: run() method completed; thread is dead.
Session Tracking is the mechanism to maintain state (user data) across multiple HTTP requests from the
same user. HTTP is stateless, so session tracking bridges this gap.
Techniques:
• Cookies: Store small data on client browser. Created: new Cookie('name','val'); [Link](c);
• Hidden Form Fields: Pass data via hidden input fields in HTML forms.
• URL Rewriting: Append session ID to URLs: [Link]('[Link]')
• HttpSession: Server-side session object. HttpSession s = [Link](); [Link]('key', value);
[Link]('key');
HttpSession implementation example:
Qc. Write a Java program to delete details of a given teacher and display
[4 Marks]
remaining records from Teacher Table (tid, tname, subject).
import [Link].*;
import [Link];
[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:school","postgres","");
ResultSet rs = [Link]()
.executeQuery("SELECT * FROM Teacher");
[Link]("tid\ttname\tsubject");
while([Link]())
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3));
[Link]();
}
}
• Directives (<%@ %>): Instructions to JSP container. Types: page, include, taglib.
• Declarations (<%! %>): Declare variables and methods at class level. Example: <%! int count=0; %>
• Scriptlets (<% %>): Java code fragments executed when page is requested.
• Expressions (<%= %>): Evaluates and displays a Java expression directly in output. Example: <%= new
[Link]() %>
• Implicit Objects: Pre-defined objects like request, response, out, session, application, config, pageContext,
page, exception.
• JSP Actions (jsp:xxx): XML-based tags to control servlet engine. Example: jsp:include, jsp:forward,
jsp:useBean.
• Comments (<%-- --%>): JSP comments not sent to client.
PAPER 4 8×1=8 | 4×2=8 | 2×4=8 | 2×4=8 | 1×3=3
A Collection is an object (container) that holds a group of elements (objects) in a single unit. Java Collections
Framework ([Link]) provides interfaces and classes like List, Set, Map to store and manipulate groups of
objects.
Interthread communication allows synchronized threads to communicate using wait(), notify(), and notifyAll()
methods of Object class. wait() pauses thread; notify() wakes one waiting thread; notifyAll() wakes all waiting
threads.
A Servlet is a server-side Java program that handles HTTP requests and generates dynamic responses. It runs
inside a Web/Servlet container (e.g., Tomcat). It extends HttpServlet and overrides doGet() or doPost().
Expressions in JSP are written using <%= expression %>. The expression is evaluated and its result is directly
written to the output stream. Example: <%= new [Link]() %> displays current date. No semicolon inside.
Spring modules: Core Container (Core, Beans, Context, SpEL), Data Access (JDBC, ORM, JMS, OXM,
Transaction), Web Layer (Web, Servlet/MVC, WebSocket, Portlet), AOP, Aspects, Instrumentation, Messaging,
Test.
HashSet implements the Set interface ([Link]). It also implements Cloneable and Serializable. HashSet
uses a HashMap internally for storage. It does not allow duplicate elements and has no guaranteed order.
getConnection() is a static method of DriverManager class that establishes and returns a Connection object to
the specified database. Syntax: Connection con = [Link](url, user, password);
Multithreading is the ability of a CPU to execute multiple threads (lightweight processes) of a single program
concurrently. Java natively supports multithreading. It improves CPU utilization, responsiveness, and application
performance.
A session is a server-side conversation between client and server across multiple HTTP requests. Since HTTP
is stateless, HttpSession maintains user data (like login info) across requests. Created using: HttpSession s =
[Link]();
Q2) Attempt any FOUR of the following [4 × 2 = 8]
Qb. What is ResultSet interface? List any two fields of it. [2 Marks]
ResultSet is a JDBC interface that holds the results of a SQL SELECT query. It acts as a cursor/iterator. Initially
cursor is before first row; use [Link]() to iterate rows.
• TYPE_FORWARD_ONLY: Cursor can only move forward (default). Read-only.
• TYPE_SCROLL_SENSITIVE: Bidirectional scrollable; reflects live database changes.
• CONCUR_READ_ONLY: ResultSet cannot be updated.
• CONCUR_UPDATABLE: ResultSet allows updates to the database.
• JSP separates business logic from presentation (HTML); Servlets mix Java code with HTML output.
• JSP pages are easier to write and maintain — HTML developers can work on JSP without deep Java
knowledge.
• No need to recompile JSP on changes; Servlets require recompilation.
• JSP has built-in implicit objects (request, response, session) — no need to declare them.
• JSP supports custom tags (JSTL) for cleaner code.
(Refer Paper 1 Q2-a — same question. Two ways: extend Thread class or implement Runnable interface.)
// Way 1: Extend Thread
class T1 extends Thread {
public void run() { [Link]("T1 running"); }
}
new T1().start();
Qa. Write a Java program to accept N integers, store in suitable collection and
[4 Marks]
display only even integers.
import [Link].*;
Qb. Write a Java program to accept details of Teacher (Tid, Tname, Tsubject),
[4 Marks]
store in database and display.
import [Link].*;
import [Link];
[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:school","postgres","");
ResultSet rs = [Link]()
.executeQuery("SELECT * FROM Teacher");
[Link]("Tid\tTname\tTsubject");
while([Link]())
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3));
[Link]();
}
}
Qc. Write a JSP program to accept username and greet the user according to time
[4 Marks]
of system.
<%-- [Link] --%>
<%@ page import="[Link].*" %>
<html><body>
<form method="post" action="[Link]">
Enter Name: <input type="text" name="uname">
<input type="submit" value="Greet">
</form>
<%
String uname = [Link]("uname");
if(uname != null && ![Link]()) {
Calendar cal = [Link]();
int hour = [Link](Calendar.HOUR_OF_DAY);
String greeting;
if(hour >= 5 && hour < 12)
greeting = "Good Morning";
else if(hour >= 12 && hour < 17)
greeting = "Good Afternoon";
else if(hour >= 17 && hour < 21)
greeting = "Good Evening";
else
greeting = "Good Night";
%>
<h2><%= greeting %>, <%= uname %>!</h2>
<% } %>
</body></html>
(Refer Paper 2 Q4-b for complete JSP Lifecycle explanation — 4 phases: Compilation, Initialization, Execution,
Cleanup.)
• 1. Compilation: JSP engine parses the .jsp file → translates to Servlet .java → compiles to .class. (Only on
first request or when modified.)
• 2. Initialization: jspInit() called once. Used to set up resources (DB connections, reading config).
• 3. Execution: _jspService() called for every request. Takes HttpServletRequest and HttpServletResponse.
Generates dynamic HTML output.
• 4. Cleanup/Destruction: jspDestroy() called when JSP removed from service. Release all resources.
Equivalent to Servlet's destroy().
(Refer Paper 2 Q4-c for complete Synchronization explanation with code example.)
Key points:
• Synchronization ensures only one thread accesses a critical section at a time.
• Uses the concept of monitor/mutex — only one thread can hold the monitor.
• Keyword: synchronized — can be applied to methods or blocks.
• Prevents race conditions and data inconsistency in multithreaded programs.
synchronized void criticalMethod() {
// Only one thread executes this at a time
// Other threads wait until the lock is released
}
import [Link].*;
import [Link];
[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:company","postgres","");
if(rows > 0)
[Link]("Salary updated successfully.");
else
[Link]("Employee not found.");