0% found this document useful (0 votes)
1 views

Advance Java

The document provides an overview of various technical concepts including types of ResultSet, IP addresses, JDBC, servlets, cookies, UDP, threads, sockets, JSP directives, and networking. It also explains JDBC interfaces, the differences between HttpServlet and GenericServlet, the life cycle of JSP, synchronization in concurrent programming, and includes a Java program for counting records in a database table. Additionally, it details the Statement interface in JDBC, highlighting its purpose and key methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Advance Java

The document provides an overview of various technical concepts including types of ResultSet, IP addresses, JDBC, servlets, cookies, UDP, threads, sockets, JSP directives, and networking. It also explains JDBC interfaces, the differences between HttpServlet and GenericServlet, the life cycle of JSP, synchronization in concurrent programming, and includes a Java program for counting records in a database table. Additionally, it details the Statement interface in JDBC, highlighting its purpose and key methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 67

1

a) List types of ResultSet.


The types of ResultSet are:
* TYPE_FORWARD_ONLY: Moves only forward.
* TYPE_SCROLL_INSENSITIVE: Scrollable, but not sensitive to changes made by
others.
* TYPE_SCROLL_SENSITIVE: Scrollable and sensitive to changes made by others.

b) What is IP Address?
An IP (Internet Protocol) address is a numerical label assigned to each device
connected to a computer network that uses the Internet Protocol for communication. It
serves to identify and locate the host in the network.

c) What is JDBC?
JDBC (Java Database Connectivity) is a Java API used to connect and interact with
different types of databases. It provides a standard way for Java programs to perform
database operations like querying and updating data.

d) What is servlet?
A servlet is a Java programming language class used to extend the capabilities of
servers that host applications accessed by means of a request-response programming
model. They are commonly used to build dynamic web content.

e) What are cookies?


Cookies are small text files that web servers store on a user's computer through their
web browser. They are used to remember information about the user, such as login
details, preferences, and browsing history.

f) What is UDP?
UDP (User Datagram Protocol) is a connectionless protocol that, like TCP, runs on top
of IP networks. It provides a low-overhead transmission of data packets but does not
guarantee delivery or order.

g) What is a thread?
A thread is a lightweight sub-process within a larger process. It allows for concurrent
execution of different parts of a program, improving performance and responsiveness.

h) What is a socket?
A socket is an endpoint of a two-way communication link between two programs
running on the network. It is defined by an IP address and a port number.
i) List the directives in JSP.
2

The directives in JSP are:


* page
* include
* taglib

j) What is networking?
Networking refers to the practice of connecting two or more computing devices together
so that they can communicate and share resources. This allows for the exchange of
data and information.

a) List & explain all the interfaces used in JDBC.


JDBC (Java Database Connectivity) provides a set of interfaces that enable Java
applications to interact with databases. Here are the key interfaces:
* Driver: This interface represents a database driver implementation. Each database
vendor provides its own Driver implementation. The DriverManager uses Driver
implementations to establish a connection with a specific database. Key methods
include connect() to establish a database connection and acceptsURL() to check if the
driver can handle a given database URL.
* Connection: This interface represents a session with a specific database. It allows
you to create statements to execute SQL queries and manage transactions. Key
methods include createStatement(), prepareStatement(), callableStatement(), commit(),
rollback(), and close().
* Statement: This interface represents a basic SQL statement that can be executed. It's
used for simple SQL queries without parameters. Key methods include executeQuery()
for SELECT statements and executeUpdate() for INSERT, UPDATE, and DELETE
statements.
* PreparedStatement: This interface extends Statement and represents a pre-compiled
SQL statement. It's more efficient for executing the same SQL statement multiple times
with different parameter values and helps prevent SQL injection vulnerabilities.
Placeholders (?) are used for parameters, which are then set using methods like
setInt(), setString(), etc.
* CallableStatement: This interface also extends PreparedStatement and is used to
execute stored procedures in the database. It provides methods to register output
parameters and retrieve their values after executing the stored procedure (e.g.,
registerOutParameter(), getInt(), getString()).
* ResultSet: This interface represents the result set of a SQL query. It provides
methods to navigate through the rows of the result and retrieve the data from each
column. Key methods include next() to move to the next row and getString(), getInt(),
getBoolean(), etc., to retrieve data based on column name or index.
3

* ResultSetMetaData: This interface provides information about the structure of a


ResultSet, such as the number of columns, the names and types of columns, and
whether a column can be null. You can obtain an instance of ResultSetMetaData using
the getMetaData() method of a ResultSet object.

b) Differentiate between HttpServlet and GenericServlet.


Both HttpServlet and GenericServlet are abstract classes in Java's Servlet API that
serve as base classes for creating servlets. However, they differ in their protocol-
specific implementation:
| Feature | GenericServlet | HttpServlet |
|---|---|---|
| Protocol | Protocol-independent. Can handle various protocols. | Specifically designed
for the HTTP protocol. |
| Service Method | Contains a single abstract service() method that takes
ServletRequest and ServletResponse objects. | Provides specialized service methods
for HTTP requests like doGet(), doPost(), doPut(), doDelete(), etc., taking
HttpServletRequest and HttpServletResponse objects. |
| Usage | Used as a base class when the servlet needs to handle requests from different
protocols. Less common for typical web applications. | The most commonly used base
class for building web applications that communicate using the HTTP protocol. |
| Convenience | Requires the developer to handle protocol-specific details within the
service() method. | Provides a more convenient and structured way to handle different
HTTP request methods. The framework dispatches requests to the appropriate doXXX()
method. |
| Abstraction Level | Lower level of abstraction regarding web protocols. | Higher level of
abstraction specifically for HTTP. |
In essence, if you are building a servlet that will only handle HTTP requests (which is
the vast majority of web applications), you should extend HttpServlet. It provides a more
natural and easier way to manage different HTTP methods. GenericServlet is more
suitable for scenarios where a servlet might need to handle requests from various
protocols, which is less common in typical web development.

c) Explain the life cycle of JSP with a suitable diagram.


The life cycle of a JavaServer Page (JSP) involves several phases, from its initial
request to its destruction. Here's a breakdown of these phases:
* Translation Phase: When a client (e.g., a web browser) requests a JSP page for the
first time or when the JSP file has been modified, the JSP container (part of the web
server) translates the JSP file into a Java servlet source code file. This involves:
* Parsing the JSP page.
4

* Converting HTML tags and static content directly into Java code for output.
* Processing JSP elements (directives, scriptlets, expressions, actions) and
converting them into corresponding Java code.
* Compilation Phase: The servlet source code generated in the translation phase is
then compiled by the Java compiler into a servlet class file (.class file).
* Class Loading Phase: The JSP container loads the generated servlet class into the
server's memory.
* Instantiation Phase: The JSP container creates an instance (object) of the loaded
servlet class. This instance handles subsequent requests for the same JSP page.
* Initialization Phase: The JSP container initializes the servlet instance by calling its
jspInit() method. This method is called only once during the servlet's life cycle and is
used for one-time setup tasks.
* Request Processing Phase: When a client sends a request to the JSP page, the JSP
container invokes the _jspService() method of the servlet instance. This method
handles the client's request, processes any dynamic content, interacts with Java beans
or databases if necessary, and generates the response (typically HTML) that is sent
back to the client. The _jspService() method is executed for each client request.
* Destruction Phase: When the JSP container decides to remove the servlet instance
from memory (e.g., during server shutdown or application undeployment), it calls the
jspDestroy() method. This method is called only once and allows the servlet to perform
any cleanup tasks, such as releasing resources.
Here's a simple diagram illustrating the JSP life cycle:
+-----------------+ +---------------------+ +-------------------+ +-------------------+
+---------------------+ +----------------------+ +-------------------+
| Client Request |----->| JSP Container |----->| Translation (.jsp -> |----->|
Compilation (.java |----->| Class Loading |----->| Instantiation (Servlet|----->|
Initialization |
| (.jsp) | | (First Time/Modify) | | .java) | | -> .class) | |
| | Object Creation) | | (jspInit()) |
+-----------------+ +---------------------+ +-------------------+ +-------------------+
+---------------------+ +----------------------+ +-------------------+
^
|
|
|

+-------------------------------------------------------------------------------------------------------------------
----------------+

|
5

+-----------------+ +---------------------+
+-----------------+
| Client Request |----->| JSP Container |----->|
Request |
| (.jsp) | | (Subsequent) | | Processing
|
+-----------------+ +---------------------+ |
(_jspService()) |
| +-----------------+
| |
| v
| +-----------------+
| | Response |
| | (HTML) |
| +-----------------+
| |
v |
+-----------------+ +---------------------+
+-------------------+
| Server Shutdown |----->| JSP Container |----->|
Destruction |
| / Undeployment | | | |
(jspDestroy()) |
+-----------------+ +---------------------+
+-------------------+

D) What is synchronization? Explain.


In concurrent programming, where multiple threads execute within a single program,
synchronization refers to the mechanism of controlling the access of multiple threads to
shared resources. The primary goal of synchronization is to prevent race conditions and
ensure data consistency when multiple threads try to read and write to the same data.
Imagine several people trying to write in the same notebook simultaneously. Without
any rules, their writing would overlap and become garbled. Synchronization in
programming acts like these rules, ensuring that only one thread can access a critical
section of code (a part that accesses shared resources) at any given time.
Here's a breakdown of why synchronization is important and how it works conceptually:
* Preventing Race Conditions: A race condition occurs when the outcome of a program
depends on the unpredictable order in which multiple threads execute. This can lead to
6

incorrect results. Synchronization helps establish a predictable and controlled order of


access.
* Ensuring Data Consistency: When multiple threads modify shared data concurrently
without proper synchronization, the data can become inconsistent. For example, if one
thread is in the middle of updating a value, and another thread reads it, the second
thread might read an incomplete or incorrect value. Synchronization ensures that
operations on shared data are atomic or happen in a controlled sequence.
Common Synchronization Mechanisms:
Java provides several mechanisms for achieving synchronization:
* synchronized keyword: This is the most fundamental way to achieve synchronization
in Java. It can be used to synchronize entire methods or specific blocks of code. When
a thread enters a synchronized method or block, it acquires a lock on the object
associated with the method or the object specified in the synchronized block. Other
threads trying to enter the same synchronized method or block on the same object will
be blocked until the first thread releases the lock.
* java.util.concurrent package: This package provides a rich set of utility classes for
concurrent programming, including more advanced synchronization primitives like:
* Locks: Interfaces like Lock and its implementations like ReentrantLock offer more
flexible locking mechanisms compared to the synchronized keyword. They provide
features like timed waits, fair locking, and the ability to interrupt waiting threads.
* Semaphores: These control the number of threads that can access a shared
resource concurrently.
* CountDownLatch: This allows one or more threads to wait until a set of operations
being performed in other threads has completed.
* CyclicBarrier: This allows a set of threads to all wait for each other to reach a
common barrier point.
* Exchanger: This allows two threads to exchange objects safely.
In essence, synchronization is a crucial concept in multithreaded programming that
ensures the correct and consistent execution of programs when multiple threads share
resources.

e) Write a Java program to count the number of records in a table?


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CountRecords {


7

public static void main(String[] args) {


String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
String password = "your_password";
String tableName = "your_table_name";

Connection connection = null;


Statement statement = null;
ResultSet resultSet = null;

try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver"); // Replace with your database driver

// Establish the connection


connection = DriverManager.getConnection(url, username, password);

// Create a statement
statement = connection.createStatement();

// Execute the query to count records


String sql = "SELECT COUNT(*) FROM " + tableName;
resultSet = statement.executeQuery(sql);

// Retrieve the count


if (resultSet.next()) {
int count = resultSet.getInt(1);
System.out.println("Number of records in table '" + tableName + "': " + count);
} else {
System.out.println("Could not retrieve the record count.");
}

} catch (ClassNotFoundException e) {
System.err.println("JDBC driver not found: " + e.getMessage());
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
} finally {
// Close resources in reverse order of creation
try {
8

if (resultSet != null) resultSet.close();


if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}

Explanation:
* Import necessary classes: We import classes from java.sql for database interaction.
* Database credentials and table name: You need to replace the placeholder values for
url, username, password, and tableName with your actual database connection details
and the name of the table you want to query.
* Establish connection:
* Class.forName("com.mysql.cj.jdbc.Driver");: This line loads the JDBC driver for your
specific database (in this case, MySQL). You'll need to change this if you're using a
different database (e.g., org.postgresql.Driver for PostgreSQL,
oracle.jdbc.driver.OracleDriver for Oracle). Make sure you have the appropriate JDBC
driver JAR file in your project's classpath.
* DriverManager.getConnection(url, username, password);: This establishes a
connection to the database using the provided URL and credentials.
* Create a statement: connection.createStatement(); creates a Statement object, which
is used to execute SQL queries.
* Execute the COUNT query:
* String sql = "SELECT COUNT(*) FROM " + tableName;: This constructs the SQL
query to count all rows in the specified table. COUNT(*) is an aggregate function that
returns the number of rows.
* resultSet = statement.executeQuery(sql);: This executes the SQL query and returns
a ResultSet object, which contains the result of the query.
* Retrieve the count:
* if (resultSet.next()): The next() method moves the cursor of the ResultSet to the next
row (which will be the first and only row in this case, containing the count).
* int count = resultSet.getInt(1);: This retrieves the integer value from the first column
of the current row in the ResultSet (which is the count returned by COUNT(*)).
* System.out.println(...): This prints the retrieved count.
* Handle exceptions: The try-catch block handles potential ClassNotFoundException (if
the JDBC driver is not found) and SQLException (for any database-related errors).
9

* Close resources: The finally block ensures that the database connection, statement,
and result set are closed properly, regardless of whether an exception occurred. This is
crucial for releasing database resources.

a) Explain the Statement interface in detail.


The java.sql.Statement interface in Java JDBC (Java Database Connectivity) is a
fundamental interface used to execute basic SQL statements against a database. It
provides a way to interact with the database and perform operations like querying,
inserting, updating, and deleting data.
Here's a detailed explanation of the Statement interface:
Purpose:
* To send SQL statements to the database.
* To execute simple SQL queries without any input parameters.
* To retrieve results from executed queries.
Key Methods:
The Statement interface defines several important methods:
* ResultSet executeQuery(String sql) throws SQLException:
* Executes an SQL query that returns a single ResultSet object (e.g., SELECT
statements).
* Returns a ResultSet object that provides access to the data retrieved from the
database.
* Throws an SQLException if a database access error occurs.
* int executeUpdate(String sql) throws SQLException:
* Executes an SQL statement that does not return a ResultSet (e.g., INSERT,
UPDATE, DELETE, CREATE TABLE, DROP TABLE).
* Returns an integer indicating the number of rows affected by the statement. For DDL
(Data Definition Language) statements, the return value might be 0 or unspecified by
some JDBC drivers.
* Throws an SQLException if a database access error occurs.
* boolean execute(String sql) throws SQLException:
* Executes an SQL statement that might return multiple results (including ResultSet
objects and update counts) or no result at all.
* Returns true if the first result is a ResultSet object; false if it is an update count or no
result.
* You need to use getResultSet(), getUpdateCount(), and getMoreResults() to
process the results.
* Generally less commonly used for simple queries and updates compared to
executeQuery and executeUpdate.
* Throws an SQLException if a database access error occurs.
* void close() throws SQLException:
10

* Releases this Statement object's database and JDBC resources immediately.


* It's crucial to close Statement objects when you're finished with them to prevent
resource leaks.
* Throws an SQLException if a database access error occurs.
* int getMaxFieldSize() throws SQLException:
* Retrieves the maximum number of bytes that can be returned for character and
binary column values in a ResultSet produced by this Statement object.
* Returns 0 if there is no limit.
* void setMaxFieldSize(int max) throws SQLException:
* Sets the limit for the maximum number of bytes that can be returned for character
and binary column values in a ResultSet produced by this Statement object.
* int getMaxRows() throws SQLException:
* Retrieves the maximum number of rows that a ResultSet produced by this
Statement object can contain.
* Returns 0 if there is no limit.
* void setMaxRows(int max) throws SQLException:
* Sets the limit for the maximum number of rows that any ResultSet object generated
by this Statement object can contain.
* void setEscapeProcessing(boolean enable) throws SQLException:
* Sets escape processing on or off. If escape scanning is enabled (the default), the
JDBC driver will perform escape substitution before sending the SQL statement to the
database.
* int getQueryTimeout() throws SQLException:
* Retrieves the number of seconds the driver will wait for a Statement object to
execute. Returns 0 if there is no limit.
* void setQueryTimeout(int seconds) throws SQLException:
* Sets the number of seconds the driver will wait for a Statement object to execute to
the given number of seconds.
* SQLWarning getWarnings() throws SQLException:
* Retrieves the first warning reported by calls on this Statement object. Subsequent
warnings will be chained to this SQLWarning object.
* void clearWarnings() throws SQLException:
* Clears all the warnings reported on this Statement object.
* void setCursorName(String name) throws SQLException:
* Sets the SQL cursor name that will be used by subsequent Statement object's
execute methods.
Limitations of Statement:
* Vulnerability to SQL Injection: Since SQL statements are constructed by
concatenating strings, Statement is susceptible to SQL injection attacks if user-provided
input is directly included in the SQL query without proper sanitization.
11

* Inefficient for Repeated Queries: If you need to execute the same SQL query multiple
times with different parameter values, using Statement is inefficient because the
database has to parse and prepare the query each time.
Alternatives:
For more secure and efficient execution of parameterized SQL queries, it's highly
recommended to use the PreparedStatement interface, which precompiles the SQL
statement and allows you to set parameter values safely.
In summary, the Statement interface is a basic tool in JDBC for executing static SQL
statements. While it's suitable for simple, non-parameterized queries, developers should
be aware of its limitations, especially regarding security and efficiency, and consider
using PreparedStatement for more complex scenarios.

b) Explain Thread priority in detail.


In Java, thread priority is a mechanism that allows the operating system's thread
scheduler to determine the order in which threads are given preference for execution.
Each thread is assigned a priority level, represented by an integer value. The scheduler
generally favors threads with higher priority over threads with lower priority.
Key Concepts:
* Priority Range: Thread priorities in Java are typically within the range of 1 (lowest
priority) to 10 (highest priority).
* Default Priority: When a thread is created without explicitly setting its priority, it
inherits the priority of the thread that created it. The default priority of the main thread is
usually 5 (normal priority).
* Constants: The Thread class provides three static constants for common priority
levels:
* Thread.MIN_PRIORITY (value 1)
* Thread.NORM_PRIORITY (value 5)
* Thread.MAX_PRIORITY (value 10)
* setPriority(int newPriority): This method of the Thread class is used to change the
priority of a thread. The newPriority argument must be within the valid range (1 to 10).
* getPriority(): This method returns the current priority of the thread.
How Thread Priority Works (Theoretically):
The thread scheduler in the operating system is responsible for deciding which thread
gets to run at any given time. A preemptive priority-based scheduling algorithm is
commonly used. In this model:
* Higher Priority Gets Preference: Threads with higher priority are generally given
preference over threads with lower priority. The scheduler will try to run the highest-
priority runnable threads first.
* Time Slicing: If multiple threads have the same priority, the scheduler typically uses
time slicing. Each thread gets a small time quantum to execute, and then the CPU is
12

switched to another thread of the same priority. This gives the illusion of concurrent
execution.
* Preemption: A higher-priority thread can preempt (interrupt) a currently running lower-
priority thread. The lower-priority thread will be paused, and the higher-priority thread
will get the CPU. The preempted thread will resume execution when no higher-priority
threads are runnable.
Important Considerations and Limitations:
* Platform Dependence: The actual behavior of thread priorities can vary significantly
across different operating systems and JVM implementations. The mapping of Java's 10
priority levels to the underlying OS priority levels is not guaranteed to be one-to-one.
Some operating systems might have fewer priority levels or might not strictly adhere to
the priority-based scheduling.
* No Guarantee of Execution: Setting a higher priority does not guarantee that a thread
will always run or will run for a specific duration. The scheduler's decisions are
influenced by various factors, including the number of runnable threads, system load,
and the OS's scheduling algorithm.
* Starvation: It's possible for low-priority threads to experience starvation, meaning they
might never get a chance to run if there are always higher-priority runnable threads.
Careful design is needed to avoid this.
* Subtle Effects: Relying heavily on thread priorities for critical synchronization or
correctness can lead to subtle and hard-to-debug issues due to the platform-dependent
nature and the scheduler's complexity.
* Best Practices: Generally, it's better to rely on proper synchronization mechanisms
(like locks, semaphores, and concurrent utilities) for controlling access to shared
resources and coordinating thread execution rather than solely depending on thread
priorities for correctness. Thread priorities can be useful for fine-tuning performance in
certain scenarios where you want to give preference to time-critical tasks, but they
should be used judiciously and with a thorough understanding of their limitations.
Use Cases (with caution):
* Real-time systems (with careful consideration): In some real-time applications, higher
priority might be assigned to critical tasks that need to be executed promptly. However,
even in these cases, proper synchronization is still essential.
* Background tasks: Lower priority might be assigned to long-running background tasks
that are less time-sensitive.
* User interface responsiveness: Giving slightly higher priority to UI-related threads
might improve the responsiveness of the application.
In conclusion, thread priority in Java is a hint to the operating system's thread scheduler
about the relative importance of threads. While it can influence the scheduling
decisions, it's not a deterministic mechanism and its behavior can vary across platforms.
For ensuring correctness and managing concurrency effectively, robust synchronization
techniques are generally preferred over sole reliance on thread priorities.
13

c) Differentiate between TCP socket and UDP socket.


Both TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are
fundamental protocols in the transport layer of the TCP/IP model, enabling
communication between applications over a network. However, they differ significantly
in their characteristics and are suited for different types of applications.
Here's a table summarizing the key differences:
| Feature | TCP Socket | UDP Socket |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Reliable (guaranteed delivery) | Unreliable (best-effort delivery) |
| Ordering | Guarantees ordered delivery of packets | |

d) Write a Java program to print “Hello Java” message 10 times.


public class PrintHello {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Hello Java");
}
}
}

e) Write a Java program to delete the salary column from the Emp table. Assume the
Emp table with attributes ENo, EName, and salary is already created.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DeleteSalaryColumn {

public static void main(String[] args) {


String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
String password = "your_password";
String tableName = "Emp";
14

String columnNameToDelete = "salary";

Connection connection = null;


Statement statement = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Replace with your database driver
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
String sql = "ALTER TABLE " + tableName + " DROP COLUMN " +
columnNameToDelete;
statement.executeUpdate(sql);
System.out.println("Column '" + columnNameToDelete + "' successfully deleted
from table '" + tableName + "'.");
} catch (ClassNotFoundException e) {
System.err.println("JDBC driver not found: " + e.getMessage());
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
} finally {
try {
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}

a) Write a Java program to display the IP Address of a Machine.


import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIPAddress {


public static void main(String[] args) {
try {
// Get the local host
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("IP Address of this machine: " + localHost.getHostAddress());
15

} catch (UnknownHostException e) {
System.err.println("Could not get the IP address: " + e.getMessage());
}
}
}

b) Explain the Architecture of Hibernate.


Hibernate is an Object-Relational Mapping (ORM) framework for Java that simplifies the
interaction between Java applications and relational databases. It provides a layer of
abstraction that maps Java objects to database tables and handles the persistence
logic, freeing developers from writing repetitive JDBC code.
The core architecture of Hibernate consists of the following key components:
* Configuration: The Configuration object is the central component used to configure
Hibernate. It reads configuration metadata from a Hibernate configuration file (e.g.,
hibernate.cfg.xml) or programmatically. This metadata includes database connection
details, mappings between Java classes and database tables, and other Hibernate
settings. The Configuration object is typically created only once per application.
* SessionFactory: The SessionFactory is a factory for Session objects. It is a
heavyweight, thread-safe object that is created once during application startup based on
the Configuration. It caches compiled mapping metadata and JDBC connection pools.
Multiple threads can concurrently access the SessionFactory.
* Session: The Session is a lightweight, non-thread-safe object that represents a single
unit of work with the database. It provides methods for persisting, retrieving, updating,
and deleting Java objects, as well as executing HQL (Hibernate Query Language) or
native SQL queries. A new Session is typically opened for each transaction or unit of
work and closed afterward.
* Transaction: The Transaction interface represents a unit of work with the database.
Hibernate transactions are typically managed using the Transaction object obtained
from the Session. It provides methods for starting, committing, and rolling back
transactions. Hibernate supports both JDBC transactions and JTA (Java Transaction
API) for managing transactions across multiple resources.
* Query: The Query interface is used to execute HQL queries against the database.
HQL is an object-oriented query language that allows you to query Java objects and
their properties, which Hibernate then translates into SQL.
* Criteria: The Criteria API provides a programmatic way to build queries using Java
objects and criteria instead of writing HQL strings. It's a more object-oriented approach
to querying.
* Native SQL: Hibernate allows you to execute native SQL queries directly through the
Session if you need database-specific features or optimizations.
16

* Interceptor: The Interceptor interface allows you to intercept Hibernate events (e.g.,
before saving an object, after loading an object) and perform custom logic. Interceptors
can be used for tasks like auditing, logging, or modifying object states.
* Mapping Metadata: This defines how Java classes are mapped to database tables.
Mapping metadata can be specified using XML files (.hbm.xml) or through Java
annotations. It includes information about table names, column names, primary keys,
relationships between entities, and data types.
Interaction Flow:
* The application loads the Hibernate configuration using the Configuration object.
* The Configuration object is used to build a single SessionFactory.
* For each unit of work, the application obtains a Session from the SessionFactory.
* The application starts a Transaction through the Session.
* The application performs database operations using the Session (e.g., save(), get(),
update(), delete(), createQuery(), createCriteria()). Hibernate handles the mapping of
Java objects to database records and generates the necessary SQL.
* The application commits or rolls back the Transaction.
* The Session is closed.
* When the application shuts down, the SessionFactory is also closed.
In essence, Hibernate acts as a mediator between your Java application's object model
and the relational database, handling the complexities of data persistence and retrieval.

c) Explain the life cycle of a servlet with a suitable diagram.


A servlet is a Java programming language class that is used to extend the capabilities
of servers that host applications accessed by means of a request-response
programming model. Servlets are commonly used to handle client requests and
generate dynamic web content. The life cycle of a servlet is managed by the servlet
container (e.g., Tomcat, Jetty).
The servlet life cycle consists of the following stages:
* Loading and Instantiation:
* When the servlet container starts up or when the first request for a servlet arrives,
the container loads the servlet class into its memory.
* The container then creates an instance (object) of the servlet class. This
instantiation happens only once during the servlet's lifetime.
* Initialization:
* After instantiation, the servlet container calls the init(ServletConfig config) method of
the servlet.
* The ServletConfig object contains configuration information for the servlet, such as
initialization parameters defined in the web deployment descriptor (web.xml) or through
annotations.
17

* The init() method is called only once. It's where the servlet can perform one-time
setup tasks, such as establishing database connections, initializing resources, or
reading configuration parameters.
* Request Handling:
* For each client request that targets the servlet, the servlet container creates two
objects:
* HttpServletRequest: This object encapsulates the client's request information,
including parameters, headers, and attributes.
* HttpServletResponse: This object is used to send a response back to the client,
including content type, status codes, and the response body.
* The container then calls the service method of the servlet. For HttpServlet, this
method is service(HttpServletRequest request, HttpServletResponse response).
* The service() method typically determines the HTTP request method (GET, POST,
PUT, DELETE, etc.) and dispatches the request to the appropriate handler method,
such as doGet(), doPost(), doPut(), doDelete(), etc.
* These doXXX() methods contain the actual logic to process the client's request and
generate the response.
* The service() method can be called multiple times, once for each incoming request
to the servlet.
* Destruction:
* When the servlet container is shutting down or when it decides to remove a servlet
instance (e.g., due to inactivity or redeployment), it calls the destroy() method of the
servlet.
* The destroy() method is called only once, before the servlet instance is garbage
collected.
* It provides an opportunity for the servlet to perform cleanup tasks, such as closing
database connections, releasing resources, or saving persistent data.
Servlet Life Cycle Diagram:
graph TD
A[Servlet Class Loaded] --> B(Servlet Instantiated);
B --> C{init(ServletConfig config) called};
C -- Once --> D[Servlet Ready to Handle Requests];
D --> E{service(HttpServletRequest, HttpServletResponse) called};
E -- Multiple times --> F[Process Request & Generate Response];
F --> D;
D --> G{destroy() called};
G -- Once --> H[Servlet Instance Destroyed];

.
d) What is multithreading? Explain.
18

Multithreading is a concurrency mechanism that allows a single process to execute


multiple parts (threads) of a program concurrently. Instead of running tasks sequentially,
multithreading enables different parts of a program to run seemingly at the same time,
improving performance and responsiveness, especially in applications that involve time-
consuming operations.
Key Concepts:
* Process: A process is an independent execution environment with its own memory
space, resources (e.g., files, network connections), and at least one thread of execution.
When you run a program, the operating system creates a process for it.
* Thread: A thread is the smallest unit of execution within a process. Multiple threads
can exist within a single process and share the process's memory space and resources.
Each thread has its own program counter, stack, and local variables.
* Concurrency vs. Parallelism:
* Concurrency: Multiple tasks make progress over time, but they might not be
executing simultaneously at every instant. On a single-core processor, concurrency is
achieved through time-sharing, where the CPU rapidly switches between threads, giving
the illusion of parallel execution.
* Parallelism: Multiple tasks are executed simultaneously on multiple processors or
cores. True parallelism requires hardware with multiple execution units. Multithreading
can enable parallelism if the underlying hardware supports it.
Benefits of Multithreading:
* Improved Responsiveness: In applications with graphical user interfaces (GUIs),
performing long-running tasks in a separate thread prevents the GUI from becoming
unresponsive. The user can continue interacting with the application while the
background task is executing.
* Increased Performance: For applications that can divide their workload into
independent tasks, multithreading can lead to significant performance improvements,
especially on multi-core processors. Multiple threads can execute these tasks in
parallel, reducing the overall execution time.
* Better Resource Utilization: Threads within the same process share resources, which
can be more efficient than creating multiple processes, each with its own memory
space.
* Simplified Program Structure: For certain types of problems, using multiple threads
can lead to a more modular and easier-to-manage program structure by separating
different concerns into independent threads.
Challenges of Multithreading:
* Complexity: Designing and debugging multithreaded programs can be more complex
than single-threaded programs due to issues like race conditions, deadlocks, and thread
interference.
19

* Synchronization: When multiple threads access shared resources, it's crucial to use
synchronization mechanisms (e.g., locks, semaphores) to prevent data corruption and
ensure data consistency.
* Overhead: Creating and managing threads incurs some overhead in terms of memory
and CPU time. Excessive thread creation can sometimes degrade performance.
* Context Switching: The operating system needs to switch between running threads,
which involves saving the state of the current thread and loading the state of the next
thread. Frequent context switching can also introduce overhead.
Multithreading in Java:
Java provides built-in support for multithreading through the Thread class and the
Runnable interface. You can create new threads by:
* Extending the Thread class: Create a subclass of Thread and override the run()
method, which contains the code to be executed by the thread.
* Implementing the Runnable interface: Create a class that implements the Runnable
interface and provide the thread's code in the run() method. Then, create a Thread
object with an instance of your Runnable class.
You start a thread by calling its start() method, which creates a new thread of execution
and calls the run() method in that new thread.
In summary, multithreading is a powerful technique for achieving concurrency and
parallelism within a single process, leading to improved responsiveness and
performance. However, it also introduces complexities related to synchronization and
thread management that developers need to address carefully.

e) Write a Java Servlet program to accept name from the user & display it on the
browser [use HTML].
Here are the Java servlet and HTML code for this:
1. HTML Form (e.g., index.html):
<!DOCTYPE html>
<html>
<head>
<title>Enter Your Name</title>
</head>
<body>
<h1>Please Enter Your Name</h1>
<form action="NameServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="userName"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
20

2. Java Servlet (NameServlet.java):


import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/NameServlet")
public class NameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Set the content type of the response
response.setContentType("text/html");

// Get the name submitted from the HTML form


String name = request.getParameter("userName");

// Get the PrintWriter object to write the response to the client


PrintWriter out = response.getWriter();

// Generate the HTML response


out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Welcome!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, " + (name != null && !name.isEmpty() ? name : "Guest") + "!
</h1>");
out.println("</body>");
out.println("</html>");

// Close the PrintWriter


out.close();
21

}
}

a) notify(), notifyAll(), and wait()


These are fundamental methods for thread synchronization in Java, inherited from the
Object class. They are used to manage the interaction between threads that are waiting
on the same object's monitor.
* wait(): When a thread calls wait() on an object, it releases the object's lock and enters
the "waiting" state. It will remain in this state until another thread calls notify() or
notifyAll() on the same object, or the waiting thread is interrupted. The wait() method
must be called from within a synchronized block or method that holds the lock of the
object.
* notify(): This method wakes up a single thread that is waiting on the object's monitor.
If multiple threads are waiting, the JVM chooses one of them to wake up (the choice is
not guaranteed and can vary). The awakened thread does not immediately acquire the
lock; it must first compete with other threads that might be trying to acquire the lock
when the notifying thread releases it. notify() must also be called from within a
synchronized block or method that holds the lock of the object.
* notifyAll(): This method wakes up all threads that are waiting on the object's monitor.
Each of the awakened threads will then compete to acquire the lock of the object when
it becomes available. Using notifyAll() is generally safer than notify() as it avoids the
possibility of a waiting thread being missed if notify() happens to wake up another
thread that cannot proceed. notifyAll() must also be called from within a synchronized
block or method that holds the lock of the object.

b) Applications of Spring
The Spring Framework is a comprehensive application development framework for
Java, offering a wide range of features applicable across various domains:
* Enterprise Java Applications: Spring is widely used for building robust and scalable
enterprise-level applications, handling complex business logic and integrations.
* Web Development: Spring MVC provides a powerful model-view-controller framework
for building flexible and testable web applications.
* RESTful Web Services: Spring Boot and Spring WebFlux simplify the creation of
RESTful APIs.
* Microservices Architecture: Spring Cloud offers tools and patterns for building and
managing distributed microservices.
* Batch Processing: Spring Batch provides a framework for developing robust batch
processing applications.
22

* Data Access: Spring Data simplifies database interactions through repositories and
various data store integrations (JPA, MongoDB, etc.).
* Cloud-Native Applications: Spring Cloud enables the development of applications that
can easily integrate with cloud platforms.
* Testing: Spring provides extensive support for unit and integration testing of
application components.
* Security: Spring Security offers comprehensive security features for authentication
and authorization.
In essence, Spring's modularity and extensive ecosystem make it applicable to virtually
any type of Java application, from small web applications to large-scale enterprise
systems.

c) Connection Interface
In Java JDBC (Java Database Connectivity), the Connection interface represents a
session with a specific database. It is the primary interface for interacting with the
database once a connection has been established. Key aspects of the Connection
interface include:
* Establishing a Session: A Connection object represents an active link to the
database.
* Creating Statements: It provides methods to create Statement, PreparedStatement,
and CallableStatement objects, which are used to execute SQL queries.
* Transaction Management: It offers methods for managing transactions, such as
setAutoCommit(), commit(), and rollback().
* Metadata Retrieval: It allows access to database metadata through the getMetaData()
method, providing information about the database structure, supported features, etc.
* Closing the Connection: The close() method is crucial for releasing database
resources when the application is finished with the connection.
* Batch Updates: It supports batch execution of SQL statements for improved
performance.
The Connection interface is central to performing any database operation in Java using
JDBC. Implementations of this interface are provided by JDBC drivers for specific
database systems (e.g., MySQL Connector/J, PostgreSQL JDBC Driver).

a) Write down 2 packages of JDBC API.


* java.sql
* javax.sql

b) What is yield ( ) method?


23

The yield() method in Java is a static method of the Thread class that hints to the thread
scheduler that the current thread is willing to relinquish its current use of a processor.
The scheduler is free to ignore this hint.

c) What is JDBC ?
JDBC (Java Database Connectivity) is a Java API that allows Java programs to interact
with various relational databases. It provides a standard way to connect to and
manipulate databases using SQL.

d) What is scriptlet tag?


In JavaServer Pages (JSP), a scriptlet tag (<% ... %>) is used to embed Java code
directly within the HTML content of the JSP page. This Java code is executed on the
server when the JSP is processed.

e) What is wait ( ) and notify ( ) in multithreading?


* wait(): A method that causes the current thread to release the object's lock and enter
the waiting state until another thread notifies it.
* notify(): A method that wakes up a single thread that is waiting on the object's
monitor.

f) What is Networking?
Networking refers to the process of connecting two or more computing devices to
enable them to communicate and share resources.

g) What is Driver Manager class?


The DriverManager class in JDBC is responsible for managing a list of database
drivers. It handles the loading of drivers and establishes connections to databases
based on connection URLs.

h) What is ORM ?
ORM (Object-Relational Mapping) is a programming technique that maps objects in an
application to tables in a relational database, simplifying data access and manipulation.

i) What is Session?
24

In the context of Hibernate, a Session is a lightweight, non-thread-safe object


representing a single unit of work with the database. It provides methods for persisting,
retrieving, and manipulating persistent objects.

j) What is the role of Prepared Statement?


The primary role of a PreparedStatement in JDBC is to execute parameterized SQL
queries. This offers benefits like preventing SQL injection attacks and improving
performance for repeated queries with different parameters as the SQL is pre-compiled.

a) Explain the life cycle of a servlet.


The life cycle of a servlet, managed by the servlet container, involves several stages:
* Loading and Instantiation: The container loads the servlet class and creates a single
instance.
* Initialization: The init() method is called once, allowing the servlet to perform setup
tasks.
* Request Handling: The service() method handles multiple client requests, dispatching
them to doGet(), doPost(), etc.
* Destruction: The destroy() method is called once before the servlet instance is
removed, enabling cleanup operations.

b) Differentiate between Statement and PreparedStatement.


| Feature | Statement | PreparedStatement |
|---|---|---|
| SQL | Executes static SQL queries. | Executes pre-compiled SQL queries with
parameters. |
| Security | Vulnerable to SQL injection. | Protects against SQL injection. |
| Performance | Less efficient for repeated queries. | More efficient for repeated queries.
|
| Parameter Handling | Parameters are embedded directly into the SQL string. |
Parameters are passed separately, allowing for type checking and proper escaping. |
| Use Cases | Simple, non-parameterized queries. | Parameterized queries, especially
when executed multiple times. |

c) Explain Inter-Thread communication in Multithreading.


Inter-thread communication (ITC) enables threads to exchange information and
synchronize their actions. Java provides mechanisms like wait(), notify(), and notifyAll()
25

for this purpose. Threads can wait for specific conditions and be notified by other
threads when those conditions are met, ensuring coordinated execution.

d) Explain JSP Architecture.


JSP (JavaServer Pages) architecture involves the following:
* Client Request: A client requests a JSP page from the web server.
* JSP Processing: The web server forwards the request to the JSP container.
* Translation and Compilation: The JSP container translates the JSP page into a
servlet and compiles it.
* Servlet Execution: The compiled servlet executes, generating dynamic content.
* Response: The generated content is sent back to the client as an HTML response.

e) Write a JDBC Program to Insert the record into a patient table (Use
PreparedStatement).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertPatient {

public static void main(String[] args) {


String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
String password = "your_password";

try (Connection connection = DriverManager.getConnection(url, username,


password);
PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO patient (patient_id, name, age) VALUES (?, ?, ?)")) {

preparedStatement.setInt(1, 101); // Example patient_id


preparedStatement.setString(2, "John Doe"); // Example name
preparedStatement.setInt(3, 30); // Example age

int rowsAffected = preparedStatement.executeUpdate();

System.out.println(rowsAffected + " row(s) inserted.");


26

} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}

Here are the answers to your questions:


a) Explain JDBC Drivers with a suitable diagram.
JDBC drivers are software components that enable Java applications to interact with
specific database systems. They act as translators between the JDBC API calls in Java
and the database-specific communication protocols. There are four main types of JDBC
drivers:
* Type 1 (JDBC-ODBC Bridge Driver): This driver uses the ODBC (Open Database
Connectivity) driver installed on the client machine to communicate with the database.
It's platform-dependent as it relies on the native ODBC driver.
* Type 2 (Native-API partly Java Driver): This driver uses a native client library (specific
to the database) installed on the client machine. It translates JDBC calls into the
database's native API. This offers better performance than Type 1 but is still platform-
dependent.
* Type 3 (Network-Protocol All-Java Driver): This driver uses a middleware application
server that communicates with the database. The JDBC driver communicates with this
server using a database-independent protocol. It's platform-independent but introduces
a network overhead.
* Type 4 (Native-Protocol All-Java Driver): This driver is a pure Java implementation
that directly communicates with the database's network protocol. It offers the best
performance and is platform-independent.
[Diagram illustrating JDBC Driver Types]

+-----------------+ JDBC API Calls +-----------------+ Database-Specific


+-----------------+
| Java Application| ---------------------> | JDBC Driver | ---------------------> | Database
|
+-----------------+ +-----------------+ +-----------------+
^
| (Different types of drivers handle this communication)
|
+-------------+ +-------------+ +-------------+ +-------------+
| Type 1 | --> | ODBC Driver | --> | Database |
| (Bridge) | +-------------+ +-------------+
27

+-------------+
| Type 2 | --> | Native Lib | --> | Database |
| (Native API)| +-------------+ +-------------+
+-------------+
| Type 3 | --> | Middleware | --> | Database |
| (Network) | +-------------+ +-------------+
+-------------+
| Type 4 | --> | Database |
| (Native) | +-------------+
+-------------+

(Imagine a diagram showing the Java application interacting with the JDBC Driver, and
then separate paths for each driver type communicating with the database, possibly
through an ODBC driver, native library, or middleware server.)

b) Write the use of InetAddress class with a suitable Example.


The InetAddress class in Java represents an Internet Protocol (IP) address. It provides
methods to obtain the IP address of a host (machine) given its hostname, or to obtain
the hostname given an IP address. It can handle both IPv4 and IPv6 addresses.
Use Cases:
* Getting the local machine's IP address: Identifying the IP address of the machine the
Java application is running on.
* Resolving hostnames to IP addresses: Looking up the IP address associated with a
domain name (e.g., "www.google.com").
* Getting the hostname from an IP address: Performing reverse DNS lookup to find the
hostname associated with an IP address.
Example:
import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressExample {


public static void main(String[] args) {
try {
// Get the InetAddress object for the local host
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local Host Address: " + localHost.getHostAddress());
System.out.println("Local Host Name: " + localHost.getHostName());

System.out.println("------------------");

// Get the InetAddress object for a given hostname


28

InetAddress googleAddress = InetAddress.getByName("www.google.com");


System.out.println("Google's IP Address: " + googleAddress.getHostAddress());
System.out.println("Google's Host Name: " + googleAddress.getHostName());

System.out.println("------------------");

// Get InetAddress objects for all IP addresses of a hostname


InetAddress[] allGoogleAddresses =
InetAddress.getAllByName("www.google.com");
System.out.println("All IP Addresses for www.google.com:");
for (InetAddress address : allGoogleAddresses) {
System.out.println(address.getHostAddress());
}

System.out.println("------------------");

// Get InetAddress object by IP address (you might need to handle


UnknownHostException)
// Note: getByAddress doesn't do a reverse DNS lookup by default
byte[] ipBytes = {(byte) 192, (byte) 168, 1, 100}; // Example IP
InetAddress byIP = InetAddress.getByAddress(ipBytes);
System.out.println("InetAddress by IP: " + byIP.getHostAddress());
System.out.println("Host Name (may be IP): " + byIP.getHostName()); // May
return the IP if no reverse DNS entry

} catch (UnknownHostException e) {
System.err.println("Error resolving host: " + e.getMessage());
}
}
}

c) Differentiate between JSP and Servlet.


| Feature | JSP (JavaServer Pages) | Servlet |
|---|---|---|
| Primary Focus | Presentation logic (view). HTML-like syntax with Java. | Control logic
(controller). Java code that generates dynamic content. |
| Structure | HTML with embedded Java code (scriptlets, EL, JSTL). | Java code that
outputs HTML using PrintWriter. |
| Ease of Development | Easier for web designers due to HTML-like structure. | More
suited for Java programmers. Presentation logic can be cumbersome. |
29

| Life Cycle | Translated into a servlet, then follows servlet lifecycle. | Managed directly
by the servlet container. |
| Reusability | Encourages separation of presentation and business logic. | Can be used
for various tasks beyond just generating HTML. |
| Configuration | Primarily configured through JSP files and web.xml. | Configured
through servlet mappings in web.xml and annotations. |

d) Write a JDBC program to delete the records of students whose names are starting
with ‘m’ character.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DeleteStudentsStartingWithM {

public static void main(String[] args) {


String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
String password = "your_password";
String tableName = "students"; // Assuming the table name is 'students'

try (Connection connection = DriverManager.getConnection(url, username,


password);
PreparedStatement preparedStatement = connection.prepareStatement(
"DELETE FROM " + tableName + " WHERE name LIKE 'm%'")) {

int rowsAffected = preparedStatement.executeUpdate();

System.out.println(rowsAffected + " student(s) whose name starts with 'm' were


deleted.");

} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}
30

e) Write a JSP program to display all the prime numbers between 1 to n.


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Prime Numbers</title>
</head>
<body>
<h1>Prime Numbers from 1 to <%= request.getParameter("limit") %></h1>
<%
String limitStr = request.getParameter("limit");
if (limitStr != null && !limitStr.isEmpty()) {
int limit = Integer.parseInt(limitStr);
out.println("Prime numbers are: ");
for (int i = 2; i <= limit; i++) {
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
out.print(i + " ");
}
}
} else {
out.println("<p>Please provide a limit in the URL parameter 'limit'.</p>");
}
%>
<br>
<a href="prime_form.html">Enter a new limit</a>
</body>
</html>

You would also need a simple HTML form (e.g., prime_form.html) to get the value of 'n'
from the user:
<!DOCTYPE html>
<html>
<head>
31

<title>Enter Limit</title>
</head>
<body>
<h1>Enter the upper limit to find prime numbers</h1>
<form action="prime_numbers.jsp" method="get">
<label for="limit">Enter limit (n):</label>
<input type="number" id="limit" name="limit"><br><br>
<input type="submit" value="Show Primes">
</form>
</body>
</html>

A) What are the scripting Elements of JSP?


Scripting elements in JSP allow embedding Java code directly within the JSP page. The
main scripting elements are:
* Scriptlets (<% ... %>): Used to embed Java code blocks that are executed on the
server. They can contain any valid Java statements, declarations, etc.
* Expressions (<%= ... %>): Used to directly output the result of a Java expression into
the HTML output. The expression is evaluated, converted to a String, and inserted into
the response.
* Declarations (<%! ... %>): Used to declare instance or static variables and methods
within the JSP page's servlet class. These declarations are outside the service method.

B) What are the steps to connect to the database in Java.


The general steps to connect to a database in Java using JDBC are:
* Load the JDBC Driver: Use Class.forName() to load the specific database driver
class.
* Establish the Connection: Use DriverManager.getConnection() with the database
URL, username, and password to create a Connection object.
* Create a Statement: Create a Statement, PreparedStatement, or CallableStatement
object using the Connection object to execute SQL queries.
* Execute the Query: Use the appropriate method of the statement object (e.g.,
executeQuery() for SELECT, executeUpdate() for INSERT/UPDATE/DELETE) to
interact with the database.
* Process the Results (if any): For SELECT queries, retrieve and process the data from
the ResultSet object.
* Close the Resources: Close the ResultSet, Statement, and Connection objects in a
finally block to release database resources.
32

C) Explain doGet and doPost methods.


doGet() and doPost() are methods in the HttpServlet class that handle HTTP GET and
POST requests, respectively.
* doGet(HttpServletRequest request, HttpServletResponse response): This method is
invoked when the servlet receives an HTTP GET request. GET requests are typically
used to retrieve data from the server. Data is usually appended to the URL in the query
string. doGet() should be implemented to handle read-only operations and should
ideally be idempotent (multiple identical requests should have the same effect as a
single request).
* doPost(HttpServletRequest request, HttpServletResponse response): This method is
invoked when the servlet receives an HTTP POST request. POST requests are typically
used to send data to the server for processing (e.g., submitting forms, uploading files).
Data is sent in the request body. doPost() is generally used for operations that might
modify data on the server and are not necessarily idempotent.
Servlets override these methods to implement the specific logic for handling different
types of client requests.

D) Write a JSP program to calculate the factorial of a given number.


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Factorial Calculator</title>
</head>
<body>
<h1>Factorial Calculator</h1>
<form method="post">
Enter a number: <input type="number" name="number">
<input type="submit" value="Calculate Factorial">
</form>
<%
String numStr = request.getParameter("number");
if (numStr != null && !numStr.isEmpty()) {
int num = Integer.parseInt(numStr);
long factorial = 1;
if (num < 0) {
out.println("<p>Factorial is not defined for negative numbers.</p>");
} else {
33

for (int i = 1; i <= num; i++) {


factorial *= i;
}
out.println("<p>Factorial of " + num + " is: " + factorial + "</p>");
}
}
%>
</body>
</html>

E) Write a Servlet program to display the details of employees in tabular format.


Employee table structure (eno, ename, sal, design)
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/EmployeeDetails")
public class EmployeeDetails extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
String password = "your_password";
34

out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Employee Details</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Employee Details</h1>");
out.println("<table border='1'>");
out.println("<tr><th>Employee
No</th><th>Name</th><th>Salary</th><th>Designation</th></tr>");

Connection connection = null;


Statement statement = null;
ResultSet resultSet = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Replace with your database driver
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
String sql = "SELECT eno, ename, sal, design FROM employee";
resultSet = statement.executeQuery(sql);

while (resultSet.next()) {
int eno = resultSet.getInt("eno");
String ename = resultSet.getString("ename");
double sal = resultSet.getDouble("sal");
String design = resultSet.getString("design");
out.println("<tr><td>" + eno + "</td><td>" + ename + "</td><td>" + sal +
"</td><td>" + design + "</td></tr>");
}

} catch (ClassNotFoundException e) {
out.println("<tr><td colspan='4'>JDBC Driver not found: " + e.getMessage() +
"</td></tr>");
} catch (SQLException e) {
out.println("<tr><td colspan='4'>Database error: " + e.getMessage() +
"</td></tr>");
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
35

if (connection != null) connection.close();


} catch (SQLException e) {
out.println("<tr><td colspan='4'>Error closing resources: " + e.getMessage() +
"</td></tr>");
}
}

out.println("</table>");
out.println("</body>");
out.println("</html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doGet(request, response);
}
}

a) GenericServlet and HttpServlet


* GenericServlet: An abstract class that implements the Servlet interface. It provides a
basic framework for creating servlets without being specific to any particular protocol. It
handles the servlet lifecycle methods (init, service, destroy) in a generic way.
Subclasses need to override the abstract service(ServletRequest, ServletResponse)
method to handle client requests and responses.
* HttpServlet: An abstract subclass of GenericServlet that is specifically designed for
handling HTTP requests. It provides convenience methods for HTTP-specific
operations, such as handling different HTTP methods (GET, POST, HEAD, etc.)
through methods like doGet(), doPost(), doHead(), etc. When extending HttpServlet,
you typically override these doXXX() methods instead of the generic service() method.

b) Cookies
Cookies are small pieces of data that a web server sends to a user's web browser. The
browser may store these cookies and send them back with subsequent requests to the
same server. Cookies are used for various purposes, including:
* Session Management: Maintaining user login status and preferences across multiple
requests.
* Personalization: Remembering user preferences, themes, and other settings.
* Tracking: Monitoring user browsing behavior and website traffic.
36

Cookies have attributes like name, value, domain, path, expiry date, and security flags.
They are managed by the browser based on these attributes.

c) ResultSet Interface
The ResultSet interface in JDBC represents the result set of a database query. It
provides methods to access the data returned by the query, row by row. Key features
include:
* Navigation: Methods like next(), previous(), first(), last(), and absolute(int row) to
move the cursor through the rows of the result set.
* Data Retrieval: getXXX() methods (e.g., getString(), getInt(), getDate()) to retrieve
data from the columns of the current row, using either column index or column name.
* Metadata Access: The getMetaData() method returns a ResultSetMetaData object,
which provides information about the structure of the result set (e.g., column names,
types, counts).
* Updatability (optional): Some ResultSet implementations allow updating the
underlying database table through the result set.

** 2-mark **
a) Write down 2 methods of Connection interface.
* createStatement()
* prepareStatement(String sql)

b) What is sleep() method in multithreading.


The sleep() method in Java pauses the execution of the current thread for a specified
period of time. It's a static method of the Thread class and can throw an
InterruptedException.

c) What is the method to set the thread priority.


The method to set the thread priority in Java is setPriority(int newPriority), which is a
non-static method of the Thread class.

d) Write down 2 classes used in socket programming.


* java.net.Socket (for client-side sockets)
* java.net.ServerSocket (for server-side sockets)

e) What is IP address.
An IP (Internet Protocol) address is a numerical label assigned to each device
connected to a computer network that uses the Internet Protocol for communication. It
serves as an identifier for a specific device on the network.
37

f) What is doGet () method of servlet?


The doGet() method is a method in the HttpServlet class that handles HTTP GET
requests. These requests are typically used to retrieve data from the server, and data is
often passed in the URL.

g) What are the parameters of service() method of servlet.


The service() method of a servlet takes two parameters:
* ServletRequest request: An object containing the client's request information.
* ServletResponse response: An object used to send a response back to the client.
h) What is JSP?
JSP (JavaServer Pages) is a technology that allows developers to create dynamic web
pages using a combination of HTML-like syntax and embedded Java code. JSPs are
translated into servlets by the JSP container.

i) What is Hibernate?
Hibernate is an Object-Relational Mapping (ORM) framework for Java that simplifies the
interaction between Java applications and relational databases by mapping Java
objects to database tables.

j) What is getConnection method?


The getConnection() method is a static method of the DriverManager class in JDBC. It
is used to establish a connection to a database using a provided database URL,
username, and password. It returns a Connection object.

a) What is Statement? Explain the types of Statements in JDBC.


In JDBC, a Statement object is used to execute SQL queries against a database. It
provides a basic way to interact with the database. There are three main types of
Statement objects in JDBC:
* Statement: This is the simplest type. It's used for executing static SQL queries where
parameters are directly embedded in the SQL string. It's susceptible to SQL injection
attacks if user input is directly included.
* PreparedStatement: This type is used for pre-compiled SQL queries that can accept
parameters. The SQL structure is defined once, and then different parameter values
can be set before executing the query multiple times. It offers better performance for
repeated queries and protects against SQL injection.
* CallableStatement: This type is used to execute stored procedures in the database. It
extends PreparedStatement and provides methods for handling IN, OUT, and INOUT
parameters of stored procedures.
38

b) Explain thread life cycle with a diagram.


The life cycle of a thread in Java involves several states:
* New: A thread is in the new state when it has been created but has not yet started.
* Runnable: A thread enters the runnable state after its start() method is invoked. In this
state, the thread is eligible to be run by the thread scheduler. It may be running or ready
to run (waiting for CPU time).
* Running: The thread is currently executing its run() method.
* Blocked: A thread enters the blocked state when it is waiting to acquire a monitor lock
to enter a synchronized block or method.
* Waiting: A thread enters the waiting state when it calls the wait() method of an object.
It will remain in this state until another thread calls notify() or notifyAll() on the same
object, or the waiting thread is interrupted.
* Timed Waiting: A thread enters the timed waiting state when it calls a method with a
timeout parameter, such as sleep(), wait(long timeout), join(long timeout), or
park(Object blocker, long timeout). The thread will remain in this state until the timeout
expires or the specific event occurs (e.g., notification, joining thread finishes).
* Terminated: A thread enters the terminated (or dead) state when its run() method
completes, either normally or by throwing an uncaught exception. Once terminated, a
thread cannot be restarted.
[Diagram of Thread Life Cycle]

+-------+ start() +----------+ Scheduler +---------+ synchronized block/wait()


+----------+
| New | ----------------> | Runnable | <-----------------> | Running |
-----------------------------------> | Blocked |
+-------+ +----------+ +---------+ +----------+
^ |
| notify()/notifyAll() |
| v
+----------------------------------------------+
^ |
| wait(timeout)/sleep()/join(timeout) |
| v
+----------+
| Timed |
| Waiting |
+----------+
^ |
| interrupt() |
| v
39

+----------+ run() completes +-----------+


| Waiting | ------------------------> | Terminated|
+----------+ +-----------+

(Imagine a flowchart depicting the states and transitions as described above.)

c) What are the implicit objects in JSP? Explain any 4.


Implicit objects in JSP are pre-defined variables that are automatically available to the
developer within JSP pages without explicit declaration. Here are four common implicit
objects:
* request (javax.servlet.http.HttpServletRequest): Represents the client's request to the
server. It provides access to request parameters, headers, attributes, and other request-
related information. For example, request.getParameter("username") retrieves the value
of the "username" parameter from the request.
* response (javax.servlet.http.HttpServletResponse): Represents the server's response
to the client. It allows setting response headers, content type, cookies, and sending
output back to the browser. For example, response.setContentType("text/html") sets the
content type of the response to HTML.
* session (javax.servlet.http.HttpSession): Represents the HTTP session associated
with the client. It allows storing and retrieving user-specific data across multiple
requests from the same client during a session. For example,
session.setAttribute("userId", 123) stores the user ID in the session.
* application (javax.servlet.ServletContext): Represents the web application context. It
provides access to application-level resources, attributes shared by all users and
servlets in the application, and information about the web application environment. For
example, application.getRealPath("/images/logo.png") gets the absolute file path on the
server for the logo image.
d) Write down the difference between doGet() and doPost() method.
| Feature | doGet() | doPost()

D) Write down the difference between doGet() and doPost() method.


| Feature | doGet() | doPost() |
|---|---|---|
| Purpose | Primarily used to retrieve data from the server. | Primarily used to send data
to the server for processing (e.g., form submission). |
| Data Transmission | Data is usually appended to the URL in the query string. | Data is
sent in the request body. |
| Security | Less secure for sensitive data as it's visible in the URL. | More secure for
sensitive data as it's not directly visible in the URL. |
| Data Length | Limited by the maximum URL length. | No practical limit on data length. |
40

| Idempotency | Should ideally be idempotent (multiple identical requests have the same
effect as one). | Not necessarily idempotent (multiple identical requests might have
different effects). |
| Caching | Responses can be cached by browsers and proxies. | Responses are
typically not cached. |
| Bookmarks/History | Can be bookmarked and are part of the browser history. | Cannot
be directly bookmarked and are usually not part of the browser history.

e) Write a Java program to count the number of records in a table.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CountRecords {

public static void main(String[] args) {


String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
String password = "your_password";
String tableName = "your_table_name";

Connection connection = null;


Statement statement = null;
ResultSet resultSet = null;

try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver"); // Replace with your database driver

// Establish the connection


connection = DriverManager.getConnection(url, username, password);

// Create a statement
statement = connection.createStatement();

// Execute the query to count records


41

String sql = "SELECT COUNT(*) FROM " + tableName;


resultSet = statement.executeQuery(sql);

// Retrieve the count


if (resultSet.next()) {
int count = resultSet.getInt(1);
System.out.println("Number of records in table '" + tableName + "': " + count);
} else {
System.out.println("Could not retrieve the record count.");
}

} catch (ClassNotFoundException e) {
System.err.println("JDBC driver not found: " + e.getMessage());
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
} finally {
// Close resources in reverse order of creation
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}

Here are the answers to your questions:


A) Explain Architecture of Hibernate.
The architecture of Hibernate, an Object-Relational Mapping (ORM) framework for
Java, comprises several key components that work together to manage the persistence
of Java objects to a relational database:
* Configuration: This object is responsible for reading Hibernate configuration metadata
from a configuration file (e.g., hibernate.cfg.xml) or programmatically. It contains
information about database connection details, mappings between Java classes and
database tables, and other Hibernate settings. A single Configuration object is typically
created during application startup.
* SessionFactory: The SessionFactory is a factory for Session objects. It is a
heavyweight, thread-safe object created once during application initialization based on
42

the Configuration. It caches compiled mapping metadata and JDBC connection pools.
Multiple threads can concurrently access the SessionFactory.
* Session: The Session is a lightweight, non-thread-safe object representing a single
unit of work with the database. It provides methods for persisting, retrieving, updating,
and deleting Java objects. A new Session is opened for each transaction or unit of work
and closed afterward.
* Transaction: The Transaction interface represents a unit of work with the database.
Hibernate transactions are typically managed using the Transaction object obtained
from the Session. It supports starting, committing, and rolling back transactions.
* Query: The Query interface is used to execute HQL (Hibernate Query Language)
queries against the database. HQL is an object-oriented query language.
* Criteria: The Criteria API provides a programmatic way to build queries using Java
objects and criteria instead of writing HQL strings.
* Native SQL: Hibernate allows executing native SQL queries directly through the
Session for database-specific features.
* Interceptor: The Interceptor interface allows you to intercept Hibernate events (e.g.,
before saving, after loading) and implement custom logic.
* Mapping Metadata: This defines how Java classes are mapped to database tables,
specified through XML files or annotations.
Interaction Flow: The application uses the Configuration to build the SessionFactory.
For each database operation, a Session is obtained. Transactions are managed through
the Session. Data is persisted and retrieved using the Session and queries (HQL,
Criteria, or Native SQL).
B) What is ResultSet interface in JDBC? Explain methods in ResultSet interface.
The ResultSet interface in JDBC represents the result set of a database query. It
provides methods to access the data returned by the query, row by row. The cursor
initially points before the first row.
Key Methods in ResultSet Interface:
* Navigation:
* next(): Moves the cursor forward one row. Returns true if there is a next row, false
otherwise.
* previous(): Moves the cursor backward one row. Returns true if there is a previous
row, false otherwise (some drivers may not fully support this).
* first(): Moves the cursor to the first row. Returns true if the cursor is on a valid row,
false otherwise.
* last(): Moves the cursor to the last row. Returns true if the cursor is on a valid row,
false otherwise (some drivers may require fetching all rows).
* absolute(int row): Moves the cursor to the specified row number. Returns true if the
cursor is on a valid row, false otherwise.
* relative(int rows): Moves the cursor a relative number of rows (positive for forward,
negative for backward). Returns true if the cursor is on a valid row, false otherwise.
43

* beforeFirst(): Moves the cursor to the position immediately before the first row.
* afterLast(): Moves the cursor to the position immediately after the last row.
* getRow(): Returns the current row number.
* Data Retrieval:
* getString(int columnIndex) / getString(String columnLabel): Retrieves the value of
the specified column as a String.
* getInt(int columnIndex) / getInt(String columnLabel): Retrieves the value of the
specified column as an int.
* getDouble(int columnIndex) / getDouble(String columnLabel): Retrieves the value of
the specified column as a double.
* getBoolean(int columnIndex) / getBoolean(String columnLabel): Retrieves the value
of the specified column as a boolean.
* getDate(int columnIndex) / getDate(String columnLabel): Retrieves the value of the
specified column as a java.sql.Date.
* getTime(int columnIndex) / getTime(String columnLabel): Retrieves the value of the
specified column as a java.sql.Time.
* getTimestamp(int columnIndex) / getTimestamp(String columnLabel): Retrieves the
value of the specified column as a java.sql.Timestamp.
* getObject(int columnIndex) / getObject(String columnLabel): Retrieves the value of
the specified column as a generic Object.
* Metadata:
* getMetaData(): Returns a ResultSetMetaData object that contains information about
the columns in the ResultSet.
* Closing:
* close(): Immediately releases the database resources held by this ResultSet object.

C) Explain JSP life cycle with diagram.


The life cycle of a JSP (JavaServer Pages) is managed by the JSP container (part of
the web server). When a client requests a JSP page for the first time (or when it's
modified), the container goes through the following phases:
* Translation: The JSP container translates the JSP page into a Java servlet source
code. This involves converting HTML tags, JSP directives, scripting elements, and
actions into Java code.
* Compilation: The generated servlet source code is then compiled into a servlet class
(.class file) by the Java compiler.
* Class Loading: The JSP container loads the generated servlet class into the JVM.
* Instantiation: The container creates an instance of the servlet class. This happens
only once during the servlet's lifetime.
* Initialization: The jspInit() method (analogous to the servlet's init()) is called once by
the container. This is where the JSP can perform one-time setup tasks.
44

* Request Handling: For each client request to the JSP, the container calls the
_jspService() method of the generated servlet. This method handles the request,
processes the JSP logic, interacts with Java beans or other resources, and generates
the dynamic content in the response.
* Destruction: When the JSP is about to be removed from service (e.g., during server
shutdown or application redeployment), the jspDestroy() method (analogous to the
servlet's destroy()) is called once. This allows the JSP to perform cleanup tasks.
[Diagram of JSP Life Cycle]

+---------------------+ First Request / Modification +-----------------------+


| Client Requests JSP | -------------------------------------> | JSP Container Receives |
+---------------------+ +-----------------------+
| |
v v
+---------------------+ +-----------------------+
| Web Server Forwards | | JSP Translation |
| Request | | (JSP -> Servlet Source)|
+---------------------+ +-----------------------+
|
v
+-----------------------+
| Servlet Compilation |
| (.java -> .class) |
+-----------------------+
|
v
+-----------------------+
| Class Loading |
+-----------------------+
|
v
+-----------------------+
| Instantiation |
| (Servlet Object) |
+-----------------------+
|
v (Once)
+-----------------------+
| Initialization |
| (jspInit() called) |
+-----------------------+
45

|
v (Multiple Requests)
+-----------------------+
| Request Handling |
| (_jspService() called)|
+-----------------------+
|
v
+-----------------------+
| Response Generation |
+-----------------------+
|
v
+---------------------+ +-----------------------+
| Response to Client | <-------------------------------------- | JSP Container Sends |
+---------------------+ +-----------------------+
|
v (Once before removal)
+-----------------------+
| Destruction |
| (jspDestroy() called) |
+-----------------------+

D) Write a Java program to print from 100 to 1 (use sleep() method).


public class PrintReverse {
public static void main(String[] args) {
for (int i = 100; i >= 1; i--) {
System.out.println(i);
try {
Thread.sleep(100); // Pause for 100 milliseconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Re-interrupt the current thread
}
}
System.out.println("Printing complete.");
}
}

E) Write a Java program to create table student with attributes Rno, Sname, Per.
import java.sql.Connection;
46

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class CreateStudentTable {


public static void main(String[] args) {
String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
String password = "your_password";

try (Connection connection = DriverManager.getConnection(url, username,


password);
Statement statement = connection.createStatement()) {

String createTableSQL = "CREATE TABLE student (" +


"Rno INT PRIMARY KEY, " +
"Sname VARCHAR(255), " +
"Per DOUBLE)";

statement.executeUpdate(createTableSQL);
System.out.println("Table 'student' created successfully.");

} catch (SQLException e) {
System.err.println("Error creating table: " + e.getMessage());
}
}
}

A) What are the states of an object in Hibernate?


In Hibernate, an entity (persistent object) can be in one of the following states:
* Transient: The object is newly created and not associated with any Hibernate
Session. It's not yet persistent and its data is not stored in the database.
* Persistent: The object is associated with a Hibernate Session. Its data is stored in the
database, and any changes to the object will be automatically synchronized with the
database during the transaction commit or flush operation.
* Detached: The object was previously persistent but is no longer associated with any
Session. Its data might still be in the database, but changes to the detached object will
47

not be automatically synchronized. To make it persistent again, it needs to be re-


attached to a Session.

B) What is session tracking? What are the different ways of session tracking in servlet?
Session tracking is the process of maintaining state information about a user across
multiple requests. Since HTTP is a stateless protocol, servlets use session tracking to
identify and maintain continuity with a particular user. The different ways of session
tracking in servlets are:
* Cookies: The server sends small text files (cookies) to the client's browser, which
stores them. The browser sends these cookies back to the server with subsequent
requests. Servlets can use cookies to store session IDs or other user-specific data.
* URL Rewriting: The session ID is appended to the URL as a parameter. This is used
when cookies are disabled in the browser.
* Hidden Form Fields: The session ID is included as a hidden field in HTML forms.
When the form is submitted, the session ID is sent back to the server.
* HttpSession API: Servlets provide the HttpSession API for managing sessions. The
server automatically creates a session object for each client and assigns a unique
session ID. The session ID is usually stored in a cookie, but URL rewriting or hidden
form fields can be used as fallback mechanisms.

C) What is thread Priority? How to set the thread priorities?


Thread priority is a mechanism that allows the operating system's thread scheduler to
determine the order in which threads are given preference for execution. Each thread is
assigned a priority level, represented by an integer value. Higher priority threads are
generally given preference over lower priority threads.
In Java, thread priorities are integers in the range of 1 (lowest) to 10 (highest). The
Thread class defines constants for common priority levels: Thread.MIN_PRIORITY (1),
Thread.NORM_PRIORITY (5), and Thread.MAX_PRIORITY (10).
To set the priority of a thread, use the setPriority(int newPriority) method of the Thread
class. The newPriority argument must be within the valid range (1 to 10).

D) Write a JSP application to accept a user name and greet the user.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Greeting App</title>
</head>
48

<body>
<h1>Welcome to my website!</h1>
<form method="post">
Enter your name: <input type="text" name="userName">
<input type="submit" value="Greet me!">
</form>
<%
String name = request.getParameter("userName");
if (name != null && !name.isEmpty()) {
out.println("<p>Hello, " + name + "!</p>");
}
%>
</body>
</html>

E) Write a Java program to display the IP address of a machine.


import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIPAddress {


public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("IP Address of this machine: " + localHost.getHostAddress());
} catch (UnknownHostException e) {
System.err.println("Could not get the IP address: " + e.getMessage());
}
}
}

a) Connection Interface
In JDBC, the Connection interface represents a session with a specific database. It's
obtained from the DriverManager and is the primary interface for interacting with the
database. It provides methods to create Statement objects, manage transactions
(commit, rollback, auto-commit), and get database metadata. A Connection object
should be closed after use to release database resources.

b) Runnable Interface
49

The Runnable interface in Java is a functional interface that defines a single method,
run(). Any class that implements Runnable can have its run() method executed by a
thread. This is a common way to define a task to be performed concurrently without
extending the Thread class, promoting better design by separating the task from the
thread management. A Thread object is then created with an instance of the Runnable
implementation.

c) Thread Synchronization
Thread synchronization is a mechanism to control the access of multiple threads to
shared resources, preventing race conditions and ensuring data consistency in
concurrent programming. Java provides several synchronization mechanisms, including
the synchronized keyword (for methods and blocks) and the java.util.concurrent
package (offering more advanced utilities like locks, semaphores, and concurrent
collections). Proper synchronization is crucial for building reliable and predictable
multithreaded applications.

a) What is the use of cookies?


Cookies are small pieces of data stored by a web browser on a user's computer. They
are used by web servers to remember information about the user, such as login status,
preferences, and browsing activity, across multiple requests.

b) What is the use of Runnable interface?


The Runnable interface in Java is used to define a task that can be executed by a
thread. Implementing Runnable allows a class to have its run() method executed
concurrently without subclassing the Thread class, promoting better design by
separating the task from thread management.

c) Explain thread priority.


Thread priority is a mechanism in Java that allows the operating system's thread
scheduler to determine the order in which threads receive CPU time. Threads with
higher priority are generally given preference over threads with lower priority, but it's not
a guarantee of execution.

d) What is the use of HQL?


HQL (Hibernate Query Language) is an object-oriented query language used in
Hibernate to query persistent entities. It allows developers to write queries against Java
objects and their properties, which Hibernate then translates into the appropriate SQL
for the underlying database.

e) What are the directives in JSP?


50

Directives in JSP provide instructions to the JSP container regarding the processing of
the JSP page. Common directives include:
* <%@ page ... %>: Defines page-specific attributes.
* <%@ include ... %>: Includes external files during translation.
* <%@ taglib ... %>: Declares tag libraries for using custom tags.

f) What is networking?
Networking refers to the interconnection of two or more computing devices to enable
them to communicate and share resources, such as data, files, and peripherals.
g) Write the method for creating connection?

The primary method for creating a database connection in Java using JDBC is
DriverManager.getConnection(String url, String username, String password).

h) What is the yield ( ) method?


The yield() method in Java is a static method of the Thread class that suggests to the
thread scheduler that the current thread is willing to relinquish its current use of a
processor. The scheduler may choose to ignore this suggestion.

i) What is the use of socket class?


The Socket class in Java is used to establish a connection between two applications
across a network. It represents one end of a network connection (the client end) and
allows for sending and receiving data.

j) What is servlet?
A servlet is a Java programming language class used to extend the capabilities of
servers that host applications accessed by means of a request-response programming
model, most commonly used to handle web requests and generate dynamic content.

a) Explain in detail directives in JSP.


JSP directives provide global instructions to the JSP container about how to process the
entire JSP page. They are defined using the <%@ ... %> syntax. There are three main
types of directives:
* page Directive: This directive defines page-specific attributes and settings. Common
attributes include:
* language: Specifies the scripting language used in the JSP page (default is java).
<%@ page language="java" %>
51

* contentType: Sets the MIME type and character encoding of the response sent to
the client (default is text/html; charset=ISO-8859-1).
<%@ page contentType="text/html; charset=UTF-8" %>

* import: Imports Java classes and packages, making them available for use in the
JSP page. Multiple import attributes can be used.
<%@ page import="java.util.*, java.sql.*" %>

* session: Specifies whether the JSP page participates in HTTP sessions (true or
false, default is true).
<%@ page session="false" %>

* buffer: Sets the buffering behavior for the output stream (none, 8kb, or a specific
size).
<%@ page buffer="16kb" %>

* autoFlush: Controls whether the buffer should be automatically flushed when it's full
(true, default) or if an exception should be thrown (false).
<%@ page autoFlush="true" %>

* isThreadSafe: Indicates whether the JSP page can handle multiple requests
concurrently (true, default) or needs to be synchronized (false).
<%@ page isThreadSafe="false" %>

* info: A string that provides a description of the JSP page.


<%@ page info="This is a greeting page" %>

* errorPage: Specifies the path to another JSP page that should be displayed if an
uncaught exception occurs in the current page.
<%@ page errorPage="error.jsp" %>

* isErrorPage: Declares the current JSP page as an error page (true or false, default
is false). If true, the exception implicit object is available.
<%@ page isErrorPage="true" %>

* extends: Specifies a superclass that the generated servlet will extend.


<%@ page extends="com.example.MyBaseServlet" %>

* include Directive: This directive includes the content of an external file (static or
dynamic) into the current JSP page during the translation phase.
* file: Specifies the relative or absolute path to the file to be included.
52

<%@ include file="header.jsp" %>

The included file's content is directly inserted into the JSP page before it's compiled
into a servlet. Changes in the included file are not reflected until the main JSP page is
re-translated and re-compiled.
* taglib Directive: This directive declares a tag library, making its custom actions
available for use in the JSP page.
* uri: Specifies a unique URI (Uniform Resource Identifier) that identifies the tag
library.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

* prefix: Specifies a prefix that will be used to identify the custom actions from the tag
library in the JSP page.
The tag library descriptor (.tld file) associated with the URI defines the custom tags
and their attributes.

b) Explain inter-thread communication with an example.


Inter-thread communication (ITC) is the mechanism by which threads running
concurrently in the same process can exchange information and synchronize their
actions. Java provides several ways for threads to communicate, with the most
fundamental being the use of wait(), notify(), and notifyAll() methods of the Object class.
These methods must be called from within a synchronized block or method that holds
the lock on the object the methods are invoked upon.
Example: Consider a producer-consumer scenario where one thread (producer) creates
data and another thread (consumer) processes it. They share a buffer.
import java.util.LinkedList;
import java.util.Queue;

class SharedBuffer {
private Queue<Integer> buffer = new LinkedList<>();
private int capacity = 5;

public synchronized void produce(int item) throws InterruptedException {


while (buffer.size() == capacity) {
wait(); // Wait if buffer is full
}
buffer.offer(item);
System.out.println("Produced: " + item);
notifyAll(); // Notify waiting consumers
}
53

public synchronized int consume() throws InterruptedException {


while (buffer.isEmpty()) {
wait(); // Wait if buffer is empty
}
int item = buffer.poll();
System.out.println("Consumed: " + item);
notifyAll(); // Notify waiting producers
return item;
}
}

class Producer implements Runnable {


private SharedBuffer buffer;

public Producer(SharedBuffer buffer) {


this.buffer = buffer;
}

@Override
public void run() {
for (int i = 1; i <= 10; i++) {
try {
buffer.produce(i);
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

class Consumer implements Runnable {


private SharedBuffer buffer;

public Consumer(SharedBuffer buffer) {


this.buffer = buffer;
}

@Override
public void run() {
54

for (int i = 0; i < 10; i++) {


try {
buffer.consume();
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

public class ProducerConsumerExample {


public static void main(String[] args) {
SharedBuffer buffer = new SharedBuffer();
Thread producerThread = new Thread(new Producer(buffer));
Thread consumerThread = new Thread(new Consumer(buffer));

producerThread.start();
consumerThread.start();
}
}

c) Differentiate between Statement and PreparedStatement interface.


| Feature | Statement | PreparedStatement |
|---|---|---|
| SQL Execution | Executes static SQL queries directly. | Executes pre-compiled SQL
queries. |
| Parameter Handling | Parameters are embedded directly into the SQL string, often
through concatenation. | Parameters are passed separately using placeholders (?) and
setter methods. |
| Security | Vulnerable to SQL injection attacks if user input is directly embedded. |
Protects against SQL injection as parameters are treated as data, not executable code.
|
| Performance | Less efficient for repeated execution of similar queries with different
data as the SQL needs to be parsed and compiled each time. | More efficient for
repeated execution as the SQL is parsed and compiled only once. |
| Code Clarity | Can lead to less readable and maintainable code when dealing with
dynamic queries. | Generally leads to more readable and maintainable code for dynamic
queries. |
55

| Database Optimization | Limited potential for database-level query optimization for


dynamic queries. | Allows the database to optimize the query execution plan for
repeated executions. |
| Syntax | String sql = "INSERT INTO users VALUES ('" + username + "', '" + password
+ "')"; | String sql = "INSERT INTO users VALUES (?, ?)";
preparedStatement.setString(1, username); preparedStatement.setString(2, password);
|
d) Explain the life cycle of a thread.
The life cycle of a thread in Java involves several distinct states:
* New: A thread is in the new state when a Thread object has been created, but the
start() method has not yet been invoked. At this point, the thread has not begun
execution.
* Runnable: Once the start() method is called, the thread transitions to the runnable
state. This means the thread is eligible to be executed by the thread scheduler. The
thread might be running or it might be ready to run (waiting for its turn to get CPU time).
* Running: The thread is currently executing its run() method, performing the tasks it
was designed to do.
* Blocked: A thread enters the blocked state when it tries to acquire a monitor lock on
an object that is currently held by another thread. The thread will remain blocked until
the lock is released. This typically occurs when entering a synchronized block or
method.
* Waiting: A thread enters the waiting state when it calls the wait() method of an object.
The thread releases the monitor lock and will remain in this state until another thread
calls the notify() or notifyAll() method on the same object, or the waiting thread is
interrupted.
* Timed Waiting: A thread enters the timed waiting state when it calls a method with a
timeout parameter, such as sleep(long), wait(long), join(long), or park(Object, long). The
thread will remain in this state for a specified amount of time or until the event that
would wake it up occurs (e.g., notification, joining thread finishes).
* Terminated: A thread enters the terminated (or dead) state when its run() method
completes, either normally (by reaching the end of the method) or by throwing an
uncaught exception. Once a thread has terminated, it cannot be restarted.

e) Explain methods of ServerSocket class with syntax.


The ServerSocket class in Java (from the java.net package) provides a mechanism for
server applications to listen for incoming connection requests from client applications
over a network using TCP. Here are some key methods of the ServerSocket class:
* ServerSocket(int port): Constructor that creates a ServerSocket bound to a specific
port number. The server will listen for incoming connections on this port.
import java.io.IOException;
import java.net.ServerSocket;
56

public class SimpleServer {


public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server started on port " + port);
// ... rest of the server logic (accepting connections) ...
} catch (IOException e) {
e.printStackTrace();
}
}
}

* accept(): Listens for an incoming connection and blocks until a client attempts to
connect. When a connection is established, it returns a new Socket object representing
the connection to the client. This Socket is used for communication with that specific
client.
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " +
clientSocket.getInetAddress().getHostAddress());
// Now you can use clientSocket to send and receive data from the client

* close(): Closes the ServerSocket, releasing the port it was listening on. Any further
attempts to accept connections on this ServerSocket will result in an IOException. It's
important to close the ServerSocket when it's no longer needed to free up system
resources.
serverSocket.close();
System.out.println("Server socket closed.");

* getLocalPort(): Returns the port number on which the ServerSocket is listening.


int listeningPort = serverSocket.getLocalPort();
System.out.println("Server is listening on port: " + listeningPort);

* getInetAddress(): Returns the local IP address to which the ServerSocket is bound. If


the server socket was created with port 0, this will return the wildcard address (0.0.0.0
or ::0 for IPv6).
java.net.InetAddress serverAddress = serverSocket.getInetAddress();
System.out.println("Server address: " + serverAddress.getHostAddress());
57

* setSoTimeout(int timeout): Sets the timeout in milliseconds for the accept() method. If
a client connection is not established within the specified timeout period, an
java.net.SocketTimeoutException is thrown. A timeout of zero means infinite timeout.
serverSocket.setSoTimeout(5000); // Set timeout to 5 seconds
try {
Socket clientSocket = serverSocket.accept();
// ...
} catch (java.net.SocketTimeoutException e) {
System.err.println("Accept timeout occurred.");
} catch (IOException e) {
e.printStackTrace();
}

These methods provide the fundamental functionality for a server to listen for and
accept connections from clients, forming the basis of network communication in Java.

A) What is the difference between execute(), executeQuery(), and executeUpdate()?


These are methods of the Statement interface in JDBC used to execute SQL
statements:
* executeQuery(String sql): This method is used to execute SQL SELECT statements
that return a single ResultSet object. If the executed SQL statement is not a SELECT
statement, or if it returns anything other than a single ResultSet, it will typically throw an
SQLException.
* executeUpdate(String sql): This method is used to execute SQL INSERT, UPDATE,
DELETE, and DDL (Data Definition Language) statements (like CREATE TABLE,
DROP TABLE). It returns an integer representing the number of rows affected by the
operation. For DDL statements, the return value might be 0 or unspecified by some
JDBC drivers. It does not return a ResultSet.
* execute(String sql): This is a more general-purpose method that can execute any type
of SQL statement. It returns a boolean value: true if the first result is a ResultSet object,
or false if it is an update count or no result. You would then need to use getResultSet(),
getUpdateCount(), and getMoreResults() to determine the actual type and content of
the result. It's less commonly used for simple queries and updates compared to
executeQuery() and executeUpdate().

B) Explain the architecture of Hibernate.


The architecture of Hibernate, an Object-Relational Mapping (ORM) framework for
Java, comprises the following key components:
58

* Configuration: Reads configuration metadata (database connection, mappings) from


hibernate.cfg.xml or programmatically. Creates the SessionFactory.
* SessionFactory: A thread-safe, heavyweight object created once per application. It's a
factory for Session objects and caches metadata.
* Session: A non-thread-safe, lightweight object representing a unit of work with the
database. Provides methods for CRUD operations and executing queries.
* Transaction: Manages database transactions (start, commit, rollback).
* Query: Executes HQL (Hibernate Query Language) queries.
* Criteria: Provides a programmatic way to build queries.
* Native SQL: Allows executing database-specific SQL queries.
* Interceptor: Enables interception of Hibernate events for custom logic.
* Mapping Metadata: Defines the mapping between Java classes and database tables
(XML or annotations).
Interaction: The application uses Configuration to build SessionFactory. For each
database operation, a Session is obtained, and transactions are managed. Data is
persisted and retrieved through the Session using various query mechanisms.

C) Explain methods of Socket class with example.


The Socket class in Java (java.net.Socket) represents a client-side socket, used to
establish a connection to a server. Here are some key methods with examples:
* Socket(String host, int port): Constructor to create a socket and connect to the
specified host and port.
import java.net.Socket;
import java.io.IOException;

public class Client {


public static void main(String[] args) {
String host = "localhost";
int port = 12345;
try (Socket socket = new Socket(host, port)) {
System.out.println("Connected to server at " + socket.getInetAddress() + ":" +
socket.getPort());
// ... communication logic ...
} catch (IOException e) {
e.printStackTrace();
}
}
}

* getInputStream(): Returns an InputStream to read data from the server.


59

java.io.InputStream inputStream = socket.getInputStream();


java.io.BufferedReader reader = new java.io.BufferedReader(new
java.io.InputStreamReader(inputStream));
String messageFromServer = reader.readLine();
System.out.println("Server says: " + messageFromServer);

* getOutputStream(): Returns an OutputStream to send data to the server.


java.io.OutputStream outputStream = socket.getOutputStream();
java.io.PrintWriter writer = new java.io.PrintWriter(outputStream, true);
String messageToServer = "Hello from client!";
writer.println(messageToServer);

* close(): Closes the socket, terminating the connection.


socket.close();
System.out.println("Connection closed.");

* getInetAddress(): Returns the IP address of the remote host to which the socket is
connected.
java.net.InetAddress serverAddress = socket.getInetAddress();
System.out.println("Connected to IP: " + serverAddress.getHostAddress());

* getPort(): Returns the port number on the remote host to which the socket is
connected.
int serverPort = socket.getPort();
System.out.println("Connected to port: " + serverPort);

D) Write a JSP program to accept Name & age of voter and check whether he/she is
eligible for voting or not.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Voter Eligibility Checker</title>
</head>
<body>
<h1>Voter Eligibility Checker</h1>
<form method="post">
Enter your Name: <input type="text" name="voterName"><br><br>
Enter your Age: <input type="number" name="voterAge"><br><br>
<input type="submit" value="Check Eligibility">
60

</form>
<%
String name = request.getParameter("voterName");
String ageStr = request.getParameter("voterAge");

if (name != null && !name.isEmpty() && ageStr != null && !ageStr.isEmpty()) {


int age = Integer.parseInt(ageStr);
out.println("<p>Name: " + name + "</p>");
out.println("<p>Age: " + age + "</p>");
if (age >= 18) {
out.println("<p><font color='green'>You are eligible for voting!</font></p>");
} else {
out.println("<p><font color='red'>You are not eligible for voting.</font></p>");
}
}
%>
</body>
</html>

E) Write a JDBC program to delete the records of employees whose names are starting
with ‘A’ character.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DeleteEmployeesStartingWithA {

public static void main(String[] args) {


String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
String password = "your_password";
String tableName = "employees"; // Assuming the table name is 'employees'

try (Connection connection = DriverManager.getConnection(url, username,


password);
PreparedStatement preparedStatement = connection.prepareStatement(
"DELETE FROM " + tableName + " WHERE ename LIKE 'A%'")) {
61

int rowsAffected = preparedStatement.executeUpdate();

System.out.println(rowsAffected + " employee(s) whose name starts with 'A'


were deleted.");

} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}

A) Write advantages and disadvantages of Spring.


Advantages of Spring:
* Dependency Injection (DI): Promotes loose coupling and makes applications more
testable and maintainable by managing object dependencies.
* Aspect-Oriented Programming (AOP): Allows applying cross-cutting concerns (like
logging, security) in a modular way, reducing code duplication.
* Comprehensive Framework: Offers a wide range of modules for various aspects of
application development (web, data access, messaging, etc.).
* Transaction Management: Provides a consistent abstraction for managing
transactions across different data access technologies.
* Testing Support: Makes unit and integration testing easier with its DI and mock object
support.
* Large and Active Community: Benefit from extensive documentation, tutorials, and a
large community for support.
* Integration Capabilities: Seamlessly integrates with other Java EE technologies and
third-party libraries.
* Spring Boot: Simplifies the setup and configuration of Spring applications, enabling
rapid development.
Disadvantages of Spring:
* Complexity: The sheer size and number of features can be overwhelming for
beginners.
* Learning Curve: Understanding the various modules and concepts requires a
significant learning effort.
* Configuration Overhead (Traditional XML): Older Spring projects relied heavily on
XML configuration, which could become verbose and difficult to manage (though Spring
Boot largely mitigates this).
62

* Performance Overhead (Potentially): While generally performant, the extensive use of


reflection and dynamic proxies can introduce a slight performance overhead compared
to simpler frameworks.
* "Magic" Feeling: The automatic wiring and configuration can sometimes make it
harder to understand what's happening under the hood.

B) Explain JSP tags with example.


JSP tags are XML-like elements used within JSP pages to perform various actions and
control the flow of the page. They enhance the presentation layer by separating Java
code from the HTML structure. There are several categories of JSP tags:
* Directives: Provide instructions to the JSP container (e.g., <%@ page ... %>, <%@
include ... %>, <%@ taglib ... %>). (Covered in a previous answer).
* Scripting Elements: Allow embedding Java code directly into the JSP page (e.g., <
% ... %> scriptlets, <%= ... %> expressions, <%! ... %> declarations). (Covered in a
previous answer).
* Implicit Objects: Pre-defined variables available within JSP pages (e.g., request,
response, session, application, out, page, pageContext, config, exception). (Covered in
a previous answer).
* Actions: Standard JSP tags that perform specific actions. Some common standard
actions include:
* <jsp:include page="url" flush="true|false" />: Includes the content of another
resource (JSP, HTML, servlet) at runtime.
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head><title>Main Page</title></head>
<body>
<h1>Welcome to the Main Page</h1>
<jsp:include page="header.jsp" flush="true" />
<p>This is the main content.</p>
<jsp:include page="footer.jsp" flush="true" />
</body>
</html>

* <jsp:forward page="url" />: Forwards the request to another resource without the
client being aware.
<jsp:forward page="process_data.jsp" />

* <jsp:useBean id="beanName" class="package.ClassName" scope="page|request|


session|application" />: Declares or locates a JavaBean component.
<jsp:useBean id="myUser" class="com.example.User" scope="session" />
63

<p>Welcome, <jsp:getProperty name="myUser" property="username" /></p>

* <jsp:setProperty name="beanName" property="propertyName" value="value" /> /


<jsp:setProperty name="beanName" property="*" />: Sets properties of a JavaBean.
<jsp:setProperty name="myUser" property="username" param="usernameInput" />

* <jsp:getProperty name="beanName" property="propertyName" />: Retrieves and


outputs a property of a JavaBean.
<p>Email: <jsp:getProperty name="myUser" property="email" /></p>

* Custom Tags: Reusable components created using tag libraries, extending the
standard JSP actions. They provide a cleaner way to implement complex logic in the
presentation layer. (Declared using the <%@ taglib ... %> directive).

C) What are the advantages and disadvantages of multithreading?


Advantages of Multithreading:
* Improved Responsiveness: Applications can remain responsive even when
performing long-running tasks in the background.
* Increased Performance: On multi-core processors, multiple threads can execute in
parallel, potentially reducing the overall execution time.
* Better Resource Utilization: Threads within the same process share resources,
leading to more efficient use of system resources compared to multiple processes.
* Simplified Program Structure (for certain tasks): Can lead to more modular and
easier-to-manage code by separating concerns into different threads.
Disadvantages of Multithreading:
* Complexity: Designing, debugging, and managing multithreaded applications can be
significantly more complex than single-threaded ones.
* Synchronization Issues: Requires careful synchronization to prevent race conditions,
deadlocks, and other concurrency problems.
* Overhead: Creating and managing threads introduces some overhead in terms of
memory and CPU time. Excessive thread creation can degrade performance.
* Context Switching: The operating system needs to switch between running threads,
which can introduce performance overhead.
* Testing Difficulty: Multithreaded applications can be harder to test due to the non-
deterministic nature of thread execution.

D) Write a servlet program to accept two numbers from the user and print the addition of
that in blue color.
import java.io.IOException;
import java.io.PrintWriter;
64

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/AdditionServlet")
public class AdditionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;

out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Addition Result</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Addition Result</h1>");
out.println("<p style=\"color:blue;\">The sum of " + num1 + " and " + num2 + " is:
" + sum + "</p>");
out.println("</body>");
out.println("</html>");

} catch (NumberFormatException e) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Error</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Error</h1>");
65

out.println("<p style=\"color:red;\">Invalid input. Please enter valid


numbers.</p>");
out.println("</body>");
out.println("</html>");
}
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Provide a simple form for GET requests
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html><head><title>Enter Numbers</title></head><body>");
out.println("<h1>Enter Two Numbers</h1>");
out.println("<form method='post' action='AdditionServlet'>");
out.println("Number 1: <input type='number' name='num1'><br><br>");
out.println("Number 2: <input type='number' name='num2'><br><br>");
out.println("<input type='submit' value='Add Numbers'>");
out.println("</form></body></html>");
}
}

You would also need a simple HTML form (e.g., index.html) to send the numbers to this
servlet using the POST method, or you can access the servlet directly via a GET
request which will display a basic input form.
E) Write a JDBC program to display the details of employees (eno, ename, department,
sal) whose department is ‘Computer Application’.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EmployeeDetailsByDepartment {

public static void main(String[] args) {


String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
66

String password = "your_password";


String department = "Computer Application";

try (Connection connection = DriverManager.getConnection(url, username,


password);
PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT eno, ename, department, sal FROM employees WHERE
department = ?")) {

preparedStatement.setString(1, department);
ResultSet resultSet = preparedStatement.executeQuery();

System.out.println("Employee Details for Department: " + department);


System.out.println("--------------------------------------------------");
System.out.printf("%-10s %-20s %-20s %-10s%n", "ENO", "ENAME",
"DEPARTMENT", "SAL");
System.out.println("--------------------------------------------------");

while (resultSet.next()) {
int eno = resultSet.getInt("eno");
String ename = resultSet.getString("ename");
String dept = resultSet.getString("department");
double sal = resultSet.getDouble("sal");
System.out.printf("%-10d %-20s %-20s %-10.2f%n", eno, ename, dept, sal);
}

System.out.println("--------------------------------------------------");

} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}

a) run() method
The run() method is the entry point for a thread's execution in Java. When a thread is
started using the start() method, the Java Virtual Machine (JVM) calls the run() method
of that thread. The code within the run() method defines the task that the thread will
perform. For classes that implement the Runnable interface, the run() method contains
67

the implementation of the task. For classes that extend the Thread class, the run()
method should be overridden to define the thread's specific behavior.

b) Statement interface
In JDBC, the Statement interface provides a basic mechanism for executing SQL
queries against a database. You obtain Statement objects from a Connection object. It
allows you to send static SQL statements to the database and retrieve the results (if
any). However, using Statement directly can be less efficient for repeated queries and is
vulnerable to SQL injection vulnerabilities if user input is directly embedded in the SQL
string. For parameterized queries, PreparedStatement is a more secure and often more
performant alternative.

c) HttpServlet
HttpServlet is an abstract class in Java that extends GenericServlet. It provides a
specialized framework for handling HTTP requests and responses. When creating web
servlets, you typically subclass HttpServlet and override its methods that correspond to
different HTTP request methods, such as doGet() for handling GET requests, doPost()
for handling POST requests, doHead(), doPut(), doDelete(), etc. The HttpServlet class
simplifies web application development by providing a structure tailored to the HTTP
protocol.

You might also like