0% found this document useful (0 votes)
11 views41 pages

Javaaaaaaaaaaaaaaaaaaa

The document contains a series of Java programming questions focused on networking concepts, including socket programming, the InetAddress class, and the URL class. It explains key classes such as Socket, ServerSocket, URL, and URLConnection, along with their methods and usage. Additionally, it differentiates between TCP and UDP protocols, providing code examples for client-server communication and URL parsing.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views41 pages

Javaaaaaaaaaaaaaaaaaaa

The document contains a series of Java programming questions focused on networking concepts, including socket programming, the InetAddress class, and the URL class. It explains key classes such as Socket, ServerSocket, URL, and URLConnection, along with their methods and usage. Additionally, it differentiates between TCP and UDP protocols, providing code examples for client-server communication and URL parsing.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Questions -- Mid-Semester

Unit I

Java Networking
Question 1

Define Socket programming in Java. Explain the role of Socket and ServerSocket classes in
establishing a TCP connection.

BETTER TO STUDY FROM THE PPT

1. Definition of Socket Programming

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

2. The Socket Class (Client-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:

- getInputStream() -- Returns an InputStream to receive data from the server.


Page 1/41
Java Questions -- Mid-Semester
- getOutputStream() -- Returns an OutputStream to send data to the server.
- close() -- Closes the socket connection.
- getPort() -- Returns the remote port to which the socket is connected.
- getInetAddress() -- Returns the address to which the socket is connected.

3. The ServerSocket Class (Server-Side)

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:

- ServerSocket(int port) -- Creates a server socket bound to the specified port.


Important Methods:

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

4. Steps to Establish a TCP Connection

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.

Diagram: TCP Connection Flow

5. Example Code

Server Side:

ServerSocket ss = new ServerSocket(6666);


Socket s = [Link](); // waits for client
DataInputStream din = new DataInputStream([Link]());
String msg = [Link]();
[Link]("Client says: " + msg);
[Link]();

Client Side:

Socket s = new Socket("localhost", 6666);


DataOutputStream dout = new DataOutputStream([Link]());
[Link]("Hello Server!");
[Link]();
[Link]();

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.

1. Definition of InetAddress Class

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.

2. Key Factory Methods

- getLocalHost() -- Returns the InetAddress of the local machine.


- getByName(String host) -- Returns the InetAddress for the given hostname or IP string.
- getAllByName(String host) -- Returns an array of all IP addresses for a hostname.

3. Important Instance Methods

- getHostName() -- Returns the hostname associated with this IP address.


- getHostAddress() -- Returns the IP address as a string (e.g., [Link]).
- getAddress() -- Returns the raw IP address as a byte array.
- isReachable(int timeout) -- Tests whether the address is reachable within timeout ms.
- toString() -- Returns a string of the form hostname/IP.

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.

5. InetAddress Class Hierarchy

InetAddress Class Hierarchy

Page 4/41
Java Questions -- Mid-Semester

6. Java Program -- Finding IP Address and Hostname

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

Host Name : MyComputer


IP Address: [Link]
Google IP : [Link]

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

TCP (Transmission Control Protocol) UDP (User Datagram Protocol)


Connection-oriented; uses a three-way handshake Connectionless; no handshake
Guarantees reliable data delivery Does not guarantee delivery
Uses acknowledgements (ACKs) No acknowledgements
Supports retransmission of lost packets No retransmission support
Ensures packets are delivered in order Does not ensure ordering
Provides flow control and congestion control No flow or congestion control
Slower due to higher overhead Faster with minimal overhead
Variable header size (20–60 bytes) Fixed header size (8 bytes)
Treats data as a continuous byte stream Treats data as independent messages
Does not support broadcasting or multicasting Supports broadcasting and multicasting
Used by HTTP, HTTPS, FTP, SMTP Used by DNS, DHCP, VoIP, Streaming

When to Prefer TCP over UDP

Choose TCP when:


- Data integrity is critical (file transfer, banking).
- Order of data matters.
- Examples: HTTP/HTTPS, FTP, SMTP, SSH.

When to Prefer UDP over TCP

Choose UDP when:


- Speed is more important than reliability (live streaming).
- Occasional data loss is acceptable.
- Examples: DNS lookups, online gaming, VoIP, DHCP.

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.

1. Definition of URL Class

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

- getProtocol() -- Returns the protocol (e.g., http, https, ftp).


- getHost() -- Returns the hostname.
- getPort() -- Returns the port number; returns -1 if not specified.
- getPath() -- Returns the path component of the URL.
- getQuery() -- Returns the query string after '?'.
- getRef() -- Returns the reference (fragment) after '#'.
- openConnection() -- Returns a URLConnection to interact with the resource.

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 {

URL url = new URL(


"[Link]
[Link]("Protocol : " + [Link]());
[Link]("Host : " + [Link]());
[Link]("Port : " + [Link]());
[Link]("Path : " + [Link]());
[Link]("Query : " + [Link]());
[Link]("Reference: " + [Link]());
}
}

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.

1. Definition of URLConnection Class

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.

2. Steps to Use URLConnection

Step 1: Create a URL object with the desired resource address.

Step 2: Call [Link]() to obtain a URLConnection object.


Step 3: Optionally set request properties using setRequestProperty().
Step 4: Call connect() (or getInputStream() which implicitly connects).
Step 5: Read the response using getInputStream().
Step 6: Close the connection/streams.

3. Important Methods

- connect() -- Opens the actual connection to the resource.


- getInputStream() -- Returns an InputStream for reading data.
- getOutputStream() -- Returns an OutputStream for writing data.
- getContentType() -- Returns the MIME type of the content.
- getContentLength() -- Returns the size of the content in bytes.
- setRequestProperty(String key, String value) -- Sets a request header.

Page 9/41
Java Questions -- Mid-Semester

4. Java Code -- Reading a Web Resource

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.

1. Overview of the [Link] 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

- Support for both TCP (reliable) and UDP (fast) communication.


- URL handling for accessing web resources.
- DNS resolution through the InetAddress class.
- Support for HTTP communication via HttpURLConnection.
- Classes for both client-side and server-side programming.

3. Five Important Classes

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

1. Concept of TCP/IP Client Socket

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

Step 1: Create Socket -- Socket s = new Socket(serverIP, port);


Step 2: Get output stream -- OutputStream os = [Link]();
Step 3: Write data to server.
Step 4: Optionally read server's response via input stream.
Step 5: Close socket -- [Link]();

4. TCP Client Program

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.

- DatagramSocket() -- Creates a socket bound to any available port.


- DatagramSocket(int port) -- Creates a socket bound to the specified port.
- send(DatagramPacket p) -- Sends a datagram packet.
- receive(DatagramPacket p) -- Receives a datagram packet (blocks until data arrives).
- close() -- Closes the socket.

3. DatagramPacket Class

Represents a datagram packet. It is a container for data plus addressing information.

- DatagramPacket(byte[] buf, int length) -- For receiving.


- DatagramPacket(byte[] buf, int len, InetAddress addr, int port) -- For sending.
- getData() -- Returns data byte array. getLength() -- Returns data length.
- getAddress() -- Returns IP address. getPort() -- Returns port.

4. Comparison

Aspect DatagramSocket DatagramPacket

Role Communication endpoint Data container

Function Sends / receives packets Holds data + address

Analogy Mailbox Letter / Envelope

5. UDP Communication Flow

UDP Sender-Receiver Flow

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

JDBC (Java Database Connectivity)


Question 1

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.

Steps to Connect a Java Application to a Database

Step 1: Import [Link] Package

The [Link] package contains all the necessary classes and interfaces for JDBC.

import [Link].*;

Step 2: Load and Register the JDBC Driver

[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]");

Step 3: Establish a Connection

[Link]() creates a connection to the database using the JDBC URL, username, and password.
The connection object represents a session with the database.

Connection con = [Link](


"jdbc:mysql://localhost:3306/mydb", "root", "password");

Step 4: Create a Statement

The Statement object is used to send SQL queries to the database.

Statement stmt = [Link]();

Step 5: Execute SQL Query

executeQuery() is used for SELECT queries that return a ResultSet. executeUpdate() is used for INSERT, UPDATE,
DELETE queries that return a row count.

ResultSet rs = [Link]("SELECT * FROM students");


Page 15/41
Java Questions -- Mid-Semester
Step 6: Process Results

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

getMessage() String Detailed error description

getSQLState() String 5-char standard SQL state code

getErrorCode() int Vendor-specific error code

getNextException() SQLException Next exception in chain

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

Difference between Statement and PreparedStatement


Feature Statement PreparedStatement
Executes simple SQL queries without Executes precompiled SQL queries with parameters.
Definition
parameters.
Compiled only once, then reused with different
Compilation Compiled every time the query runs.
parameters.
Faster for repeated queries since it reuses precompiled
Performance Slower due to repeated compilation.
SQL.
Supports placeholders (?) for dynamic values.
Parameters Does not support parameters.

Safe against SQL injection since parameters are bound.


SQL Injection Vulnerable to SQL injection attacks.

Suitable for repeated queries with varying inputs.


Use Case Suitable for one-time, static queries.

When to Use PreparedStatement

Executing the Same Query Multiple Times


 PreparedStatement is more efficient as the query is compiled once
 Reduces database server load
Handling User Input
 Automatically escapes special characters
 Prevents SQL injection attacks
 Recommended for any user-provided data

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.

Following are some methods of ResultSetMetaData class.

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:

ResultSet rs = [Link]("select * from Dataset");


ResultSetMetaData rsMetaData = [Link]();
//Number of columns
[Link]("Number of columns: "+[Link]());
//Column label
[Link]("Column Label: "+[Link](1));
//Column name
[Link]("Column Name: "+[Link](1));
//Number of columns
[Link]("Table Name: "+[Link](1));

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.

Why Transaction Management is Needed

Example -- Bank transfer of Rs. 500 from Account A to Account B:


Operation 1: UPDATE accounts SET balance = balance - 500 WHERE id='A'
Operation 2: UPDATE accounts SET balance = balance + 500 WHERE id='B'

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

Transaction Management 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.

[Link](false); // Start manual transaction

(b) commit()

Permanently saves all changes made since the last commit or rollback. Should be called after ALL statements in the
transaction succeed.

[Link](); // Save all changes permanently

(c) rollback()

Undoes ALL changes made since the last commit. Typically called in the catch block when an exception occurs during
the transaction.

[Link](); // Undo all changes

Summary Table

Method Purpose When to Call

setAutoCommit(false) Disable auto-commit Before transaction starts

commit() Save permanently After all statements succeed

rollback() Undo all changes In catch block on error

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

SQLWarning ([Link]) is a subclass of SQLException that represents non-critical, informational conditions


or warnings that occur during database access. Unlike exceptions, warnings do NOT interrupt program execution. They
must be explicitly retrieved using getWarnings() on Connection, Statement, or ResultSet objects.

2. Differences from SQLException

Feature SQLException SQLWarning

Nature Exception (error) Warning (informational)

Execution Interrupts program flow Does NOT interrupt flow

How obtained Thrown automatically (catch block) Retrieved via getWarnings()

Severity Critical errors Non-critical notices

Chaining getNextException() getNextWarning()

Example Table not found Data truncation

3. How to Retrieve Warnings

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.

PreparedStatement pstmt = [Link](


"INSERT INTO students (id, name, marks) VALUES (?, ?, ?)");
[Link](1, 1);
[Link](2, "Rahul");
[Link](3, 85.5);
int rows = [Link]();
[Link](rows + " row(s) inserted.");

3. UPDATE Operation

UPDATE modifies existing rows in a table. Always use a WHERE clause to avoid updating all rows.

PreparedStatement pstmt = [Link](


"UPDATE students SET marks = ? WHERE id = ?");
[Link](1, 90.0);
[Link](2, 1);
int rows = [Link]();
[Link](rows + " row(s) updated.");

4. DELETE Operation

DELETE removes rows from a table. Always use a WHERE clause to avoid deleting all rows.

PreparedStatement pstmt = [Link](


"DELETE FROM students WHERE id = ?");
[Link](1, 1);
int rows = [Link]();
[Link](rows + " row(s) deleted.");

5. Comparison Table

Operation Purpose Returns

INSERT Add new row(s) Count of rows inserted

UPDATE Modify existing row(s) Count of rows updated

DELETE Remove row(s) Count of rows deleted

Page 25/41
Java Important Questions -- Mid-Semester

Key Points

- Use executeUpdate() for INSERT/UPDATE/DELETE (not executeQuery()).


- Always use PreparedStatement for user-supplied values to prevent SQL injection.
- Always include WHERE in UPDATE/DELETE to avoid modifying all rows.
- Use transactions (setAutoCommit(false), commit(), rollback()) when multiple updates must succeed or fail together.

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

2. What is CGI (Common Gateway Interface)?

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

4. Advantages of Servlets over CGI

The table below demonstrates the difference between servlet and CGI

Servlet CGI (Common Gateway Interface)


Page 27/41
Java Important Questions -- Mid-Semester
Servlets are portable and efficient. CGI is not portable.
In Servlets, sharing data is possible. In CGI, sharing data is not possible.
Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.

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.

1. Overview of Servlet Life Cycle

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.

The servlet life cycle consists of five main phases:


1. Loading and Instantiation
2. Initialization (init())
3. Request Handling (service())
4. Destruction (destroy())
5. Garbage Collection

2. Servlet Life Cycle Diagram

Servlet Life Cycle

Detailed Explanation of Each Phase


Initialization -- init() Method

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.

public void init(ServletConfig config)


throws ServletException {
[Link](config);
[Link]("Servlet initialized!");
}

Request Handling -- service() Method

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:

- GET requests --> doGet(request, response)


- POST requests --> doPost(request, response)
- PUT requests --> doPut(request, response)
- DELETE requests -> doDelete(request, response)
Developers typically override doGet()/doPost() rather than overriding service() directly.

Destruction -- destroy() Method

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

public void destroy() {


[Link]("Servlet destroyed!");
}

Garbage Collection

After destroy(), the instance becomes eligible for garbage collection by the JVM.

3. Summary Table

Method Called Purpose

init() Once (at startup) One-time initialization

service() Every request (per thread) Handle client request

destroy() Once (at shutdown) Cleanup and release resources

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?

BETTER TO STUDY FROM THE NOTES

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

- One per web application -- shared by ALL servlets in that application.


- Created at deployment time, destroyed at un-deployment or server shutdown.
- Provides application-wide initialization parameters (from [Link]).
- Acts as a shared data store (application scope) using attributes.
- Provides utility methods for logging, MIME types, resource access, etc.

Data Sharing Diagram

Data Sharing via ServletContext

Page 33/41
Java Important Questions -- Mid-Semester

Context Init Parameters in [Link]

It is written inside the <context-param> tag

<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:

String dbURL = getServletContext().getInitParameter("dbURL");

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

ServletConfig is servlet specific ServletContext is for whole application

Parameters of servletConfig are present as Parameters of servletContext are present as name-value


name-value pair in <init-param> inside pair in <context-param> which is outside of <servlet> and
<servlet> tag. inside <web-app>

ServletConfig object is obtained by ServletContext object is obtained by getServletContext()


getServletConfig() method. method.

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

Scope of Config vs Context

Page 35/41
Java Important Questions -- Mid-Semester

When to Use Each


Use ServletConfig when:
- A parameter is relevant only to a specific servlet.
- Examples: max login attempts for LoginServlet, page size for ListServlet.

Use ServletContext when:


- A parameter needs to be shared across ALL servlets.
- Examples: database URL, application name, shared counters, global settings.

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.

BETTER TO STUDY FROM NOTES

Definition of Deployment Descriptor

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

The [Link] file provides metadata to the servlet container about:


- Servlet declarations and their class names
- URL patterns (mappings) for each servlet
- Initialization parameters (both servlet-level and context-level)
- Welcome files (default pages)
- Error pages
- Filters and listeners
- Session configuration
- Security constraints

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

Sample [Link] File

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

Annotation Alternative (Servlet 3.0+)

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?

1. Introduction to HTTP 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.

2. Detailed Explanation of HTTP Methods

(a) GET

The GET method requests data from a specified resource. Most common HTTP method.

- Purpose: Retrieve data from the server.


- Data: Sent as query parameters in the URL (e.g., /search?q=java).
- Visibility: Parameters are visible in the URL (address bar).
- Security: Less secure (data visible in URL, browser history, server logs).
- Data Limit: Limited by URL length (typically 2048 characters).
- Idempotent: Yes. Cacheable: Yes. Can be bookmarked.
- Example: Viewing a web page, search queries, reading a resource.
(b) POST

The POST method submits data to be processed by a specified resource.

- Purpose: Send data to the server for processing or storage.


- Data: Sent in the request body (not in the URL).
- Visibility: Parameters are NOT visible in the URL.
- Security: More secure than GET (data not in URL).
- Data Limit: No limit (can send large data, files, etc.).
- Idempotent: No. Cacheable: No (by default).
- Example: Login forms, file uploads, creating new records.
(c) PUT

Replaces the entire resource at the specified URL with the data sent in the request body.

- Purpose: Update or replace an existing resource completely.


- Idempotent: Yes (sending the same PUT request multiple times has the same effect).
- Example: Updating a user profile, replacing a file on the server.
(d) DELETE

Requests the server to remove the resource at the specified URL.

- Purpose: Delete a resource from the server.


- Idempotent: Yes. Example: Deleting a user account, removing a file.
(e) HEAD

Page 40/41
Java Important Questions -- Mid-Semester

Identical to GET except the server does NOT return a response body. Returns only headers.

- Purpose: Retrieve only response headers (no body).


- Example: Checking if a URL is valid, getting file size before downloading.
3. How HttpServlet Handles HTTP Methods

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.

HttpServlet Dispatch Flow

HTTP Method HttpServlet Method

GET doGet(req, res)

POST doPost(req, res)

PUT doPut(req, res)

DELETE doDelete(req, res)

HEAD doHead(req, res)

OPTIONS doOptions(req, res)

TRACE doTrace(req, res)

4. Key Points

- Developers override doGet() and doPost() (not service()) in most cases.


- The default implementation of doXxx() methods returns a '405 Method Not Allowed'.
- doHead() by default calls doGet() and discards the body, returning only headers.
- GET should only retrieve data (should not modify server state).
- POST is used when data submission causes a change on the server.
- PUT is used for full resource replacement (RESTful APIs).
- DELETE is used for resource removal (RESTful APIs).

Page 41/41

You might also like