0% found this document useful (0 votes)
2 views29 pages

Java II CS365 QnA

The document is a compilation of previous year question papers for a course on Object Oriented Programming using Java, covering various topics such as Collections, Multithreading, JDBC, Servlets & JSP, and the Spring Framework. It includes detailed questions and answers, programming exercises, and explanations of concepts like thread lifecycle, JDBC architecture, and differences between interfaces. The content is structured into multiple papers with sections for different types of questions, including definitions, applications, and coding tasks.

Uploaded by

ganesh.cs23041
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

Java II CS365 QnA

The document is a compilation of previous year question papers for a course on Object Oriented Programming using Java, covering various topics such as Collections, Multithreading, JDBC, Servlets & JSP, and the Spring Framework. It includes detailed questions and answers, programming exercises, and explanations of concepts like thread lifecycle, JDBC architecture, and differences between interfaces. The content is structured into multiple papers with sections for different types of questions, including definitions, applications, and coding tasks.

Uploaded by

ganesh.cs23041
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS-365

Object Oriented Programming


using Java - II
T.Y. [Link]. Computer Science | Semester VI
Previous Year Question Papers — Complete Answers

Paper 1 • Paper 2 • Paper 3 • Paper 4

Chapter Topics Covered

1. Collections Collection Framework, List, Set, Map, Iterator, ArrayList, LinkedList, HashSet, TreeSet, HashTable

2. Multithreading Thread creation, Lifecycle, Priorities, Synchronization, Interthread Communication, wait/notify

3. JDBC Architecture, Drivers, Statement, PreparedStatement, CallableStatement, ResultSet, Metadata

4. Servlets & JSP Servlet lifecycle, Session Tracking, Cookies, HttpSession, JSP lifecycle, Implicit Objects, Directive

5. Spring Framework Introduction, Modules, Architecture, Advantages, IoC, DI


PAPER 1 8×1=8 | 4×2=8 | 2×4=8 | 2×4=8 | 1×3=3

Q1) Attempt any EIGHT of the following [8 × 1 = 8]

Qa. Define Map Interface. [1 Mark]

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.

Qb. What is use of wait()? [1 Mark]

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)

Qc. What is use of getConnection()? [1 Mark]

getConnection() is a method of DriverManager class used to establish a connection to the database. Syntax:
Connection con = [Link](url, username, password);

Qd. What is a Scriptlet? [1 Mark]

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.

Qe. What is the purpose of JSP Directives? [1 Mark]

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.

Qf. Define Spring Framework. [1 Mark]

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.

Qg. Give the name of JDBC API. [1 Mark]

JDBC API interfaces and classes include: DriverManager, Connection, Statement, PreparedStatement,
CallableStatement, ResultSet, ResultSetMetaData, DatabaseMetaData.

Qh. Define Iterator Interface. [1 Mark]

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.

Qi. What is ArrayList? [1 Mark]

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.

Qj. Define Cookie. [1 Mark]

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]

Qa. How to create a Thread? [2 Marks]

There are two ways to create a thread in Java:


• Method 1 – Extend Thread class: Create a class that extends Thread, override run() method, create object
and call start().
• Method 2 – Implement Runnable interface: Implement run() method, pass object to Thread constructor,
call start().

// 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]();

Qb. List JDBC Drivers. [2 Marks]

There are four types of JDBC drivers:


• Type 1 – JDBC-ODBC Bridge Driver: Uses ODBC driver to connect. Requires ODBC configuration.
Platform-dependent.
• Type 2 – Native API Driver: Converts JDBC calls to database-specific native API calls. Requires native
library on client.
• Type 3 – JDBC Network Driver: Uses middleware server to translate JDBC calls. Pure Java,
platform-independent.
• Type 4 – Thin Driver (100% Pure Java): Directly converts JDBC calls to database protocol. Most commonly
used.

Qc. Differentiate between Set and List Interface. [2 Marks]

Set Interface List Interface

Does not allow duplicate elements Allows duplicate elements

No guaranteed insertion order (except LinkedHashSet) Maintains insertion order

Implemented by HashSet, TreeSet Implemented by ArrayList, LinkedList

No index-based access Supports index-based access (get(i))

Qd. Write any two methods of HttpSession. [2 Marks]

• 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.

Qe. What are the applications of Spring? [2 Marks]

• Web application development using Spring MVC framework.


• Enterprise applications using Dependency Injection and IoC container.
• RESTful Web Services using Spring REST.
• Data access applications using Spring JDBC / Spring ORM with Hibernate.
• Security-enabled applications using Spring Security module.

Q3) Attempt any TWO of the following [2 × 4 = 8]

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];

public class BookJDBC {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Enter B_id: ");
int bid = [Link]();
[Link]("Enter B_name: ");
String bname = [Link]();
[Link]("Enter B_cost: ");
double bcost = [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.");
}
}
}
}

public class AlphabetDemo {


public static void main(String[] args) {
AlphabetThread t = new AlphabetThread();
[Link]();
}
}
// Output: A (after 2s) B (after 2s) ... Z

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>

Q4) Attempt any TWO of the following [2 × 4 = 8]

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].*;

public class CountServlet extends HttpServlet {


public 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](24*60*60); // 1 day
[Link](c);
[Link]("<h2>Servlet invoked " + count + " time(s).</h2>");
}
}

Qb. Explain the Life Cycle of a Thread. [4 Marks]

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.

Qc. Differentiate between Statement and PreparedStatement Interface. [4 Marks]

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

Syntax: [Link]() Syntax: [Link](query)

Suitable for DDL statements (CREATE, DROP) Suitable for DML with varying values (INSERT, UPDATE)

No protection against SQL injection Protects against SQL injection


Q5) Attempt any ONE of the following [1 × 3 = 3]

Qa. Explain JDBC Architecture. [3 Marks]

JDBC architecture has two layers:


• JDBC API Layer: Provides Application-to-JDBC Manager connection. Includes interfaces like Connection,
Statement, ResultSet.
• JDBC Driver API Layer: Supports JDBC Manager-to-Driver connection. Translates Java calls to
database-specific protocol.
Components:
• Application: Java program (Servlet/Applet) that uses JDBC API.
• DriverManager: Manages list of database drivers. Selects appropriate driver for the connection URL.
• JDBC Driver: Translates JDBC API calls to DBMS-specific calls. 4 types: ODBC Bridge, Native API,
Network, Thin.
• Database: The target data source (MySQL, PostgreSQL, Oracle, etc.).
Flow: Application → JDBC API → DriverManager → JDBC Driver → Database

Qb. Write a Java program to accept 'n' numbers, store in LinkedList, display only
[3 Marks]
odd numbers.

import [Link].*;

public class OddLinkedList {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter n: ");
int n = [Link]();
LinkedList<Integer> list = new LinkedList<>();
for(int i = 0; i < n; i++) {
[Link]("Enter number: ");
[Link]([Link]());
}
[Link]("Odd Numbers:");
for(int num : list) {
if(num % 2 != 0)
[Link](num);
}
}
}
PAPER 2 8×1=8 | 4×2=8 | 2×4=8 | 2×4=8 | 1×3=3

Q1) Attempt any EIGHT of the following [8 × 1 = 8]

Qa. What is a Collection? [1 Mark]

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.

Qb. Define Thread Priority. [1 Mark]

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).

Qc. What is JDBC? [1 Mark]

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.

Qd. Define Session. [1 Mark]

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]().

Qe. What is the use of request object? [1 Mark]

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.

Qf. Write any one application of Spring. [1 Mark]

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.

Qg. What is the use of join() method? [1 Mark]

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.

Qh. Define HashTable. [1 Mark]

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.

Qi. What is the use of commit() method? [1 Mark]

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).

Qj. List any two implicit objects in JSP. [1 Mark]

1. request — HttpServletRequest object; holds client request data. 2. response — HttpServletResponse


object; used to send response. Others: out, session, application, config, pageContext, page, exception.
Q2) Attempt any FOUR of the following [4 × 2 = 8]

Qa. Write any two differences between ArrayList and LinkedList. [2 Marks]

ArrayList LinkedList

Based on dynamic array Based on doubly linked list

Fast random access O(1) Slow random access O(n)

Slow insertion/deletion in middle Fast insertion/deletion anywhere O(1)

Less memory (stores data only) More memory (stores data + two pointers)

Qb. Give any two fields of ResultSet Interface. [2 Marks]

• TYPE_FORWARD_ONLY: Cursor can only move forward. Read-only ResultSet.


• TYPE_SCROLL_SENSITIVE: Scrollable ResultSet; changes in database are reflected while ResultSet is
open.
• TYPE_SCROLL_INSENSITIVE: Scrollable but not sensitive to database changes.
• CONCUR_READ_ONLY: ResultSet cannot be updated. CONCUR_UPDATABLE: Allows updates.

Qc. Give any two types of Servlet. [2 Marks]

• GenericServlet: Protocol-independent servlet. Implements Servlet interface. Override service() method.


Part of [Link] package.
• HttpServlet: HTTP-specific servlet. Extends GenericServlet. Override doGet() or doPost(). Most commonly
used. Part of [Link] package.

Qd. Differentiate between sleep() and interrupt(). [2 Marks]

sleep() interrupt()

Pauses thread for specified milliseconds Sends interrupt signal to a sleeping/waiting thread

Static method: [Link](ms) Instance method: [Link]()

Thread automatically resumes after timeout Thread resumes by catching InterruptedException

Used to add delay in execution Used to stop or wake a blocked thread

Qe. Write a syntax of getCookies() method in Servlet. [2 Marks]

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]();
}
}

Q3) Attempt any TWO of the following [2 × 4 = 8]


Qa. Write a JDBC program to accept details of Student (RN, Name, Percentage)
[4 Marks]
from user and display those details.

import [Link].*;
import [Link];

public class StudentJDBC {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("RN: "); int rn = [Link]();
[Link]("Name: "); String name = [Link]();
[Link]("Percentage: "); double perc = [Link]();

[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:college","postgres","");

PreparedStatement pst = [Link](


"INSERT INTO Student VALUES(?,?,?)");
[Link](1, rn);
[Link](2, name);
[Link](3, perc);
[Link]();

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]();
}
}

Qb. Write a Java program in multithreading to display numbers 1 to 10. Each


[4 Marks]
number should display after 2 seconds.
class NumberThread extends Thread {
public void run() {
for(int i = 1; i <= 10; i++) {
[Link](i);
try {
[Link](2000);
} catch(InterruptedException e) {
[Link]("Interrupted");
}
}
}
}

public class NumberDemo {


public static void main(String[] args) {
NumberThread t = new NumberThread();
[Link]();
}
}

Qc. Write a JSP script to check whether the given number is prime or not. Display
[4 Marks]
result in blue 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);
boolean prime = (n > 1);
for(int i = 2; i <= [Link](n); i++) {
if(n % i == 0) { prime = false; break; }
}
if(prime) {
%>
<p style="color:blue;"><%= n %> is a PRIME number.</p>
<% } else { %>
<p style="color:blue;"><%= n %> is NOT a prime number.</p>
<% } } %>
</body></html>

Q4) Attempt any TWO of the following [2 × 4 = 8]

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].*;

public class ServerInfoServlet extends HttpServlet {


public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Server Information</h2>");
[Link]("<br>Server Name : " + [Link]());
[Link]("<br>Server Port : " + [Link]());
[Link]("<br>Server Info : " +
getServletContext().getServerInfo());
[Link]("<br>Protocol : " + [Link]());
[Link]("</body></html>");
}
}

Qb. Explain JSP Lifecycle in detail. [4 Marks]

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).

Qc. Explain Synchronization with an example. [4 Marks]

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); }

synchronized void display(String name) {


for(int i = 0; i < [Link]; i++) {
[Link](name + msg[i]);
}
}
public void run() { display(getName()); }
}

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.

Q5) Attempt any ONE of the following [1 × 3 = 3]

Qa. Explain execution process of Servlet application. [3 Marks]

• 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].*;

public class SortArrayList {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter n: ");
int n = [Link]();
ArrayList<String> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
[Link]("Enter name: ");
[Link]([Link]());
}
[Link](list);
[Link]("Sorted names:");
for(String name : list)
[Link](name);
}
}
PAPER 3 8×1=8 | 4×2=8 | 2×4=8 | 2×4=8 | 1×3=3

Q1) Attempt any EIGHT of the following [8 × 1 = 8]

Qa. What is the use of CallableStatement? [1 Mark]

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(?)}').

Qb. What is a Thread? [1 Mark]

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.

Qc. How is Servlet different from CGI? [1 Mark]

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.

Qd. Define Set. [1 Mark]

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.

Qe. List any two parameters using Scriptlet. [1 Mark]

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');

Qf. Define Spring. [1 Mark]

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.

Qg. Which interface is implemented by TreeSet class? [1 Mark]

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.

Qh. List any two methods of Statement interface. [1 Mark]

1. executeQuery(String sql) — Executes SELECT query; returns ResultSet. 2. executeUpdate(String sql) —


Executes INSERT/UPDATE/DELETE; returns int (rows affected). 3. execute(String sql) — Executes any SQL;
returns boolean.

Qi. Write the purpose of yield(). [1 Mark]

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.

Qj. What is a Cookie? [1 Mark]


A cookie is a small piece of information stored on the client's browser by the server. It is used for session
tracking. Created in Servlet: Cookie c = new Cookie('name','value'); [Link](c); Retrieved:
[Link]();

Q2) Attempt any FOUR of the following [4 × 2 = 8]

Qa. What is Map interface and how to implement it? [2 Marks]

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]());

Qb. What is DatabaseMetaData? [2 Marks]

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.

Qc. Give the names of directives in JSP. [2 Marks]

• <%@ 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' %>

Qd. State the types of Servlet. [2 Marks]

• GenericServlet: Protocol-independent. Extends GenericServlet ([Link]). Overrides


service(ServletRequest, ServletResponse). Suitable for any protocol.
• HttpServlet: HTTP-specific. Extends HttpServlet ([Link]). Overrides doGet()/doPost()/doPut()
etc. Most commonly used for web apps.

Qe. What are the thread priorities? [2 Marks]

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]();

Q3) Attempt any TWO of the following [2 × 4 = 8]

Qa. Write a Java program to accept 'N' student names, store in LinkedList and
[4 Marks]
display in reverse order.
import [Link].*;

public class ReverseLinkedList {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter N: ");
int n = [Link]();
LinkedList<String> list = new LinkedList<>();
for(int i = 0; i < n; i++) {
[Link]("Enter name: ");
[Link]([Link]());
}
[Link](list);
[Link]("Names in Reverse Order:");
for(String s : list)
[Link](s);
}
}

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];

public class StudentDB {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
int rn = [Link]();
String nm = [Link]();
double perc = [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'.

<%-- [Link] --%>


<html><body>
<form method="post" action="[Link]">
Username: <input type="text" name="uname"><br>
Password: <input type="password" name="pwd"><br>
<input type="submit" value="Login">
</form>

<%
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]

Qa. Explain Life Cycle of a Thread. [4 Marks]

(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.

Qb. What is session tracking? How to implement it? [4 Marks]

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:

HttpSession session = [Link]();


[Link]("user", username);
// In next servlet:
String user = (String) [Link]("user");

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];

public class DeleteTeacher {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Enter Teacher ID to delete: ");
int tid = [Link]();

[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:school","postgres","");

PreparedStatement pst = [Link](


"DELETE FROM Teacher WHERE tid=?");
[Link](1, tid);
int rows = [Link]();
[Link](rows + " record(s) deleted.");

ResultSet rs = [Link]()
.executeQuery("SELECT * FROM Teacher");
[Link]("tid\ttname\tsubject");
while([Link]())
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3));
[Link]();
}
}

Q5) Attempt any ONE of the following [1 × 3 = 3]

Qa. Explain the Architecture of Spring Framework. [3 Marks]

Spring Framework architecture consists of modules organized into layers:


• Core Container: Core, Beans, Context, SpEL. Core provides IoC and DI. Bean module provides
BeanFactory. Context initializes beans. SpEL provides expression language.
• Data Access/Integration Layer: JDBC (abstraction), ORM (Hibernate/JPA), JMS (messaging), OXM
(Object/XML), Transaction (programmatic & declarative).
• Web Layer: Web, Web-Servlet (Spring MVC), WebSocket (two-way communication), Web-Portlet.
• AOP & Instrumentation: AOP module for aspect-oriented programming. Aspects integrates with AspectJ.
Instrumentation provides class loader support.
• Test Module: Supports testing with JUnit and TestNG.

Qb. Explain the components of JSP. [3 Marks]

• 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

Q1) Attempt any EIGHT of the following [8 × 1 = 8]

Qa. Define Collection. [1 Mark]

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.

Qb. Give the name of JDBC API. [1 Mark]

JDBC API includes: DriverManager, Connection, Statement, PreparedStatement, CallableStatement, ResultSet,


ResultSetMetaData, DatabaseMetaData — all in [Link] package.

Qc. What is interthread communication? [1 Mark]

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.

Qd. What is a Servlet? [1 Mark]

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().

Qe. How to represent expression in JSP? [1 Mark]

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.

Qf. List modules in Spring. [1 Mark]

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.

Qg. Which interface is implemented by HashSet class? [1 Mark]

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.

Qh. What is use of getConnection()? [1 Mark]

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);

Qi. Define Multithreading. [1 Mark]

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.

Qj. What is a Session? [1 Mark]

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]

Qa. Differentiate between List and Set Interface. [2 Marks]

(Refer Paper 1 Q2-c for full table — same question.)

List Interface Set Interface

Allows duplicate elements Does not allow duplicates

Maintains insertion order No guaranteed order (HashSet)

Indexed access using get(i) No index-based access

ArrayList, LinkedList, Vector HashSet, TreeSet, LinkedHashSet

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.

Qc. Write a syntax of doGet(). [2 Marks]

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Set content type
[Link]("text/html");
// Get PrintWriter to send response
PrintWriter out = [Link]();
[Link]("<h1>Hello from doGet!</h1>");
}
// Called automatically for HTTP GET requests

Qd. What are advantages of JSP over Servlet? [2 Marks]

• 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.

Qe. How to create a thread in multithreading? [2 Marks]

(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();

// Way 2: Implement Runnable


class T2 implements Runnable {
public void run() { [Link]("T2 running"); }
}
new Thread(new T2()).start();

Q3) Attempt any TWO of the following [2 × 4 = 8]

Qa. Write a Java program to accept N integers, store in suitable collection and
[4 Marks]
display only even integers.

import [Link].*;

public class EvenNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter N: ");
int n = [Link]();
ArrayList<Integer> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
[Link]("Enter number: ");
[Link]([Link]());
}
[Link]("Even Numbers:");
for(int num : list) {
if(num % 2 == 0)
[Link](num);
}
}
}

Qb. Write a Java program to accept details of Teacher (Tid, Tname, Tsubject),
[4 Marks]
store in database and display.
import [Link].*;
import [Link];

public class TeacherJDBC {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Tid: "); int tid = [Link]();
[Link]("Tname: "); String tname = [Link]();
[Link]("Tsubject: "); String tsub = [Link]();

[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:school","postgres","");

PreparedStatement pst = [Link](


"INSERT INTO Teacher VALUES(?,?,?)");
[Link](1, tid);
[Link](2, tname);
[Link](3, tsub);
[Link]();
[Link]("Teacher record inserted.");

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>

Q4) Attempt any TWO of the following [2 × 4 = 8]

Qa. Explain the Life Cycle of JSP. [4 Marks]

(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().

Qb. Explain Synchronization with an example. [4 Marks]

(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
}

Qc. Write a Java program to update salary of a given employee using


[4 Marks]
PreparedStatement. Assume Emp(Eno, Ename, Esal).

import [Link].*;
import [Link];

public class UpdateSalary {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Enter Employee No to update: ");
int eno = [Link]();
[Link]("Enter new salary: ");
double newSal = [Link]();

[Link]("[Link]");
Connection con = [Link](
"jdbc:postgresql:company","postgres","");

PreparedStatement pst = [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.");

// Display updated record


PreparedStatement pst2 = [Link](
"SELECT * FROM Emp WHERE Eno=?");
[Link](1, eno);
ResultSet rs = [Link]();
while([Link]())
[Link]([Link](1)+" "+
[Link](2)+" "+[Link](3));
[Link]();
}
}

Q5) Attempt any ONE of the following [1 × 3 = 3]

Qa. What is Spring Framework? Explain its advantages. [3 Marks]


Spring Framework is an open-source, lightweight Java application framework that provides Inversion of
Control (IoC) and Dependency Injection (DI) for enterprise Java development.
Advantages:
• Lightweight: Uses POJO (Plain Old Java Objects) — no need for heavyweight EJB containers.
• Inversion of Control (IoC): Reduces tight coupling between components. Objects don't create their
dependencies — the framework injects them.
• Dependency Injection: Promotes loose coupling; easier to test with mock objects.
• Modular: Use only the modules you need (Core, MVC, Security, JDBC, etc.).
• Integration: Easily integrates with Hibernate, JPA, Struts, and other frameworks.
• Spring MVC: Built-in support for clean Model-View-Controller web development.
• Testability: POJO-based design makes unit testing straightforward.

Qb. Explain execution process of Servlet application. [3 Marks]

(Refer Paper 2 Q5-a for complete step-by-step execution process.)


• Step 1: Client sends HTTP request to Web Server.
• Step 2: Server identifies servlet request via URL mapping ([Link]/annotation) → forwards to Servlet
Container.
• Step 3: Servlet Container loads Servlet class (if first request).
• Step 4: Container instantiates the Servlet and calls init() once.
• Step 5: For each request, a new thread is created; service() method is called.
• Step 6: service() internally calls doGet() or doPost() based on HTTP method.
• Step 7: Servlet processes request, writes HTML to response.
• Step 8: On shutdown, destroy() is called for cleanup.

You might also like