Javaaaaaaaaaaaaaaaaaaa
Javaaaaaaaaaaaaaaaaaaa
Unit I
Java Networking
Question 1
Define Socket programming in Java. Explain the role of Socket and ServerSocket classes in
establishing a TCP connection.
Socket programming is a mechanism in Java that enables two programs (processes) running on different machines (or
the same machine) to communicate with each other over a network. A socket represents one endpoint of a two-way
communication link between two programs. Java provides built-in support for socket programming through the [Link]
package, making it easier to develop networked applications such as chat applications, file transfer utilities, and
client-server systems.
In Java, socket programming primarily uses the TCP/IP protocol, which is a connection-oriented protocol that guarantees
reliable, ordered delivery of data between applications. The two key classes used for TCP socket communication are
Socket (client-side) and ServerSocket (server-side).
The [Link] class represents a client-side socket. It is used by the client to establish a connection to a server.
When a Socket object is created, it automatically attempts to connect to the specified server IP address and port number.
Key Constructors:
- Socket(String host, int port) -- Connects to the specified host and port.
- Socket(InetAddress addr, int port) -- Connects using an InetAddress object.
Important Methods:
The [Link] class is used on the server side. It creates a socket that listens (waits) for incoming client
connection requests on a specified port number. Once a client connects, the ServerSocket's accept() method returns a
new Socket object representing the connection to that specific client.
Key Constructor:
- accept() -- Waits for and accepts an incoming client connection; returns a Socket.
- close() -- Closes the server socket.
- getLocalPort() -- Returns the port on which the server socket is listening.
Page 2/41
Java Questions -- Mid-Semester
Step 1: The server creates a ServerSocket on a specific port and calls accept(), which blocks until a client connects.
Step 2: The client creates a Socket specifying the server's IP address and port.
Step 3: The accept() method on the server returns a new Socket object for that client.
Step 4: Both client and server use getInputStream() and getOutputStream() to exchange data.
Step 5: After communication is complete, both sides close their sockets.
5. Example Code
Server Side:
Client Side:
Page 3/41
Java Questions -- Mid-Semester
Question 2
What is the InetAddress class in Java? Write a Java program to find the IP address and hostname of
a machine using InetAddress.
The InetAddress class in Java (part of [Link] package) represents an Internet Protocol (IP) address. It encapsulates
both the numerical IP address and the domain name (hostname) for that address. Since there are no constructors for this
class, objects are obtained through static factory methods. This class handles both IPv4 and IPv6 addresses.
4. Characteristics of InetAddress
- InetAddress has no public constructors; objects are created using static methods.
- It performs DNS resolution automatically when getByName() is called with a hostname.
- It is serializable and can be used to pass address information across streams.
- It is an immutable class -- once created, its values cannot be changed.
Page 4/41
Java Questions -- Mid-Semester
import [Link];
public class InetAddressDemo {
public static void main(String[] args) throws Exception {
InetAddress local = [Link]();
[Link]("Host Name : " + [Link]());
[Link]("IP Address: " + [Link]());
InetAddress remote = [Link]("[Link]");
[Link]("Google IP : " + [Link]());
}
}
7. Sample Output
Page 5/41
Java Questions -- Mid-Semester
Question 3
Differentiate between TCP/IP sockets and Datagrams (UDP) in Java. When would you prefer one over
the other?
Comparison Table
Page 6/41
Java Questions -- Mid-Semester
Question 4
Explain the URL class in Java. Write a code snippet to parse a URL and extract its protocol, host,
port, and path components.
The URL (Uniform Resource Locator) class in Java ([Link] package) represents a pointer to a resource on the World
Wide Web. A URL identifies a resource using a protocol, hostname, optional port number, and a path. It is immutable --
once created, cannot be changed.
2. Structure of a URL
URL Structure
3. Important Methods
Page 7/41
Java Questions -- Mid-Semester
4. Java Code -- Parsing a URL
import [Link];
public class URLDemo {
public static void main(String[] args) throws Exception {
5. Sample Output
Protocol : https
Host : [Link]
Port : 8080
Path : /docs/[Link]
Query : id=10
Reference: top
Page 8/41
Java Questions -- Mid-Semester
Question 5
What is the URLConnection class? Explain how it is used to read content from a web resource with a
suitable example.
The URLConnection class ([Link]) is an abstract class that represents a communication link between
the application and a URL resource. It is the superclass of HttpURLConnection. It provides methods to read from and write
to the resource referenced by the URL. Obtained by calling openConnection() on a URL object.
3. Important Methods
Page 9/41
Java Questions -- Mid-Semester
import [Link].*;
import [Link].*;
public class URLConnectionDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
URLConnection conn = [Link]();
[Link]("Content Type : " + [Link]());
[Link]("Content Length: " + [Link]());
BufferedReader br = new BufferedReader(
new InputStreamReader([Link]()));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
}
}
Page 10/41
Java Questions -- Mid-Semester
Question 6
Write a short note on the [Link] package. List and briefly describe any five important classes in this
package.
The [Link] package is one of the core packages in Java that provides classes and interfaces for networking operations.
It enables Java programs to communicate over the network using various protocols such as TCP, UDP, and HTTP. It
supports two categories:
1. Low-level networking -- Using sockets (TCP) and datagrams (UDP).
2. High-level networking -- Using URL and URLConnection classes for web resource access.
2. Key Features
(i) Socket
Implements a TCP client socket. Used to connect to a remote server. Provides getInputStream()/getOutputStream() for
bidirectional data exchange with the server.
(ii) ServerSocket
Listens for incoming TCP connections on a specified port. The accept() method blocks until a client connects, then
returns a Socket object for that specific client.
(iii) InetAddress
Represents an IP address (IPv4/IPv6). Provides static methods like getByName() and getLocalHost() for DNS
resolution. Encapsulates both hostname and numeric address.
(iv) URL
Represents a Uniform Resource Locator. Parses URL components (protocol, host, port, path). Provides
openConnection() to create a URLConnection for accessing the resource.
(v) DatagramSocket
Used for UDP (connectionless) communication. Sends and receives DatagramPacket objects without establishing a
prior connection. Faster but unreliable compared to TCP.
Page 11/41
Java Questions -- Mid-Semester
Question 7
Explain the concept of a TCP/IP client socket. Write a simple Java TCP client program that sends a
message to a server.
A TCP/IP client socket is one endpoint of a two-way TCP communication channel. The client socket actively initiates a
connection to a server listening on a specific IP and port. In Java, it is represented by [Link]. Creating a Socket
triggers the TCP three-way handshake (SYN -> SYN-ACK -> ACK).
2. Characteristics
- The client always initiates the connection; the server waits passively.
- TCP provides reliable, ordered, error-checked delivery of data.
- The connection is full-duplex -- data flows both directions simultaneously.
- Each connection is identified by (Client IP, Client Port, Server IP, Server Port).
- Data is transferred as a continuous byte stream, not discrete messages.
3. Communication Steps
import [Link].*;
import [Link].*;
public class TCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 5000);
DataOutputStream dout = new DataOutputStream([Link]());
[Link]("Hello from Client!");
[Link]();
[Link]("Message sent to server.");
[Link]();
}
}
Question 8
What are Datagrams in Java? Explain DatagramSocket and DatagramPacket classes with a complete
example of a UDP sender and receiver.
1. Definition of Datagrams
A Datagram is a self-contained, independent packet of data sent over a network without establishing a prior connection.
In Java, datagrams use UDP (User Datagram Protocol). UDP does not guarantee delivery, ordering, or duplicate protection
Page 12/41
Java Questions -- Mid-Semester
but is significantly faster than TCP because there is no connection setup overhead.
2. DatagramSocket Class
Represents a socket for sending and receiving datagram packets via UDP.
3. DatagramPacket Class
4. Comparison
Page 13/41
Java Questions -- Mid-Semester
6. UDP Sender
import [Link].*;
public class UDPSender {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String msg = "Hello via UDP!";
byte[] data = [Link]();
InetAddress ip = [Link]("localhost");
DatagramPacket dp = new DatagramPacket(data, [Link], ip, 9876);
[Link](dp);
[Link]("Message sent.");
[Link]();
}
}
UDP Receiver:
import [Link].*;
public class UDPReceiver {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(9876);
byte[] buffer = new byte[1024];
DatagramPacket dp = new DatagramPacket(buffer, [Link]);
[Link]("Waiting for data...");
[Link](dp);
String msg = new String([Link](), 0, [Link]());
[Link]("Received: " + msg);
[Link]();
}
}
7. Key Points
- Receiver must be started BEFORE the Sender (UDP does not buffer).
- No connection setup; each packet is independent.
- Ideal for real-time apps where speed matters more than reliability.
- Maximum packet size is limited (typically 65,507 bytes for IPv4).
Page 14/41
Java Questions -- Mid-Semester
Unit II
Write the steps involved in connecting a Java application to a database using JDBC. Include the
necessary code for loading the driver and establishing a connection.
JDBC (Java Database Connectivity) is a standard Java API that allows Java applications to connect to relational
databases. It provides a set of interfaces and classes to send SQL queries, retrieve results and manage database
connections.
The [Link] package contains all the necessary classes and interfaces for JDBC.
import [Link].*;
[Link]() dynamically loads the driver class into memory and registers it with DriverManager. From JDBC 4.0+,
this step is optional if the driver JAR is on classpath.
[Link]("[Link]");
[Link]() creates a connection to the database using the JDBC URL, username, and password.
The connection object represents a session with the database.
executeQuery() is used for SELECT queries that return a ResultSet. executeUpdate() is used for INSERT, UPDATE,
DELETE queries that return a row count.
The ResultSet object holds the data returned by the query. [Link]() moves the cursor to the next row. Column values
are retrieved using getInt(), getString(), etc.
while ([Link]()) {
[Link]([Link]("id") + " " + [Link]("name"));
}
Page 16/41
Java Questions -- Mid-Semester
Step 7: Close Resources
Always close ResultSet, Statement, and Connection to release database resources. Close in reverse order of creation to
avoid resource leaks.
[Link]();
[Link]();
[Link]();
Page 17/41
Java Questions -- Mid-Semester
Question 2
What is SQLException in JDBC? Explain its important methods like getMessage(), getSQLState(), and
getErrorCode() with examples.
1. Definition
SQLException ([Link]) is a checked exception that provides information about database access errors or
other SQL-related errors. It is thrown when SQL syntax is wrong, a table doesn't exist, a constraint violation occurs, the
connection fails, or the JDBC driver encounters an error during database operations.
2. Important Methods
(a) getMessage()
Returns a String containing a detailed, human-readable description of the error that occurred.
(b) getSQLState()
Returns a 5-character standard SQL state code defined by ISO/ANSI SQL standards.
Common codes:
- 08001: Unable to connect to database
- 23000: Integrity constraint violation
- 42000: Syntax error in SQL statement
- 42S02: Table or view not found
(c) getErrorCode()
Returns a vendor-specific integer error code. For example, MySQL error code 1045 means 'Access denied for user', and
1146 means 'Table doesn't exist'.
(d) getNextException()
Returns the next SQLException in the chain, or null if there are no more. SQLExceptions can be chained together when
multiple errors occur during a single operation.
Summary Table
Method Return Type Description
Page 18/41
Java Questions -- Mid-Semester
Question 3
Differentiate between Statement and PreparedStatement interfaces in JDBC. When should you use
PreparedStatement over Statement?
What is a Statement
It is used for accessing your database. The statement interface cannot accept parameters and is useful when you are
using static SQL statements at runtime. If you want to run a SQL query only once, then this interface is preferred over
PreparedStatement.
Syntax:
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM students WHERE age > 20");
What is PreparedStatement
It is used when you want to use SQL statements many times. The PreparedStatement interface accepts input parameters
at runtime.
Syntax:
PreparedStatement pstmt = [Link](
"SELECT * FROM students WHERE age > ?");
[Link](1, 20);
ResultSet rs = [Link]();
Page 19/41
Java Questions -- Mid-Semester
Question 4
What is ResultSetMetaData? Explain how it is used to retrieve metadata about the columns in a
ResultSet with a code snippet.
Definition
ResultSetMetaData is an interface in JDBC that provides metadata (data about data) about a ResultSet. It allows you to
obtain information about the types, properties, and characteristics of the columns in a ResultSet without actually retrieving
the row data.
Method Description
getColumnCount() Retrieves the number of columns in the current ResultSet object.
getColumnLabel() Retrieves the suggested name of the column for use.
getColumnName() Retrieves the name of the column.
getTableName() Retrieves the name of the table.
Code Example:
Page 20/41
Java Questions -- Mid-Semester
Question 5
Explain the concept of Transaction Management in JDBC. What are commit(), rollback(), and
setAutoCommit() methods?
What is a Transaction?
- In Java, transactions play a vital role in maintaining data integrity by ensuring ACID properties—Atomicity, Consistency,
Isolation, and Durability. A transaction is a sequence of one or more SQL statements executed as a single unit. This all-or-
nothing approach ensures that either all operations succeed together or none do, safeguarding data from partial updates
or errors during processing.
- Atomicity: Ensures that all operations within a transaction are treated as a single unit—either all succeed or none do. If
any part fails, the entire transaction is rolled back.
- Consistency: Guarantees that the database remains in a consistent state before and after the transaction.
- Isolation: Ensures that transactions are executed independently, without interference from other concurrent transactions.
- Durability: Once a transaction is committed, changes are permanent even in case of a system crash.
If Op1 succeeds but Op2 fails (e.g., due to a crash), money disappears! Transactions ensure both succeed or both are
undone (rolled back).
Transaction Flow
Page 21/41
Java Questions -- Mid-Semester
Key Methods
(a) setAutoCommit(boolean)
By default, auto-commit is true (each SQL statement is automatically committed). Set to false to start a manual
transaction. Multiple statements can then be grouped.
(b) commit()
Permanently saves all changes made since the last commit or rollback. Should be called after ALL statements in the
transaction succeed.
(c) rollback()
Undoes ALL changes made since the last commit. Typically called in the catch block when an exception occurs during
the transaction.
Summary Table
Page 22/41
Java Questions -- Mid-Semester
Question 6
What is the SQLWarning class in JDBC? How does it differ from SQLException? Explain with an
example how to retrieve SQL warnings.
1. Definition
Warnings can be retrieved from Connection, Statement, or ResultSet objects using getWarnings(). Multiple warnings are
chained and accessed via getNextWarning(). After processing, call clearWarnings() to reset the warning chain.
4. Example
import [Link].*;
public class SQLWarningDemo {
public static void main(String[] args) throws
Exception {
[Link]("[Link]");
Connection con =
[Link](
"jdbc:mysql://localhost:3306/mydb", "root",
"password"); Statement stmt =
[Link](); [Link]("SELECT *
FROM students");
SQLWarning warning = [Link]();
while (warning != null) {
[Link]("Warning : " +
[Link]());
[Link]("SQLState : " +
[Link]()); warning =
[Link]();
}
Page 23/41
Java Important Questions -- Mid-Semester
Question 7
Explain the role of ResultSetMetaData in JDBC and how it is used to obtain information about
database tables.
SAME AS PREVIOUS
Page 24/41
Java Important Questions -- Mid-Semester
Question 8
Explain how SQL update operations such as INSERT, UPDATE, and DELETE are executed using
JDBC.
1. Introduction
SQL update operations (INSERT, UPDATE, DELETE) modify data in the database. They use the executeUpdate() method
of Statement or PreparedStatement, which returns the number of rows affected (unlike executeQuery() which returns a
ResultSet for SELECT queries).
2. INSERT Operation
INSERT adds new rows to a table. Use PreparedStatement with placeholders for dynamic values.
3. UPDATE Operation
UPDATE modifies existing rows in a table. Always use a WHERE clause to avoid updating all rows.
4. DELETE Operation
DELETE removes rows from a table. Always use a WHERE clause to avoid deleting all rows.
5. Comparison Table
Page 25/41
Java Important Questions -- Mid-Semester
Key Points
Page 26/41
Java Important Questions -- Mid-Semester
Unit III
Java Servlets
Question 1
What is a Servlet? Explain the advantages of Servlets over CGI (Common Gateway Interface).
1. Definition of a Servlet
A Servlet is a Java class that runs on a web server (or application server) and handles client requests and generates
dynamic responses. Servlets are part of the Java EE (Jakarta EE) specification and are managed by a Servlet Container
(also called a web container), such as Apache Tomcat, GlassFish, or Jetty.
Servlets are primarily used to extend the functionality of web servers by processing HTTP requests (like GET and POST)
and generating dynamic web content such as HTML pages, JSON responses, or file downloads. They act as a middle
layer between the client's browser and the server-side databases or business logic.
A servlet implements the [Link] interface or more commonly extends the [Link] class,
which provides HTTP-specific methods like doGet() and doPost().
CGI is an older technology used to generate dynamic web content. In CGI, the web server creates a new process (typically
a separate program written in C, Perl, or Python) for every client request. Each process handles one request, generates
its response, and then terminates. This approach is simple but has significant performance and scalability limitations.
3. Servlet Architecture
Servlet Architecture
The table below demonstrates the difference between servlet and CGI
Page 28/41
Java Important Questions -- Mid-Semester
Page 29/41
Java Important Questions -- Mid-Semester
Question 2
Describe the Servlet life cycle with a neat diagram. Explain the role of init(), service(), and destroy()
methods.
The Servlet life cycle refers to the entire process from the creation of a servlet instance to its destruction. The life cycle is
managed entirely by the Servlet Container (e.g., Apache Tomcat). The programmer does not create or destroy servlet
objects manually; instead, the container handles it.
After creating the instance, the container calls init() exactly ONCE. Used for one-time initialization tasks such as:
- Opening database connections
Page 30/41
Java Important Questions -- Mid-Semester
- Reading configuration parameters (from [Link] or annotations)
- Loading resources (files, properties)
- Initializing data structures
The init() method receives a ServletConfig object providing access to initialization parameters.
The service() method is the heart of the servlet. Called by the container for EVERY client request. A new thread is created
for each request. In HttpServlet, service() examines the HTTP method and dispatches to the appropriate handler:
Called by the container exactly ONCE before the servlet is removed from memory (server shutdown or servlet
unloaded). Used for cleanup:
- Closing database connections
- Releasing file handles or network resources
- Saving state to persistent storage
- Logging shutdown messages
Garbage Collection
After destroy(), the instance becomes eligible for garbage collection by the JVM.
3. Summary Table
Page 31/41
Java Important Questions -- Mid-Semester
Page 32/41
Java Important Questions -- Mid-Semester
Question 3
Explain the ServletContext interface. How is it used to share data among all servlets in a web
application?
1. Definition of ServletContext
The ServletContext interface ([Link]) represents the entire web application running within the servlet
container. There is exactly ONE ServletContext object per web application (per JVM). It is created by the servlet container
when the web application is deployed and destroyed when the application is undeployed or the server shuts down.
ServletContext provides a way for servlets to communicate with the servlet container and with each other. It acts as a
shared space (application scope) where data can be stored and accessed by ALL servlets within the same web application.
2. Key Characteristics
Page 33/41
Java Important Questions -- Mid-Semester
<web-app>
<context-param>
<param-name>dbURL</param-name>
<param-value>jdbc:mysql://localhost:3306/mydb</param-value>
</context-param>
</web-app>
Accessing in Servlet:
Page 34/41
Java Important Questions -- Mid-Semester
Question 4
Differentiate between ServletContext and ServletConfig interfaces. Give examples of when each
would be used.
ServletConfig ServletContext
Each servlet has got its own ServletConfig ServletContext object is only one and used by different
object. servlets of the application.
Use ServletConfig when only one servlet Use ServletContext when whole application needs
needs information shared by it. information shared by it
Scope Diagram
Page 35/41
Java Important Questions -- Mid-Semester
Page 36/41
Java Important Questions -- Mid-Semester
Question 5
What is a Deployment Descriptor ([Link])? Explain its structure with a sample [Link] file that
maps a servlet to a URL pattern.
The Deployment Descriptor is an XML configuration file named [Link] that describes how a Java web application should
be deployed and configured in the servlet container. It is located in the WEB-INF directory of the web application (WEB-
INF/[Link]).
Note: From Servlet 3.0 onwards, many configurations can also be done using annotations (like @WebServlet).
However, [Link] is still widely used and important to understand.
Structure of [Link]
The [Link] has a root element <web-app> and contains several child elements:
- <servlet> -- Declares a servlet with a name and its fully qualified class name.
- <servlet-mapping> -- Maps a servlet name to a URL pattern.
- <context-param> -- Defines application-wide initialization parameters.
- <welcome-file-list> -- Specifies default pages (e.g., [Link]).
- <error-page> -- Maps error codes or exception types to error pages.
- <filter> and <filter-mapping> -- Declares request/response filters.
- <session-config> -- Configures session timeout.
Page 37/41
Java Important Questions -- Mid-Semester
<web-app>
<servlet>
<servlet-name>mlog1 </servlet-name>
<servlet-class>packagename.Login1 </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mlog1 </servlet-name>
<url-pattern>/loginForm1 </url-pattern></servlet-mapping>
<servlet>
<servlet-name>mlog2</servlet-name>
<servlet-class>packagename.Login2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mlog</servlet-name>
<url-pattern>/loginForm2 </url-pattern>
</servlet-mapping>
</web-app>
Page 38/41
Java Important Questions -- Mid-Semester
Instead of [Link], you can use the @WebServlet annotation:
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
// doGet, doPost...
}
Page 39/41
Java Important Questions -- Mid-Semester
Question 6
Explain the various HTTP methods -- GET, POST, PUT, DELETE, HEAD. How does the HttpServlet
class handle these methods?
HTTP (HyperText Transfer Protocol) defines several request methods that indicate the desired action to be performed
on a resource. Each method has a specific semantic meaning.
(a) GET
The GET method requests data from a specified resource. Most common HTTP method.
Replaces the entire resource at the specified URL with the data sent in the request body.
Page 40/41
Java Important Questions -- Mid-Semester
Identical to GET except the server does NOT return a response body. Returns only headers.
The [Link] class extends GenericServlet and provides built-in support for all HTTP methods. Its
service() method automatically checks the HTTP method of the incoming request and dispatches it to the corresponding
doXxx() method.
4. Key Points
Page 41/41