0% found this document useful (0 votes)
6 views19 pages

Java 2081 Set Solution

The document covers advanced Java programming concepts, including servlet APIs, JSP forms for employee data submission, JPanel usage in Swing, mnemonics and accelerators for menu items, inner and anonymous inner classes, and file serialization of employee objects. It also discusses JavaFX layouts, a button click counter program, RMI architecture, and mouse event handling in Swing. Each section includes explanations, code examples, and practical applications.

Uploaded by

1230bicky
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)
6 views19 pages

Java 2081 Set Solution

The document covers advanced Java programming concepts, including servlet APIs, JSP forms for employee data submission, JPanel usage in Swing, mnemonics and accelerators for menu items, inner and anonymous inner classes, and file serialization of employee objects. It also discusses JavaFX layouts, a button click counter program, RMI architecture, and mouse event handling in Swing. Each section includes explanations, code examples, and practical applications.

Uploaded by

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

Advanced Java Programming

Model set 2081 Solution


Section A: Long Answer Questions

1. Discuss about any four servlet APIs. Design a form in JSP to take necessary
information about an employee, and when the user clicks the submit button, it
should be displayed on the second page.

➢ 1. Servlet APIs, JSP Form, and Data Display


Four Servlet APIs
The Servlet API provides a set of classes and interfaces for creating web applications
in Java. Four fundamental APIs are:
1. [Link] Interface: This is the core interface for all servlets. It defines
the lifecycle methods that a servlet container uses to manage a servlet instance. Key
methods include:
o init(ServletConfig config): Called once by the container to initialize the servlet.
o service(ServletRequest req, ServletResponse res): Called by the container to
handle each client request.
o destroy(): Called once when the servlet is taken out of service.
o getServletConfig(): Returns the ServletConfig object.
o getServletInfo(): Returns a string with information about the servlet.
2. [Link] Interface: This interface represents a client's request
to the servlet. It provides methods to get request information such as parameters,
attributes, headers, and the input stream.
o getParameter(String name): Returns the value of a request parameter.
o getInputStream(): Retrieves the body of the request as a binary data stream.
o getAttribute(String name): Returns the value of a named attribute.
o getProtocol(): Returns the name and version of the protocol the request uses.
3. [Link] Interface: This interface helps a servlet to formulate
and send a response back to the client. It provides methods for setting response
headers and getting the output stream.
o getWriter(): Returns a PrintWriter object that can send character text to the
client.
o getOutputStream(): Returns a ServletOutputStream suitable for writing binary
data.
Page 1 of 19
o setContentType(String type): Sets the MIME type of the content being sent in
the response (e.g., "text/html").
o setContentLength(int len): Sets the length of the content body in the response.
4. [Link] Class: This is an abstract class that extends
GenericServlet and is specifically designed to handle HTTP requests. It simplifies
servlet development by providing separate methods for different HTTP request types
like GET, POST, PUT, DELETE, etc.
o doGet(HttpServletRequest req, HttpServletResponse res): Handles HTTP GET
requests.
o doPost(HttpServletRequest req, HttpServletResponse res): Handles HTTP
POST requests.

JSP Form to Display Employee Information


Here's the code for a two-page JSP application that captures and displays employee
data.
Page 1: employee_form.jsp (The Form)
This page contains an HTML form to input employee details.
Java
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Employee Information Form</title>
</head>
<body>

<h2>Enter Employee Details</h2>


<form action="display_employee.jsp" method="post">
Employee ID: <input type="text" name="empId"><br/><br/>
Employee Name: <input type="text" name="empName"><br/><br/>
Department: <input type="text" name="empDept"><br/><br/>
Salary: <input type="text" name="empSalary"><br/><br/>
<input type="submit" value="Submit">
</form>

</body>

Page 2 of 19
</html>
Page 2: display_employee.jsp (The Display Page)
This page retrieves the data submitted from the form and displays it.
Java
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Employee Details</title>
</head>
<body>

<h2>Submitted Employee Information</h2>

<%
// Retrieve parameters from the request object
String id = [Link]("empId");
String name = [Link]("empName");
String department = [Link]("empDept");
String salary = [Link]("empSalary");
%>

<p><strong>Employee ID:</strong> <%= id %></p>


<p><strong>Employee Name:</strong> <%= name %></p>
<p><strong>Department:</strong> <%= department %></p>
<p><strong>Salary:</strong> <%= salary %></p>

</body>
</html>

2. When do we use JPanel? How do you add mnemonics and accelerators to menu
items? Explain.
➢ When to use JPanel
A JPanel is a generic, lightweight Swing container. It's one of the most versatile
components and is used primarily for two reasons:

Page 3 of 19
1. Grouping Components: JPanel acts as a general-purpose container to group other
UI components (like JButton, JTextField, JLabel). You can set a layout manager on a
JPanel to organize the components within it. This allows you to build complex user
interfaces by creating smaller, manageable panels and combining them within a top-
level container like a JFrame.
2. Custom Painting: You can extend JPanel and override its paintComponent(Graphics
g) method to create custom drawings, graphics, and animations. It provides a blank
canvas for rendering shapes, images, or custom visualizations.
Adding Mnemonics and Accelerators
Mnemonics and Accelerators are keyboard shortcuts that improve the usability of a
GUI application, particularly for menus.
• Mnemonic: A keyboard shortcut that activates a menu or menu item when the Alt key
is pressed along with the mnemonic character. It's visually indicated by an underline
on the character. You add it using the setMnemonic(char c) method.
• Accelerator: A global keyboard shortcut (e.g., Ctrl+S to save) that triggers a menu
item's action directly, without needing to open the menu first. You add it using the
setAccelerator(KeyStroke ks) method.
Example Code:
Here's a Java Swing program demonstrating how to add a mnemonic and an
accelerator to menu items.
Java
import [Link].*;
import [Link];
import [Link];

public class MenuShortcutsExample extends JFrame {

public MenuShortcutsExample() {
setTitle("Menu Shortcuts Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JMenuBar menuBar = new JMenuBar();

// --- File Menu ---


JMenu fileMenu = new JMenu("File");
// Add a mnemonic to the 'File' menu itself (Alt + F)
[Link](KeyEvent.VK_F);

Page 4 of 19
// --- New Menu Item ---
JMenuItem newItem = new JMenuItem("New");
// No shortcuts for this one

// --- Save Menu Item ---


JMenuItem saveItem = new JMenuItem("Save");
// Add a mnemonic (Alt + S, when menu is open)
[Link](KeyEvent.VK_S);
// Add an accelerator (Ctrl + S, works anytime)
[Link]([Link](KeyEvent.VK_S,
ActionEvent.CTRL_MASK));

[Link](e -> [Link]("Save item clicked!"));

// --- Exit Menu Item ---


JMenuItem exitItem = new JMenuItem("Exit");
[Link](e -> [Link](0));

[Link](newItem);
[Link](saveItem);
[Link]();
[Link](exitItem);

[Link](fileMenu);
setJMenuBar(menuBar);
setVisible(true);
}

public static void main(String[] args) {


new MenuShortcutsExample();
}
}

3. How do you create inner class and anonymous inner class? Create a class
EMPLOYEE with data members: Emp_ID, Name, and Occupation. Write those
objects to the file [Link] where the occupation is Doctor.
➢ Inner Class and Anonymous Inner Class

Page 5 of 19
1. Inner Class (or Member Inner Class): An inner class is a class defined within the
body of another class. It has access to all members (fields and methods) of the outer
class, including private ones. It is useful for logically grouping classes that are only
used in one place and for creating more readable and maintainable code.
Syntax:
Java
class OuterClass {
private int outerData;

class InnerClass {
void display() {
// Can access private members of OuterClass
[Link]("Outer data is: " + outerData);
}
}
}
2. Anonymous Inner Class: An anonymous inner class is an inner class without a
name. It is declared and instantiated in a single expression. It is typically used for
creating a one-time-use object of a class or an implementation of an interface, often
for event handlers.
Syntax (for implementing an interface):
Java
// Assuming 'MyInterface' is an interface with a 'doSomething' method
MyInterface myObject = new MyInterface() {
@Override
public void doSomething() {
[Link]("Anonymous implementation.");
}
};
EMPLOYEE Class and Writing Objects to a File
Here's a program that defines an EMPLOYEE class and writes instances of it to a file
[Link] only if their occupation is "doctor".
1. The EMPLOYEE Class
The class must implement [Link] to allow its objects to be written to an
object stream.
Java
import [Link];

Page 6 of 19
public class EMPLOYEE implements Serializable {
// A version ID for serialization compatibility
private static final long serialVersionUID = 1L;

private int empId;


private String name;
private String occupation;

public EMPLOYEE(int empId, String name, String occupation) {


[Link] = empId;
[Link] = name;
[Link] = occupation;
}

public String getOccupation() {


return occupation;
}

@Override
public String toString() {
return "EMPLOYEE [empId=" + empId + ", name=" + name + ", occupation=" +
occupation + "]";
}
}
2. The Main Program ([Link])
This program creates several EMPLOYEE objects and serializes only the doctors to
[Link].
Java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class WriteDoctorsToFile {

public static void main(String[] args) {


// Create a list of employees

Page 7 of 19
List<EMPLOYEE> employees = new ArrayList<>();
[Link](new EMPLOYEE(101, "Dr. Alice", "doctor"));
[Link](new EMPLOYEE(102, "Bob Smith", "engineer"));
[Link](new EMPLOYEE(103, "Dr. Charlie", "doctor"));
[Link](new EMPLOYEE(104, "Diana Prince", "manager"));
[Link](new EMPLOYEE(105, "Dr. Eve", "doctor"));

// Use try-with-resources to ensure the stream is closed


try (FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {

[Link]("Writing doctor objects to [Link]...");

// Iterate through the list and write only employees whose occupation is
"doctor"
for (EMPLOYEE emp : employees) {
if ("doctor".equalsIgnoreCase([Link]())) {
[Link](emp);
[Link]("Wrote: " + emp);
}
}

[Link]("Done writing to file.");

} catch (IOException e) {
[Link]();
}
}
}

Section B: Short Answer Questions


4. Describe about any three types of JavaFX layouts.
➢ Three Types of JavaFX Layouts
JavaFX provides several layout panes to automatically manage the position and size
of UI controls. Three common types are:

Page 8 of 19
I. VBox: Arranges its child nodes in a single vertical column. You can set spacing
between the nodes and alignment within the box. It's ideal for creating toolbars or
forms where elements are stacked on top of each other.
II. HBox: Arranges its child nodes in a single horizontal row. Similar to VBox, it allows
for spacing and alignment. It's perfect for menus, button bars, or any horizontal
arrangement of components.
III. BorderPane: Divides the layout area into five distinct regions: top, bottom, left,
right, and center. Each region can hold one node. This is very useful for typical
application layouts where you might have a menu bar at the top, a status bar at the
bottom, navigation on the left, and the main content in the center.

5. Write a program to design a form with a button and label, such that the number of
times the button is clicked is displayed in the label.
➢ Program to Count Button Clicks
This Java Swing program creates a window with a button and a label. Each time the
button is clicked, a counter is incremented, and the label is updated to show the
current count.
Java
import [Link].*;
import [Link];
import [Link];

public class ButtonClickCounter extends JFrame implements ActionListener {


private int clickCount = 0;
private JLabel label;
private JButton button;

public ButtonClickCounter() {
setTitle("Button Click Counter");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new [Link]());

// Create the button


button = new JButton("Click Me!");
[Link](this); // Register this class as the listener

// Create the label

Page 9 of 19
label = new JLabel("Number of clicks: 0");

// Add components to the frame


add(button);
add(label);

setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
// This method is called when the button is clicked
if ([Link]() == button) {
clickCount++;
[Link]("Number of clicks: " + clickCount);
}
}

public static void main(String[] args) {


new ButtonClickCounter();
}
}
6. Explain the architecture of RMI.
➢ Architecture of RMI

Page 10 of 19
RMI (Remote Method Invocation) allows a Java object on one Java Virtual Machine
(JVM) to invoke methods on an object in another JVM. Its architecture is based on a
layered model:

I. Application Layer: This layer consists of the client application code and the
server-side remote object implementation. The client makes a call to a method as
if it were a local object, and the remote object contains the actual logic to be
executed.
II. Stub/Skeleton Layer (Proxy Layer): This is an intermediary layer that hides the
complexity of network communication.
o Stub (Client-side): The stub acts as a proxy for the remote object on the
client side. When the client invokes a method, it's actually calling a method
on the stub. The stub is responsible for marshalling (packing) the method
parameters and sending the request to the server.
o Skeleton (Server-side): The skeleton resides on the server. It receives the
request from the stub, unmarshals (unpacks) the parameters, and invokes
the actual method on the remote object. It then marshals the return value
and sends it back to the stub.
III. Remote Reference Layer (RRL): This layer manages the references and
connections between the client and the remote object. It ensures that the client's
reference (stub) is uniquely mapped to the server-side object and handles
connection management.
IV. Transport Layer: This is the underlying network protocol layer responsible for the
actual transmission of data over the network. RMI typically uses TCP/IP for
reliable, connection-oriented communication.

7. Write a program to show the use of mouse event.


➢ Program to Show Mouse Events
This Java Swing program demonstrates how to capture and display different mouse
events like clicks, presses, and movement. It uses a MouseAdapter for convenience.
Java
import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class MouseEventDemo extends JFrame {


private JLabel statusLabel;

Page 11 of 19
public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

JPanel drawingPanel = new JPanel();


[Link](Color.LIGHT_GRAY);

statusLabel = new JLabel("Move mouse over the gray area",


[Link]);

// Add a mouse listener to the panel


[Link](new MyMouseListener());
[Link](new MyMouseListener());

add(drawingPanel, [Link]);
add(statusLabel, [Link]);
setVisible(true);
}

// Inner class extending MouseAdapter to handle events


private class MyMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at (" + [Link]() + ", " + [Link]() + ")");
}

@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed at (" + [Link]() + ", " + [Link]() + ")");
}

@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released at (" + [Link]() + ", " + [Link]() + ")");
}

Page 12 of 19
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered the panel");
}

@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited the panel");
}

@Override
public void mouseMoved(MouseEvent e) {
// This is part of MouseMotionListener
[Link]("Mouse Moved at (" + [Link]() + ", " + [Link]() + ")");
}
}

public static void main(String[] args) {


new MouseEventDemo();
}
}
8. Define package. What is the use of the final keyword and finally block?
➢ Package, final Keyword, and finally Block
• Package: A package in Java is a mechanism for organizing related classes and
interfaces into a namespace. It helps in preventing naming conflicts, controlling
access to classes, and making the codebase more manageable and reusable. For
example, [Link] is a package that contains utility classes like ArrayList and
HashMap.
• Use of final keyword: The final keyword is a non-access modifier that can be
applied to variables, methods, and classes with the following effects:
o final variable: Its value cannot be changed once assigned. It effectively
becomes a constant.
o final method: It cannot be overridden by a subclass. This is used to
preserve the implementation of an important method.
o final class: It cannot be extended or inherited. This is used for security
reasons or to create immutable classes (e.g., the String class).

Page 13 of 19
• Use of finally block: The finally block is used in a try-catch exception handling
structure. The code within the finally block is always executed, regardless of
whether an exception was thrown or caught. Its primary purpose is to perform
cleanup operations, such as closing file streams, database connections, or
network sockets, to release system resources and prevent memory leaks.

9. Explain the architecture of JDBC and list the JDBC driver types.
➢ JDBC Architecture

JDBC (Java Database Connectivity) provides a standard API for Java applications to
interact with databases. Its architecture consists of two main components:
I. JDBC API: This provides a set of interfaces and classes for the Java application,
including Connection, Statement, ResultSet, and DriverManager. The application
code uses this API to perform database operations without needing to know the
specifics of the underlying database.
II. JDBC Driver Manager and Drivers: The DriverManager class is the backbone of
the architecture. It manages a list of available database drivers. When the
application requests a connection, the DriverManager finds a suitable driver from

Page 14 of 19
its list and uses it to establish the connection with the database. The JDBC Driver
is a software component that implements the JDBC API for a specific database
vendor (e.g., MySQL, Oracle). It translates the standard JDBC calls into the
database's native protocol.

JDBC Driver Types

There are four main types of JDBC drivers:


I. Type 1: JDBC-ODBC Bridge: Translates JDBC calls into ODBC (Open Database
Connectivity) calls. It requires an ODBC driver to be installed on the client
machine. This driver is platform-dependent and now considered obsolete.
II. Type 2: Native-API Driver: A mix of Java and native code. It uses a vendor-specific
native library on the client machine to communicate with the database. It offers
better performance than Type 1 but is also platform-dependent.
III. Type 3: Network-Protocol Driver: A pure Java driver that communicates with a
middleware server. The middleware then translates the requests into the
database-specific protocol. This allows a single driver to connect to multiple
types of databases.
IV. Type 4: Thin Driver (Database-Protocol Driver): A pure Java driver that directly
converts JDBC calls into the vendor-specific database protocol. It communicates
directly with the database server over the network. This is the most common type
today as it is platform-independent and does not require any special software on
the client side.

10. Write the steps of writing a socket program using UDP.


➢ UDP (User Datagram Protocol) is a connectionless protocol. A program using UDP
involves a client sending datagram packets and a server receiving them.
Server Steps:
I. Create a DatagramSocket: Instantiate a DatagramSocket and bind it to a specific
port number on which it will listen for incoming data. DatagramSocket socket =
new DatagramSocket(portNumber);
II. Create a Buffer: Create a byte array (byte[]) to act as a buffer to store the data
received from the client.
III. Create a DatagramPacket: Create a DatagramPacket object to receive the
incoming data. This packet is associated with the byte buffer.
IV. Receive Data: Call the receive() method of the DatagramSocket. This is a blocking
call that waits until a packet is received from a client.
V. Process Data: Once a packet is received, extract the data, sender's IP address,
and port number from the DatagramPacket object and process it.

Page 15 of 19
VI. (Optional) Send Reply: To send a response, create a new DatagramPacket
containing the reply data, the client's IP address, and port number (obtained from
the received packet), and use the send() method of the socket.
VII. Close Socket: Close the DatagramSocket when it's no longer needed.

Client Steps:

I. Create a DatagramSocket: Instantiate a DatagramSocket. It does not need to be


bound to a specific port; the OS will assign one.
II. Prepare Data: Convert the message to be sent into a byte array.
III. Get Server Address: Create an InetAddress object representing the server's IP
address.
IV. Create DatagramPacket to Send: Create a DatagramPacket containing the data
buffer, server's InetAddress, and the server's port number.
V. Send Data: Call the send() method of the DatagramSocket to transmit the packet
to the server.
VI. (Optional) Receive Reply: If expecting a response, create a buffer and a packet
and call the receive() method.
VII. Close Socket: Close the DatagramSocket.

11. Define scriplets. Discuss about JSP access models.



• Scriptlet: A scriptlet is a fragment of Java code embedded inside a JSP
(JavaServer Pages) file. It is enclosed within <% ... %> tags. The Java code within a
scriptlet is executed on the server every time the JSP page is requested. While
powerful, overuse of scriptlets is discouraged as it mixes business logic with
presentation code, making pages hard to maintain.
JSP Access Models
There are two primary architectural models for building web applications using JSP:

I. Model 1 Architecture:

Page 16 of 19
o In this simple model, the JSP page is responsible for everything. It
processes the incoming HTTP request, executes any business logic (e.g.,
accessing a database), and generates the HTML response for the browser.
o The workflow is straightforward: Browser -> JSP -> Browser.
o Advantages: Simple to learn and quick for small projects.
o Disadvantages: It tightly couples business logic with presentation logic,
leading to messy, unmaintainable code ("spaghetti code") as the
application grows.

II. Model 2 Architecture (MVC):

Page 17 of 19
o This model is based on the Model-View-Controller (MVC) design pattern,
which separates the application's concerns.
o Controller: A Servlet acts as the controller. It receives all incoming
requests, processes user input, interacts with the Model to perform
business logic, and then decides which View to forward the request to.
o Model: Plain Java Objects (POJOs) or JavaBeans represent the
application's data and business logic. They are manipulated by the
Controller.
o View: A JSP page acts as the view. Its sole responsibility is to present the
data prepared by the Controller. It contains minimal Java logic, mostly
using JSP tags (like JSTL) and Expression Language (EL) to display data from
the Model.
o Advantages: Promotes a clean separation of concerns, making the
application more organized, scalable, and easier to maintain and test. This
is the standard for modern Java web applications.

Page 18 of 19
12. Why do we need ports in socket programming? What types of instructions are
written in a try block?
➢ Why We Need Ports in Socket Programming
An IP address is used to identify a specific computer (host) on a network. However, a
single computer can run many different network applications at the same time (e.g.,
a web browser, an email client, a file server).
A port number is a 16-bit number (0−65535) used to identify a specific application or
process running on that host. When a network packet arrives at a computer, the IP
address directs it to the correct machine, and the port number tells the operating
system which application should receive that data.
Therefore, the combination of an IP address and a port number creates a unique
endpoint for communication, known as a socket. Ports are essential for enabling
multiple network communications to occur simultaneously on a single machine
without getting mixed up.
Instructions Written in a try Block
The try block in Java is a fundamental part of its exception handling mechanism. You
should place any code inside a try block that has the potential to throw an exception.
Types of instructions typically written in a try block include:
• Risky Operations: Code that interacts with external resources which may not be
available. This includes:
o File I/O operations (e.g., new FileInputStream("[Link]")).
o Network communication (e.g., new Socket("server", 80)).
o Database connections and queries (e.g.,
[Link](...)).
• Error-Prone Calculations: Operations that can lead to runtime errors, such as:
o Integer division by zero (ArithmeticException).
o Accessing an array element with an out-of-bounds index
(ArrayIndexOutOfBoundsException).
o Attempting to use a null reference (NullPointerException).
• Method Calls: Any call to a method that is declared with a throws clause for a
checked exception. The Java compiler forces you to handle these potential
exceptions by placing the method call within a try block.

Page 19 of 19

You might also like