AJP End Sem Official Paper Solution
AJP End Sem Official Paper Solution
-› a) Container Class:
1. Top-Level Containers:
- These containers are the root of a Java Swing application and are required
to create a GUI.
- Examples:
- JFrame: Used to create a main application window.
- JDialog: Used to create popup dialogs.
- JApplet: Special container used in applets.
- JWindow: A borderless top-level container.
2. Lightweight Containers:
Q.1
- These are containers placed inside top-level containers to manage
components more effectively.
- Examples:
- JPanel: Groups multiple components together.
- JScrollPane: Adds scroll functionality to components.
- JTabbedPane: Allows switching between different panels using tabs.
- JSplitPane: Splits the display area into two resizable parts.
Diagram :
AWT Components:
import [Link].*;
import [Link].*;
[Link](true);
}
-› b) i) Hashing in Java:
Definition:
- Hashing is a technique used to store and retrieve data efficiently using a hash
function.
- It converts input data into a fixed-size hash code for quick access.
Features of Hashing:
Q.1
1. Fast Data Retrieval:
- Hashing allows searching and inserting data in constant time complexity O(1)
in ideal cases.
3. Collision Handling:
- When two different keys produce the same hash value, techniques like
chaining and open addressing are used to resolve conflicts.
import [Link];
- The ‘[Link]’ package is one of the most important utility packages in Java.
- It provides various utility classes and interfaces that help in performing
common programming tasks efficiently.
- This package contains collections framework, date and time handling, random
number generation, internationalization, and event handling classes.
Definition:
- The ‘[Link]’ package is a core Java package that contains a set of utility
classes for handling data structures, algorithms, and common functionalities.
- It provides essential tools that enhance the efficiency of Java applications.
1. Collections Framework:
- Provides a set of classes and interfaces for working with data structures
like lists, sets, and maps.
- Common classes include ‘ArrayList’, ‘HashSet’, ‘HashMap’, and ‘LinkedList’.
4. Event Handling:
- Contains event listener interfaces that help in GUI event-driven
programming.
- Examples include ‘EventListener’, ‘Observer’, and ‘TimerTask’.
5. Internationalization Support:
- Provides classes like ‘Locale’, ‘ResourceBundle’, and ‘Currency’ for adapting
applications to different languages and regions.
- The ‘import’ keyword is used to include classes from the ‘[Link]’ package in
a Java program.
- Example of importing a single class:
import [Link];
- Example of importing the entire package:
import [Link].*;
-› a) Swings Component :
- Swing is a part of Java Foundation Classes (JFC) and provides GUI components
for creating interactive applications.
- It is an extension of AWT and is more flexible and powerful.
- The JTextField component is used to take input, and JButton is used to trigger
the addition process.
- The JLabel component is used to display the result.
import [Link].*;
import [Link].*;
import [Link].*;
public AddTwoNumbers() {
// Setting up the frame
setTitle("Addition of Two Numbers");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
// Creating components
JLabel num1Label = new JLabel("Enter First Number: ");
num1Field = new JTextField();
Q.2
JLabel num2Label = new JLabel("Enter Second Number: ");
num2Field = new JTextField();
setVisible(true);
}
Explanation of Program :
- JFrame: Creates the main window of the application.
- JTextField: Used to take input for two numbers and display the result.
- JLabel: Displays labels for input fields and results.
- JButton: Adds an event listener to perform the addition when clicked.
- GridLayout: Arranges the components in a 4-row, 2-column layout.
- ActionListener: Listens for button clicks and performs the addition operation.
Expected Output :
- User enters two numbers.
- Clicks on the "Add" button.
- The result is displayed in the text field below.
-› b) AWT Components :
1. Button:
- Creates a clickable button that performs an action when pressed.
- Used to trigger events in the application.
2. Label:
- Displays static text or an image on the screen.
- Does not allow user interaction.
3. TextField:
- Allows the user to enter a single line of text input.
- Commonly used in forms and login screens.
4. TextArea:
- Supports multi-line text input.
- Useful for comments, descriptions, and notes.
5. Checkbox:
- Represents an option that can be selected or deselected.
- Used for multiple-choice selections.
6. RadioButton:
- Allows the selection of one option from a group of choices.
- Used in mutually exclusive selections.
Q.2
7. List:
- Displays a list of selectable items.
- Allows single or multiple selections.
8. Choice:
- A drop-down menu allowing users to select one option.
9. Scrollbar:
- Provides vertical and horizontal scrolling functionality.
- Used in areas where content exceeds visible space.
10. Canvas:
- A drawing surface for custom graphics.
- Used for game development and animations.
Diagram :
import [Link].*;
import [Link].*;
Q.2
-› a) Database Connection:
- Ensure Prerequisites:
- MySQL should be installed, and the required database should be created.
- Java Development Kit (JDK) should be installed.
- Download the MySQL JDBC driver (e.g., ‘[Link]-
[Link]’) and place it in the appropriate directory (e.g.,
‘C:\your_tomcat_directory\common\lib’).
- Establish a Connection:
- ‘Connection conn =
[Link]("jdbc:mysql://localhost:3306/my_database",
"username", "password");’
Create a Statement:
Execute Queries:
- Execute SQL queries using the ‘Statement’ object:
‘ResultSet rs = [Link]("SELECT * FROM table_name");’
Process Results:
Close Resources:
- Close the ‘ResultSet’, ‘Statement’, and ‘Connection’ to free resources:
- ‘[Link]();’
Q.3
- ‘[Link]();’
- ‘[Link]();’
Diagram:
Explanation of Diagram:
- Java Application:
- Initiates the process by loading the JDBC driver and establishing a
connection to the database.
- JDBC Driver:
- Acts as an intermediary, translating Java calls into database-specific calls.
- Database:
- Receives and processes SQL queries from the application via the JDBC driver
and returns results.
Q.3
-› b) PreparedStatement
- PreparedStatement is a subinterface of ‘Statement’ in JDBC, used to execute
parameterized SQL queries.
- It helps in preventing SQL injection and improves performance for repeated
executions.
- This program inserts Student Name and Branch Name into the ‘Student’
table.
- Prerequisites:
- Install and configure a relational database (e.g., MySQL).
- Ensure the ‘Student’ table exists with columns student_name and
branch_name.
- Add the MySQL JDBC Driver (‘[Link]’) to the project.
import [Link];
import [Link];
import [Link];
import [Link];
// Execute update
int rowsAffected = [Link]();
[Link](rowsAffected + " row(s) inserted successfully.");
} catch (Exception e) {
[Link]();
}
}
}
Features:
- Uses PreparedStatement to prevent SQL injection.
- Takes user input dynamically for insertion.
- Follows best practices for JDBC connection handling.
This program successfully inserts Student Name and Branch Name into the
Student table using JDBC ‘PreparedStatement’.
Q.4
- Translates JDBC calls into ODBC (Open Database Connectivity) calls, which
are then processed by the ODBC driver to interact with the database.
Diagram :
Explanation of Diagram:
Disadvantages:
- Performance overhead due to double translation (JDBC to ODBC to
database).
- Requires ODBC driver installation on the client machine.
- Not suitable for large-scale applications.
Diagram :
Explanation of Diagram:
Disadvantages:
- Requires native database libraries on the client machine.
- Not portable across different databases.
- Unsuitable for internet-based applications.
Diagram :
Explanation:
Advantages:
- No need for client-side database libraries.
- Suitable for internet-based applications.
- Allows centralized management of database connections.
Disadvantages:
- Requires middleware server setup and maintenance.
- Potential performance overhead due to network communication.
Diagram :
Explanation of Diagram:
Disadvantages:
- Requires a separate driver for each database.
- Establishing a Connection:
- To begin, load the JDBC driver and establish a connection to the database
using ‘[Link]()’.
- Handling Results:
- For queries returning data, process the ‘ResultSet’ to retrieve the results.
- Example:
while ([Link]()) {
int rollNumber = [Link]("rollNumber");
String studentName = [Link]("studentName");
}
- Closing Resources:
- Always close ‘ResultSet’, ‘Statement’, and ‘Connection’ objects to free
resources.
- Example:
[Link]();
[Link]();
[Link]();
Q.5
- Definition:
- RMI stands for Remote Method Invocation.
- It enables an object running on one Java Virtual Machine (JVM) to invoke
methods on an object running on another JVM, possibly on a different physical
machine.
- Purpose:
- Facilitates the development of distributed applications in Java.
- Allows seamless communication between objects across different JVMs.
RMI Architecture:
- Stub:
- Acts as a proxy for the remote object on the client side.
- Implements the same interfaces as the remote object.
- Transmits method calls from the client to the server via the skeleton.
- Skeleton:
- Resides on the server side.
- Receives method calls from the stub.
- Invokes the corresponding method on the actual remote object.
- Remote Reference Layer:
- Manages references to remote objects.
- Handles the semantics of invoking a method on a remote object.
- Transport Layer:
- Establishes and manages network connections between client and server
JVMs.
- Typically uses TCP/IP for communication.
Q.5
- Diagram:
- Explanation of Diagram:
- The client interacts with the stub as if it were the actual remote object.
- The stub forwards the method invocation to the skeleton on the server side.
- The skeleton then calls the appropriate method on the actual remote object.
- The result is sent back through the skeleton to the stub, and finally to the
client.
- Provide the logic for the ‘isPalindrome’ method to determine if the input is
a palindrome.
- Bind the remote object to the RMI registry using a unique name.
Q.5
Example Implementation:
import [Link];
import [Link];
import [Link];
import [Link];
@Override
public boolean isPalindrome(String input) throws RemoteException {
String cleanInput = [Link]("\\s+", "").toLowerCase();
String reverse = new StringBuilder(cleanInput).reverse().toString();
return [Link](reverse);
}
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Explanation of Code:
- Server Program: Registers the ‘PalindromeImpl’ object with the RMI registry
under the name "PalindromeService".
Introduction to RMI:
- Remote Method Invocation (RMI): A Java API that allows an object to invoke
methods on an object running in another Java Virtual Machine (JVM),
facilitating distributed computing.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
Explanation:
Q.6
- Remote Interface (‘Adder’): Declares the ‘add’ method that can be invoked
remotely.
- Remote Implementation (‘AdderRemote’): Provides the actual implementation
of the ‘add’ method.
- Server (‘MyServer’): Binds the remote object to the RMI registry for clients
to access.
- Client (‘MyClient’): Looks up the remote object in the RMI registry and invokes
the ‘add’ method.
Note: Ensure that the RMI registry is running, and the server is bound correctly
before running the client application.
- Purpose:
- Facilitates the development of distributed applications in Java.
- Allows seamless communication between objects across different JVMs.
RMI Architecture:
- Stub:
- Acts as a proxy for the remote object on the client side.
- Implements the same interfaces as the remote object.
- Transmits method calls from the client to the server via the skeleton.
- Skeleton:
Q.6
- Resides on the server side.
- Receives method calls from the stub.
- Invokes the corresponding method on the actual remote object.
- Remote Reference Layer:
- Manages references to remote objects.
- Handles the semantics of invoking a method on a remote object.
- Transport Layer:
- Establishes and manages network connections between client and server
JVMs.
- Typically uses TCP/IP for communication.
- Diagram:
- Explanation of Diagram:
- The client interacts with the stub as if it were the actual remote object.
- The stub forwards the method invocation to the skeleton on the server side.
- The skeleton then calls the appropriate method on the actual remote object.
- The result is sent back through the skeleton to the stub, and finally to the
client.
Q.6
Goals of RMI:
- Transparency:
- Allow remote method invocations to appear similar to local method calls.
- Simplicity:
- Provide a straightforward API for developers to implement distributed
applications.
- Flexibility:
- Support various transport protocols and enable future enhancements without
significant changes to existing code.
- Integration:
- Seamlessly integrate with Java's object-oriented features, ensuring that
remote objects can be used just like local ones.
Q.7
-› a) TCP/IP Communication
- The ‘Socket’ class in Java represents the client-side socket and provides the
necessary methods to establish a connection to a server.
- ‘getInputStream()’:
- Retrieves the input stream of the socket, allowing the client to read data
sent by the server.
Q.7
- ‘getOutputStream()’:
- Retrieves the output stream of the socket, enabling the client to send data
to the server.
- ‘close()’:
- A server socket waits for requests to come in over the network. It performs
operations based on the request and then possibly returns a result to the
requester.
- The ‘ServerSocket’ class in Java provides mechanisms for the server program
to listen for clients and establish connections.
- ‘accept()’:
Q.7
- Listens for a connection to be made to this socket and accepts it. The method
blocks until a connection is made.
- ‘close()’:
Server Program:
import [Link].*;
import [Link].*;
String text;
while ((text = [Link]()) != null) {
[Link]("Received: " + text);
[Link]("Message received");
}
} catch (IOException ex) {
[Link]("Server exception: " + [Link]());
[Link]();
}
}
}
Client Program:
import [Link].*;
import [Link].*;
Q.7
public class TCPClient {
public static void main(String[] args) {
String hostname = "localhost";
int port = 1234;
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = [Link]();
PrintWriter writer = new PrintWriter(output, true);
[Link]("Hello, Server!");
Explanation of Code:
- Server Program:
- The server listens on a specified port number for incoming client connections.
- Client Program:
- The client attempts to connect to the server using the server's hostname
and port number.
- Upon establishing the connection, the client sends a message to the server
and waits for a response.
- Types of Sockets:
- Stream Sockets (TCP): Provide reliable, connection-oriented communication.
- Datagram Sockets (UDP): Offer connectionless, unreliable communication.
1. Server Side:
- Create ServerSocket: Initialize with a specific port to listen for client
requests.
- Listen and Accept: Wait for client connections and establish communication
upon request.
Q.7
- Open I/O Streams: Set up input and output streams to receive and send
data.
- Process Requests: Handle client data as per application logic.
- Close Connections: Terminate streams and sockets after communication
ends.
2. Client Side:
- Create Socket: Connect to the server using its hostname and port number.
- Open I/O Streams: Establish input and output streams for data exchange.
- Send Requests: Transmit data or requests to the server.
- Receive Responses: Obtain and process data sent by the server.
- Close Connections: Shut down streams and sockets after tasks are complete.
- Server Program:
import [Link].*;
import [Link].*;
- Client Program:
import [Link].*;
import [Link].*;
Q.7
public class SimpleClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket .getInputStream()))) {
[Link]("Hello, Server!");
String response = [Link]();
[Link]("Server response: " + response);
} catch (IOException e) {
[Link]();
}
}
}
Explanation of Code:
- Server Program:
- Creates a ‘ServerSocket’ listening on port 12345.
- Waits for client connections and starts a new thread for each connection.
- Reads a message from the client and sends an acknowledgment.
- Client Program:
- Connects to the server at ‘localhost’ on port 12345.
- Sends a message to the server.
- Receives and prints the server's response.
Q.8
Datagram:
- A datagram is a self-contained, independent packet of data carrying enough
information to be routed from the source to the destination without relying on
earlier exchanges.
- Each datagram contains:
- Header Information:
- Source and destination addresses.
- Port numbers.
- Length and checksum.
- Payload:
- The actual data being transmitted.
- Datagrams are used in scenarios where speed is crucial, and occasional data
loss is acceptable, such as live video streaming or online gaming.
‘DatagramSocket’:
‘DatagramPacket’:
- The ‘DatagramPacket’ class represents the data packet sent or received via
a ‘DatagramSocket’.
- components include:
- Data Buffer:
- Holds the data to be sent or the data received.
- Length:
- Specifies the size of the data in bytes.
- Address and Port:
- Indicates the destination or source address and port number.
- When sending data, a ‘DatagramPacket’ is constructed with the data,
destination address, and port. When receiving data, it's constructed with a
buffer to store incoming data.
- A Datagram Example:
- Below is an example demonstrating the use of ‘DatagramSocket’ and
‘DatagramPacket’ for sending and receiving data over UDP:
Server (Receiver):
Q.8
import [Link];
import [Link];
while (true) {
// Create a packet to receive data
DatagramPacket receivePacket = new
DatagramPacket(receiveData, [Link]);
// Receive data from client
[Link](receivePacket);
// Extract data from packet
String sentence = new String([Link](), 0,
[Link]());
[Link]("RECEIVED: " + sentence);
}
} catch (Exception e) {
[Link]();
}
}
}
Client (Sender):
import [Link];
import [Link];
Q.8
import [Link];
- Server Side:
- A ‘DatagramSocket’ is created and bound to port 9876 to listen for
incoming datagram packets.
- A buffer (‘receiveData’) is defined to store incoming data.
- The server enters an infinite loop, continuously waiting for data:
Q.8
- A ‘DatagramPacket’ (‘receivePacket’) is created to receive data into the
buffer.
- The ‘receive()’ method waits for an incoming packet and stores it in
‘receivePacket’.
- The data is extracted from the packet and converted into a string
(‘sentence’).
- The received message is printed to the console.
- Client Side:
- A ‘DatagramSocket’ is created to send data.
- The server's IP address (‘localhost’) and port number (9876) are specified.
- The message to be sent (‘sentence’) is converted into bytes and stored in
‘sendData’.
- A ‘DatagramPacket’ (‘sendPacket’) is created with the data, server
address, and port number.
- The ‘send()’ method is used to transmit the packet to the server.
- The socket is closed after sending the data.
- The servlet lifecycle is managed by the servlet container and consists of the
following stages:
- Loading and Instantiation:
- The servlet class is loaded into memory by the servlet container.
- An instance of the servlet is created.
- Initialization (‘init’ method):
- The servlet container calls the ‘init(ServletConfig config)’ method to
initialize the servlet.
- This method is called only once during the servlet's lifecycle.
- Request Handling (‘service’ method):
- For each client request, the servlet container invokes the
‘service(ServletRequest req, ServletResponse res)’ method.
- This method determines the type of request (e.g., GET, POST) and
dispatches it to the appropriate handler method (‘doGet’, ‘doPost’, etc.).
- Termination (‘destroy’ method):
- When the servlet is to be removed from service, the servlet container
calls the ‘destroy()’ method.
- This allows the servlet to release resources before being garbage
collected.
Diagram:
Q.8
Explanation of Diagram:
- To create a basic servlet, extend the ‘HttpServlet’ class and override the
‘doGet()’ or ‘doPost()’ method.
- A servlet is deployed inside a Java web container such as Apache Tomcat.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/CalculatorServlet")
public class CalculatorServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
[Link]("text/html");
Q.8
PrintWriter out = [Link]();
switch (operation) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
result = num2 != 0 ? num1 / num2 : 0;
break;
}
Explanation of Code:
- Annotations (‘@WebServlet’): Specifies the URL pattern for accessing the
servlet.
- ‘doPost()’ method: Handles POST requests from an HTML form.
- Extracting parameters: Reads user input (‘num1’, ‘num2’, and ‘operation’).
Q.8
- Performing operations: Executes addition, subtraction, multiplication, or
division based on the selected operation.
- Displaying result: Sends an HTML response with the calculated result.