Final Advanced Java Programming
Final Advanced Java Programming
1. Write a complete Java program to create a data entry form using JFrame,
JLabel, JTextField, JRadioButton, ButtonGroup, and JButton. The program
should handle a button click to display the collected data.
2. Write a GUI application that performs a calculation based on user input and
events (e.g., a simple BMI calculator or currency converter).
3. Write a complete Java program to INSERT multiple records into a database
table using PreparedStatement inside a loop.
4. Write a complete Java program to SELECT records from a database table and
display the results on the console using a while loop on the ResultSet.
5. Write a GUI application that connects to a database. The UI should have a text
field for a user to enter an ID and a "Search" button. When clicked, the
program should retrieve the corresponding record from the database and
display its details in other text fields.
6. Write a servlet that processes an HTML form. The servlet should retrieve at
least two parameters from the request, perform a simple operation, and write
an HTML response back to the client.
7. Write a JSP page that uses HttpSession to manage state (e.g., a page hit
counter that increments and displays a count specific to the user's current
session).
8. Write a JSP page (the view) and a Servlet (the controller) that work together
using the MVC pattern. The servlet should process a request, set an attribute,
and then forward the request to the JSP for display.
9. Write a complete client-server application using RMI. This must include all four
parts: the Remote Interface, the Implementation class, the Server program,
and the Client program.
10. RMI Application with Primitive Data Types and Logic
11. RMI Application with Custom Serializable Objects
2
1. Differentiate between AWT and Swing.
Feature AWT (Abstract Window Swing
Toolkit)
Componen Heavyweight: Relies on the Lightweight: Components are
t Type native OS's GUI components written purely in Java, without
(peers). native peers.
Platform Look and feel is determined by Has a pluggable look and feel
Dependen the OS, leading to variations. (PLAF), ensuring a consistent
ce appearance across platforms.
Componen Provides a basic, limited set of Offers a much richer and more
t Set components (Button, Frame). advanced set (JTable, JTree,
JProgressBar).
Flexibility Less flexible; does not support Highly flexible; supports
& Features features like transparent transparency, custom borders,
backgrounds or tooltips. tooltips, and more advanced UI
features.
Package & Components are in the java.awt Components are in javax.swing.
Naming package. Names are simple Class names are typically prefixed
(e.g., Button). with a 'J' (e.g., JButton).
2. Explain the Java Delegation Event Model (Event Source, Event Object,
Event Listener).
The Java Delegation Event Model is the standard mechanism for handling user
interactions in a GUI. It is designed to be efficient and to decouple the application
logic from the user interface components by separating the roles into three distinct
parts.
1. Event Source: This is the GUI component that originates or "fires" an event. It
is the object with which the user interacts. For example, a JButton is the
source of an ActionEvent when it is clicked. The source object is responsible
for creating an event object and maintaining a list of listeners that are
interested in its events.
2. Event Object: When an interaction occurs, the system creates an object to
encapsulate all information about that event. This object is an instance of a
class extending java.util.EventObject. The event object is passed to the
listener's handler method and contains all the necessary context about what
happened. For example, a MouseEvent contains the X/Y coordinates of the
mouse click, while an ActionEvent contains the command string of the action.
3. Event Listener: This is an object designed to "listen" for and respond to
events. To be a listener, a class must implement a specific listener interface
(e.g., ActionListener, MouseListener). The listener must be registered with an
event source using an add...Listener() method (e.g.,
button.addActionListener(myListener);). When the event occurs, the source
calls the appropriate method on the listener (e.g., actionPerformed()), passing
the event object as an argument. The listener's method contains the code that
performs the desired action.
This model is called a "delegation" model because the event source delegates the
task of handling the event to its registered listeners.
1
3. What are adapter classes and why are they useful? Provide WindowAdapter
as an example.
An adapter class is an abstract class in Java's GUI frameworks that provides a
default, empty implementation of all methods in a corresponding event listener
interface.
Why They Are Useful:
Their primary benefit is code simplification and readability. Many listener
interfaces, like WindowListener, contain multiple methods (seven in this case). If a
developer only needs to handle one of these events (e.g., the window closing), but
implements the interface directly, they are forced to provide empty method bodies
for all the other methods. This leads to verbose and cluttered code.
By extending an adapter class instead, the developer only needs to override the
specific method(s) they are interested in. This makes the code cleaner and more
focused.
Example using WindowAdapter:
If you want to exit an application when its window's 'X' button is clicked, you only
care about the windowClosing event.
Generated java
// Using an adapter is clean and concise. We only implement the method we
need.
myFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Without the adapter, you would have to implement windowOpened, windowClosed,
windowIconified, and four other methods with empty bodies, which is unnecessary
and adds clutter.
6. What is a WindowEvent? List and explain at least three key methods from
the WindowListener interface.
A WindowEvent is an event object that signals a change in the state of a window
(JFrame, JDialog). It is handled by listeners that implement the WindowListener
interface.
Key WindowListener Methods:
1. windowClosing(WindowEvent e): This is the most commonly used method.
It is called when the user attempts to close the window (e.g., by clicking the 'X'
button). This is the ideal place to put code to exit the application
(System.exit(0)) or to prompt the user to save their work before closing.
2. windowOpened(WindowEvent e): This method is called only once, the very
first time a window is made visible. It is useful for performing one-time
initialization tasks that need to happen after the UI is visible, such as setting
focus to a specific component.
3. windowActivated(WindowEvent e): This method is called whenever the
window becomes the active window (i.e., gains focus). This is useful for
resuming activities or refreshing data when the user switches back to the
application.
3
7. Differentiate between Statement and PreparedStatement.
Feature Statement PreparedStatement
Compilati The SQL query is compiled by The SQL query is pre-compiled
on the database every single time it once by the database, and the
is executed. plan is cached for reuse.
Performan Slower for queries that are Faster for repeated queries, as
ce executed multiple times due to only the new parameter values
repeated compilation. are sent to the database.
Security Vulnerable to SQL Injection Prevents SQL Injection attacks
attacks because parameters by treating parameters as literal
are often concatenated into the data, not executable code.
SQL string.
Parameter Parameters are part of the static Uses ? as placeholders for
Handling SQL string. parameters, which are set safely
using setter methods like
setString() and setInt().
Readabilit Suitable only for simple, static Preferred for all SQL queries,
y & Usage SQL with no user input. Code especially those with dynamic
can become messy with string parameters. The code is cleaner
concatenation. and more maintainable.
10. What is a disconnected RowSet (like CachedRowSet) and what are its main
advantages?
Main Advantages:
1. Resource Efficiency and Scalability: Database connections are expensive
and limited resources. By disconnecting after fetching data, a CachedRowSet
frees the connection back to a connection pool, allowing it to be used by other
application threads. This significantly reduces the number of concurrent
connections a server needs, which is critical for building scalable applications.
2. Ideal for Distributed Applications: Because a CachedRowSet is serializable
and does not hold a live database connection, it is the perfect Data Transfer
Object (DTO). A server-side business layer can package query results into a
CachedRowSet and send this lightweight object over the network to a client
tier (like a Swing app), which can then work with the data without needing any
database drivers or a direct connection.
3. Offline Capability: This model is perfect for applications that might not always
have a stable network connection (e.g., mobile or field-service desktop apps).
A user can fetch data when online, work with it offline, and then synchronize
their changes back to the server once the connection is restored.
5
11. Explain the different types of JDBC drivers (Type 1-4).
JDBC drivers are the essential components that enable a Java application to
communicate with a specific database. They act as translators between standard
JDBC calls and the database-specific protocol. There are four architectural types.
1. Type 1: JDBC-ODBC Bridge Driver:
This driver translates JDBC calls into ODBC (Open Database Connectivity)
calls. It requires an ODBC driver to be configured on the client machine. This
type was a useful early solution but is slow due to the two-step translation and
is now obsolete (removed from Java 8).
2. Type 2: Native-API Driver:
This driver is a mix of Java and native code. It uses a vendor-specific native
library (e.g., a .dll or .so file) on the client machine to communicate with the
database. It is faster than Type 1 but is platform-dependent and requires
client-side installation, making deployment more difficult.
3. Type 3: Network-Protocol Driver (Middleware Driver):
This is a pure Java driver on the client-side that sends requests to a
middleware server. The middleware server then translates the request into the
database-specific protocol. While the client is platform-independent, this
architecture adds the complexity of maintaining a separate middleware server.
4. Type 4: Thin Driver (Pure Java Driver):
This is also a 100% pure Java driver. It communicates directly with the
database using the database's native network protocol. It is
platform-independent, easy to deploy (just a single JAR file), and generally
offers the best performance. This is the most common and recommended
type used today.
16. What is Introspection and what is the purpose of the BeanInfo interface?
Introspection is the automatic process by which a tool (like a GUI builder or a
framework) analyzes a JavaBean's class at runtime to discover its properties,
methods, and events.
Purpose of the BeanInfo interface:
While automatic introspection is powerful, sometimes a developer needs more
control. The BeanInfo interface is the mechanism for providing explicit information
about a bean, which overrides the default introspection process.
A developer can create a companion class (e.g., MyBeanBeanInfo for MyBean) that
implements BeanInfo. This allows the developer to:
1. Selectively Expose Features: Hide certain public methods or properties from
a design tool to present a simpler component.
2. Provide Metadata: Associate user-friendly display names, descriptions, and
icons with the bean and its properties.
3. Define Custom Editors: Specify a custom PropertyEditor or Customizer for
configuring complex properties.
4. Resolve Ambiguity: Explicitly define the bean's features if its method names
might confuse the automatic process.
8
17. Differentiate between doGet() and doPost() methods.
Feature doGet() (Handles HTTP GET) doPost() (Handles HTTP POST)
Data Appends data as a query string Sends data within the body of the
Transmiss to the end of the URL. Example: HTTP request. The data is not visible
ion page.jsp?name=john&age=30. in the URL.
Visibility Data is visible in the URL, Data is not visible in the URL,
& Security browser history, and server logs. making it more secure for sending
It is not secure for sensitive sensitive information.
data like passwords.
Data Size Has a strict limit on the amount Has no inherent size limit, making it
Limit of data that can be sent (usually suitable for sending large amounts
around 2-4 KB, depending on of data, including file uploads.
the browser/server).
Idempoten Idempotent. An identical GET Not Idempotent. Making the same
cy request can be made multiple POST request multiple times may
times without changing the result in duplicate data creation or
server's state. It is safe to updates. Browsers warn users
bookmark and refresh. before resubmitting a POST
request.
Intended Primarily used for retrieving data Primarily used for sending data to
Use from the server (e.g., fetching a the server to create or modify
search result, loading a user resources (e.g., submitting a form,
profile). uploading a file, processing a
payment).
9
Translation It is a pure Java class that is It is not run directly. The
Process compiled directly into a .class container first translates the JSP
file and run by the servlet file into a Java servlet source file
container. (.java), then compiles it into a
.class file, and then runs that
servlet.
Maintainabil Difficult to maintain the Easy to maintain the presentation
ity presentation layer, as UI layer. UI changes can be made
changes require modifying directly in the JSP file, similar to
and recompiling Java code. editing an HTML file.
11
23. Explain the three types of JSP scripting elements, describing the syntax
for each.
JSP scripting elements are tags that allow developers to embed Java code directly
into a JSP page. When the JSP is translated into a servlet, this Java code is placed
into the generated servlet class.
1. Declaration Tag:
○ Syntax: <%! ... %>
○ Purpose: Used to declare class-level variables and methods for the
generated servlet. The code inside this tag is placed outside the
_jspService() method, at the member level of the class. Variables
declared here are shared across all requests and are not thread-safe.
○ Example:
<%! private int hitCounter = 0; %>
<%! public String sayHello() { return "Hello!"; } %>
2. Scriptlet Tag:
○ Syntax: <% ... %>
○ Purpose: Used to embed arbitrary Java code statements. The code
inside this tag is placed directly inside the _jspService() method. This is
where most processing logic, such as loops, if-statements, and method
calls, goes. Variables declared here are local to the request.
○ Example:
<% String name = request.getParameter("name");
if (name != null) {
out.println("Hello, " + name); } %>
3. Expression Tag:
○ Syntax: <%= ... %>
○ Purpose: Used to evaluate a single Java expression, convert its result
to a String, and print it directly to the HTML output stream. It is a
convenient shortcut for out.print(...). The expression must not end with a
semicolon.
○ Example:
<p>The current time is: <%= new java.util.Date() %></p>
<p>Your total is: <%= 2 + 2 %></p>
24. What is a JSP directive? Explain the purpose of the page and include
directives.
A JSP directive is a message for the JSP container that provides overall
instructions on how to translate the JSP page into a servlet. Directives do not
produce any direct output to the client but instead control the structure and behavior
of the generated servlet class. The syntax is always <%@ directive ... %>.
1. page Directive (<%@ page ... %>)
The page directive is used to define attributes that apply to the entire JSP page. It
can appear multiple times on a page, but it is best practice to consolidate them into
one tag at the top.
● Purpose: It controls page-level settings.
● Key Attributes:
○ import: Specifies a comma-separated list of Java packages or classes
that need to be imported for the servlet (e.g.,
import="java.util.*,java.sql.Connection").
○ contentType: Sets the MIME type and character encoding of the
response (e.g., contentType="text/html; charset=UTF-8").
12
○ session: A boolean (true or false) that indicates whether the page should
participate in an HTTP session. The default is true.
○ errorPage: Specifies the URL of another JSP page that will handle any
uncaught exceptions thrown from this page.
2. include Directive (<%@ include ... %>)
The include directive is used to include the content of another file (which can be
HTML, JSP, or plain text) into the current JSP page at translation time.
● Purpose: It is used to create reusable, static page fragments like headers,
footers, or navigation menus.
● Mechanism: The content of the included file is literally pasted into the main
JSP file before the container translates it into a servlet. This results in a single,
larger servlet class. This is also known as a "static include."
● Syntax:
<%@ include file="header.html" %>
<!-- Main page content here -->
<%@ include file="footer.jsp" %>
25. What are Cookies and how are they created and added to the response in a
servlet?
Cookies are small pieces of textual data that a servlet sends to a client's web
browser. The browser stores this information and is designed to send it back to the
same server with every subsequent request. They are a fundamental mechanism for
session management (though less secure than HttpSession), for storing user
preferences, and for tracking user behavior.
How They Are Created and Added in a Servlet:
The process involves two main steps on the server-side:
1. Create a Cookie Object:
You instantiate the javax.servlet.http.Cookie class. The constructor takes two string
arguments: the cookie's name and its value. Cookie names should not contain
whitespace or special characters.
Cookie themeCookie = new Cookie("userPreference", "darkMode");
2. Configure Cookie Properties (Optional but Recommended):
Before sending the cookie, you can set its attributes to control its lifespan and
scope.
○ setMaxAge(int expiryInSeconds): This is the most important attribute. It
sets the cookie's lifespan in seconds.
■ A positive value makes it a persistent cookie, stored on the user's
hard drive until it expires.
■ A negative value (the default) makes it a session cookie, which is
deleted when the browser closes.
■ A value of zero instructs the browser to delete the cookie
immediately.
themeCookie.setMaxAge(24 * 60 * 60);
○ setPath(String uri): This restricts the cookie to a specific path on the
server. For example, setPath("/app") means the cookie will only be sent
for requests to /app and its subdirectories.
3. Add the Cookie to the HttpServletResponse:
This is the final step that actually sends the cookie to the browser. You use the
addCookie() method of the response object. This causes the servlet container to
add a Set-Cookie header to the HTTP response.
response.addCookie(themeCookie);
13
Complete Example Snippet:
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException {
// 1. Create the cookie
Cookie userNameCookie = new Cookie("userName", "john_doe");
// 2. Configure it to be persistent for 7 days
userNameCookie.setMaxAge(7 * 24 * 60 * 60);
// 3. Add it to the response
response.addCookie(userNameCookie);
response.getWriter().println("Username cookie has been set!"); }
26. What are Java Web Frameworks? Give two examples and explain their
purpose.
A Java Web Framework is a software library that provides a structured way to build
web applications, web services, and APIs. It reduces the need to write repetitive
code by offering built-in tools and best practices.
Purpose of Frameworks:
Frameworks automate and streamline common tasks by providing proven solutions
for:
● Request Routing and MVC: Handling incoming HTTP requests and routing
them to the correct controller logic, implementing the Model-View-Controller
(MVC) pattern cleanly.
● Database Interaction: Often including an Object-Relational Mapping (ORM)
tool (like Hibernate via JPA) to map Java objects to database tables,
abstracting away raw JDBC code.
● Dependency Injection: Managing the creation and lifecycle of objects and
their dependencies, leading to loosely coupled and more testable code.
● Security: Providing built-in support for authentication (who you are) and
authorization (what you are allowed to do).
● Session Management: Offering robust and configurable session
management.
● Form Validation and Data Binding: Automatically binding incoming form
data to Java objects and validating it against defined rules.
Two Key Examples:
1. Spring Framework (and Spring Boot):
○ The most popular framework in the Java ecosystem. It is built on the
principle of Dependency Injection. Spring Boot is an extension that
simplifies the creation of stand-alone, production-ready web applications
with minimal configuration, making it the standard for modern Java web
development and microservices.
2. Jakarta EE (formerly Java EE):
○ A set of specifications rather than a single framework. It provides a
standard for building large-scale enterprise applications. Key
specifications include JPA (for database interaction), JAX-RS (for REST
APIs), and JSF (for user interfaces). Application servers like WildFly or
GlassFish implement these standards.
14
27. Explain the RMI architecture, defining the roles of the Client, Server, Stub,
Skeleton, and RMI Registry.
RMI (Remote Method Invocation) architecture is a layered system that enables a
Java object in one JVM to invoke methods on an object in another JVM. It is
designed to make this remote interaction appear local to the developer.
Key Components and Their Roles:
1. Client:
○ Role: The application that initiates the remote call. It needs to perform a
specific task but the logic for that task resides on a remote server.
○ Interaction: The client code does not directly communicate with the
remote object. Instead, it holds a reference to a local Stub object and
calls methods on it.
2. Server:
○ Role: The application that creates and hosts the remote object. It is
responsible for making the object available for remote access and
waiting for clients to connect.
○ Interaction: The server creates an instance of the remote object's
implementation and registers it with the RMI Registry.
3. RMI Registry:
○ Role: A simple, server-side naming service. It acts as a directory where
the server can register its remote objects with a unique, human-readable
name.
○ Interaction: The server binds its object to the registry. The client looks
up the object in the registry using its name to get the initial reference
(the stub). It is the central meeting point that bootstraps the
communication.
4. Stub (Client-Side Proxy):
○ Role: The Stub resides on the client machine and acts as a local
representative for the remote object.
○ Interaction: When the client calls a method, the Stub intercepts the call.
It performs marshalling (packaging the method arguments into a byte
stream), sends the request over the network, waits for the response, and
then unmarshals the return value for the client.
5. Skeleton (Server-Side Dispatcher):
○ Role: The Skeleton resides on the server. Its job is to be the point of
contact for incoming client requests.
○ Interaction: It receives the request from the stub, unmarshals the
arguments, calls the appropriate method on the actual remote object
implementation, and then marshals the return value to send back to the
stub.
28. What is the role of the remote interface in RMI? List the rules it must
follow.
The remote interface is the absolute cornerstone of an RMI application. It defines
the contract between the client and the server, specifying exactly which methods a
client is allowed to invoke on the remote server object.
The Role of the Remote Interface:
1. Defines the Service Contract: It provides an abstract definition of the service
being offered. It lists the exact signatures of all the remote methods, including
their parameter types and return types. This is the only part of the server's
logic that the client needs to know about.
15
2. Enables Proxy Generation (Type Safety): The RMI compiler (rmic, though
now often automatic) uses this interface to generate the client-side stub. The
stub is a proxy class that implements this same remote interface. This is
critical because it allows the client code to be written and compiled against the
interface, providing full compile-time type safety. The client can treat the stub
just like any other object that implements the interface.
3. Abstraction: It completely hides the server-side implementation details from
the client. The client has no knowledge of the concrete class that implements
the interface on the server; it only interacts with the methods defined in the
interface.
Rules a Remote Interface Must Follow:
1. Must be public: The interface must be declared with the public access
modifier so that clients, which may be in different packages, can access it.
2. Must extend java.rmi.Remote: It must extend the java.rmi.Remote interface.
This is a marker interface (it has no methods) that signals to the RMI system
that this interface is intended for remote invocation.
Every Method Must Throw RemoteException: RemoteException must be
thrown by all remote methods to handle possible network failures like server crashes
or connection loss. It's required for safe remote communication in RMI.
import java.rmi.*;
public interface MyRemoteService extends Remote {
String performTask(String param) throws RemoteException; }
17
network socket, or exiting the JVM), the Java runtime consults the Security
Manager.
● Policy File: The Security Manager, in turn, consults a security policy file.
This is a plain text file written by the system administrator that explicitly grants
specific permissions to code from specific locations. For example, a policy file
might state, "Code downloaded from server.example.com is allowed to
connect back to that host on port 80, but it is not allowed to read any local
files."
● Enforcement: If the operation is permitted by the policy file, the Security
Manager allows it to proceed. If it is not permitted, the Security Manager
throws a java.lang.SecurityException, and the operation is blocked.
Why it is Important:
Without a Security Manager, any downloaded RMI code would run with the same full
permissions as the client application itself, creating a massive security hole. It could
read sensitive files, delete data, or connect to other machines on the network.
While often omitted in simple "localhost" examples for convenience, installing a
Security Manager (System.setSecurityManager(new RMISecurityManager());) and
defining a proper policy file are essential steps for deploying a secure,
production-ready RMI application that interacts with remote, untrusted code sources.
18
● fill() methods create solid shapes: g2d.fillRect(x, y, width, height);,
g2d.fillOval(...).
● You can also create Shape objects (like new Rectangle2D.Double(...)) and
pass them to g2d.draw(shape) or g2d.fill(shape).
Displaying Images
Method 1: Using ImageIcon and JLabel (The Simple Way)
This is the easiest and most common method for displaying static images.
Create an ImageIcon: Create an instance of javax.swing.ImageIcon, passing the
path to your image file.
Generated java
ImageIcon icon = new ImageIcon("path/to/my_image.png");
Create a JLabel: Create a JLabel and pass the ImageIcon object to its constructor.
Generated java
JLabel imageLabel = new JLabel(icon);
Add to Container: Add the JLabel to your JFrame or JPanel. The label will
automatically size itself to fit the image.
Method 2: Using Graphics.drawImage() (The Controlled Way)
This method is used when you need to draw an image as part of a custom
component, giving you precise control over its position and size.
Load the Image: Load the image into a java.awt.Image object. This is often done in
the constructor of your custom panel to avoid re-loading the image on every repaint.
Generated java
private Image myImage;
public DrawingCanvas() {
try {
myImage = ImageIO.read(new File("path/to/my_image.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
Draw the Image in paintComponent: Inside the paintComponent method, call the
drawImage() method of the Graphics object.
Generated java
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (myImage != null) {
// Draws the image at coordinates (x, y)
g.drawImage(myImage, 10, 10, this);
}}
19
1. Write a complete Java program to create a data entry form using JFrame,
JLabel, JTextField, JRadioButton, ButtonGroup, and JButton. The program
should handle a button click to display the collected data.
This program creates a simple employee registration form. It uses various Swing
components to collect user data and an ActionListener to display a summary of the
entered information in a dialog box when the "Register" button is clicked.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DataEntryForm extends JFrame implements ActionListener {
// Declare components as instance variables to access them in the event handler
private JTextField txtName, txtEmail;
private JRadioButton rbMale, rbFemale;
private ButtonGroup genderGroup;
private JButton btnRegister;
public DataEntryForm() {
// --- Frame Setup ---
setTitle("Employee Registration Form");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window
// --- Panel and Layout Setup ---
// Use a panel with a grid layout for organized component placement
JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); // Add
padding
// --- Component Creation and Addition ---
// Name Field
panel.add(new JLabel("Full Name:"));
txtName = new JTextField();
panel.add(txtName);
// Email Field
panel.add(new JLabel("Email Address:"));
txtEmail = new JTextField();
panel.add(txtEmail);
// Gender Radio Buttons
panel.add(new JLabel("Gender:"));
JPanel genderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); //
A sub-panel for radio buttons
rbMale = new JRadioButton("Male", true); // Default selection
rbFemale = new JRadioButton("Female");
genderGroup = new ButtonGroup(); // Ensures only one radio button can be
selected
genderGroup.add(rbMale);
genderGroup.add(rbFemale);
genderPanel.add(rbMale);
genderPanel.add(rbFemale);
panel.add(genderPanel);
// Register Button
panel.add(new JLabel()); // Placeholder for grid alignment
btnRegister = new JButton("Register");
btnRegister.addActionListener(this); // Register this class to handle its events
panel.add(btnRegister);
// --- Finalize Frame ---
this.add(panel);
this.setVisible(true);
}
20
// --- Event Handling Logic ---
@Override
public void actionPerformed(ActionEvent e) {
// This method is called when btnRegister is clicked
if (e.getSource() == btnRegister) {
// 1. Gather data from the form components
String name = txtName.getText();
String email = txtEmail.getText();
String gender = rbMale.isSelected() ? "Male" : "Female";
// 2. Perform simple validation
if (name.isEmpty() || email.isEmpty()) {
JOptionPane.showMessageDialog(this, "Name and Email cannot be
empty.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// 3. Construct and display the summary message
String message = "Registration Details:\n\n"
+ "Name: " + name + "\n"
+ "Email: " + email + "\n"
+ "Gender: " + gender;
JOptionPane.showMessageDialog(this, message, "Registration Successful",
JOptionPane.INFORMATION_MESSAGE);
}
}
// --- Main Method ---
public static void main(String[] args) {
// Run the GUI on the Event Dispatch Thread for thread safety
SwingUtilities.invokeLater(() -> new DataEntryForm());
}
}
2. Write a GUI application that performs a calculation based on user input and
events (e.g., a simple BMI calculator or currency converter).
This program creates a simple currency converter that converts an amount from
USD to either NPR or INR based on a user's selection. It demonstrates getting input
from a text field, checking the state of radio buttons, and displaying a formatted
result in a label.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CurrencyConverter extends JFrame implements ActionListener {
// Declare GUI components
private JTextField txtAmountUSD;
private JRadioButton rbToNPR, rbToINR;
private ButtonGroup currencyGroup;
private JButton btnConvert;
private JLabel lblResult;
// Fixed conversion rates
private static final double USD_TO_NPR = 133.0;
private static final double USD_TO_INR = 83.0;
public CurrencyConverter() {
setTitle("Simple Currency Converter");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.CENTER, 10, 20));
21
setLocationRelativeTo(null);
// --- Component Creation ---
add(new JLabel("Amount in USD:"));
txtAmountUSD = new JTextField(10);
add(txtAmountUSD);
// Radio buttons for currency selection
rbToNPR = new JRadioButton("To NPR", true);
rbToINR = new JRadioButton("To INR");
currencyGroup = new ButtonGroup();
currencyGroup.add(rbToNPR);
currencyGroup.add(rbToINR);
add(rbToNPR);
add(rbToINR);
// Convert button
btnConvert = new JButton("Convert");
btnConvert.addActionListener(this);
add(btnConvert);
// Result label
lblResult = new JLabel("Result will be shown here.");
lblResult.setFont(new Font("Arial", Font.BOLD, 14));
add(lblResult);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnConvert) {
try {
// Get amount from text field
double amountUSD = Double.parseDouble(txtAmountUSD.getText());
double convertedAmount;
String currencySymbol;
// Check which radio button is selected and perform calculation
if (rbToNPR.isSelected()) {
convertedAmount = amountUSD * USD_TO_NPR;
currencySymbol = "NPR";
} else {
convertedAmount = amountUSD * USD_TO_INR;
currencySymbol = "INR";
}
// Display the formatted result
lblResult.setText(String.format("Result: %.2f %s", convertedAmount,
currencySymbol));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Please enter a valid number.",
"Input Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CurrencyConverter());
}
}
22
3. Write a complete Java program to INSERT multiple records into a database
table using PreparedStatement inside a loop.
This program demonstrates how to efficiently insert multiple records into a books
table. Using a PreparedStatement inside a loop is the standard, secure, and
performant way to handle such bulk operations.
Prerequisites: A database named library with a table books (isbn VARCHAR(20)
PRIMARY KEY, title VARCHAR(100), author VARCHAR(100)).
Generated java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class BatchInsertBooks {
private static final String DB_URL = "jdbc:mysql://localhost:3306/library";
private static final String DB_USER = "root";
private static final String DB_PASS = "password";
public static void main(String[] args) {
// Data to be inserted
String[][] booksData = {
{"978-0321765723", "The C++ Programming Language", "Bjarne
Stroustrup"},
{"978-0132350884", "Clean Code", "Robert C. Martin"},
{"978-0201633610", "Design Patterns", "Erich Gamma et al."}
};
String sql = "INSERT INTO books (isbn, title, author) VALUES (?, ?, ?)";
// Using try-with-resources for automatic resource management
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER,
PASS);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
System.out.println("Inserting book records...");
for (String[] book : booksData) {
// Bind values to the prepared statement
pstmt.setString(1, book[0]); // isbn
pstmt.setString(2, book[1]); // title
pstmt.setString(3, book[2]); // author
// Execute the insert statement
pstmt.executeUpdate();
System.out.println("Inserted: " + book[1]);
}
System.out.println("All records inserted successfully.");
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
e.printStackTrace();
}
}
}
23
4. Write a complete Java program to SELECT records from a database table
and display the results on the console using a while loop on the ResultSet.
This program connects to a database, retrieves all records from an employees table,
and iterates through the ResultSet to print each record's details to the console. It
showcases the fundamental JDBC data retrieval pattern.
Prerequisites: A database named company with a table employees (id INT, name
VARCHAR(100), department VARCHAR(50)).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SelectAllEmployees {
private static final String DB_URL = "jdbc:mysql://localhost:3306/company";
private static final String DB_USER = "root";
private static final String DB_PASS = "password";
public static void main(String[] args) {
String sql = "SELECT id, name, department FROM employees";
// Using try-with-resources to ensure resources are closed automatically
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER,
PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
System.out.println("Employee List:");
System.out.println("----------------------------------------");
// Loop through the result set until rs.next() returns false
while (rs.next()) {
// Retrieve data from the current row by column name
int id = rs.getInt("id");
String name = rs.getString("name");
String department = rs.getString("department");
// Display the retrieved values
System.out.printf("ID: %-4d | Name: %-20s | Department: %s%n", id,
name, department);
}
System.out.println("----------------------------------------");
} catch (SQLException e) {
System.err.println("Database query failed: " + e.getMessage());
e.printStackTrace();
}
}
}
24
5. Write a GUI application that connects to a database. The UI should have a
text field for a user to enter an ID and a "Search" button. When clicked, the
program should retrieve the corresponding record from the database and
display its details in other text fields.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class EmployeeSearchApp extends JFrame implements ActionListener {
JTextField txtSearchId, txtName, txtSalary;
JButton btnSearch;
private static final String DB_URL = "jdbc:mysql://localhost:3306/company";
private static final String DB_USER = "root";
private static final String DB_PASS = "password";
public EmployeeSearchApp() {
setTitle("Employee Search");
setSize(450, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.add(new JLabel("Enter Employee ID:"));
txtSearchId = new JTextField();
panel.add(txtSearchId);
panel.add(new JLabel("")); // Placeholder
btnSearch = new JButton("Search");
btnSearch.addActionListener(this);
panel.add(btnSearch);
panel.add(new JLabel("Employee Name:"));
txtName = new JTextField();
txtName.setEditable(false);
panel.add(txtName);
this.add(panel);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String idStr = txtSearchId.getText();
if (idStr.isEmpty()) return;
txtName.setText(""); // Clear previous results
String sql = "SELECT name FROM employees WHERE id = ?";
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASS);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, Integer.parseInt(idStr));
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
txtName.setText(rs.getString("name"));
} else {
JOptionPane.showMessageDialog(this, "Employee not found.");
}
}
} catch (SQLException | NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new EmployeeSearchApp());
}}
25
6. Write a servlet that processes an HTML form. The servlet should retrieve at
least two parameters from the request, perform a simple operation, and write
an HTML response back to the client.
This example consists of an HTML form that asks for a first name and a last name,
and a servlet that concatenates them to create a full name and displays a greeting.
1. greeting.html (The Form)
<!DOCTYPE html>
<html>
<head><title>Greeting Form</title></head>
<body>
<h2>Enter Your Name</h2>
<form action="greet" method="post">
First Name: <input type="text" name="firstName"><br><br>
Last Name: <input type="text" name="lastName"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
2. GreetingServlet.java (The Servlet)
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/greet")
public class GreetingServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// 1. Retrieve the parameters from the request
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
// 2. Perform a simple operation
String fullName = firstName + " " + lastName;
// 3. Set the response content type
response.setContentType("text/html");
// 4. Write the HTML response back to the client
try (PrintWriter out = response.getWriter()) {
out.println("<html>");
out.println("<head><title>Greeting</title></head>");
out.println("<body>");
out.println("<h1>Hello, " + fullName + "!</h1>");
out.println("<p>Welcome to our servlet application.</p>");
out.println("</body>");
out.println("</html>");
}
}
}
26
7. Write a JSP page that uses HttpSession to manage state (e.g., a page hit
counter that increments and displays a count specific to the user's current
session).
This JSP page will track how many times a user has visited it within a single browser
session. It uses the HttpSession object to store a counter, incrementing it on each
page load.
SessionCounter.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ page import="java.util.Date" %>
<!DOCTYPE html>
<html>
<head>
<title>Session Hit Counter</title>
<style>
body { font-family: sans-serif; text-align: center; margin-top: 50px; }
.counter { font-size: 2em; color: navy; font-weight: bold; }
</style>
</head>
<body>
<h1>Welcome to the Session Tracking Page!</h1>
<p>This page demonstrates how HttpSession works.</p>
<hr>
<%
// 1. Get the session object. The 'true' argument creates a new session if one
doesn't exist.
HttpSession currentSession = request.getSession(true);
// 2. Try to retrieve the counter attribute from the session.
// It will be null on the first visit of the session.
Integer hitCount = (Integer) currentSession.getAttribute("pageHitCounter");
// 3. Check if the counter exists. If not, initialize it.
if (hitCount == null) {
hitCount = 1; // It's the first hit
} else {
// If it exists, increment it.
hitCount = hitCount + 1;
}
// 4. Store the new (or initial) count back into the session attribute.
currentSession.setAttribute("pageHitCounter", hitCount);
%>
<h3>You have visited this page <span class="counter"><%= hitCount %></span>
time(s) during this session.</h3>
<p>(Refresh the page to see the counter increase. Close and reopen your
browser to start a new session.)</p>
<br>
<p>Your Session ID is: <%= currentSession.getId() %></p>
<p>Session created at: <%= new Date(currentSession.getCreationTime())
%></p>
</body>
</html>
27
8. Write a JSP page (the view) and a Servlet (the controller) that work together
using the MVC pattern. The servlet should process a request, set an attribute,
and then forward the request to the JSP for display.
This example demonstrates a simple MVC flow. A servlet acts as the controller,
creates some data (a list of names), puts it in the request scope, and then forwards
the request to a JSP page, which acts as the view to display the data.
1. UserServlet.java (The Controller)
Generated java
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/users")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// 1. (Model) Create some data. In a real app, this would come from a
database.
List<String> userList = new ArrayList<>();
userList.add("Alice");
userList.add("Bob");
userList.add("Charlie");
// 2. (Controller) Set the data as a request attribute.
// The JSP will be able to access this attribute.
request.setAttribute("users", userList);
// 3. (Controller) Get the RequestDispatcher for the target JSP page.
RequestDispatcher dispatcher =
request.getRequestDispatcher("/displayUsers.jsp");
// 4. Forward the request and response objects to the JSP.
// The control is transferred on the server-side.
dispatcher.forward(request, response);
}
}
9. Write a complete client-server application using RMI. This must include all
four parts: the Remote Interface, the Implementation class, the Server
program, and the Client program.
This example creates a simple RMI service that returns the current server date and
time.
1. DateTimeService.java (The Remote Interface)
Defines the contract for the remote service.
Generated java
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Date;
// 1. Must be public and extend java.rmi.Remote
public interface DateTimeService extends Remote {
// 2. Every method must throw RemoteException
Date getCurrentDateTime() throws RemoteException;
}
2. DateTimeServiceImpl.java (The Implementation)
Provides the concrete logic for the remote method.
Generated java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;
// 1. Must implement the remote interface
// 2. Must extend UnicastRemoteObject to handle remote communication
public class DateTimeServiceImpl extends UnicastRemoteObject implements
DateTimeService {
// 3. Must have a constructor that throws RemoteException
public DateTimeServiceImpl() throws RemoteException {
super();
}
// Provide the implementation for the remote method
@Override
public Date getCurrentDateTime() throws RemoteException {
System.out.println("Server: A client requested the current date and time.");
return new Date();
}
29
}
3. Server.java (The RMI Server)
Creates an instance of the implementation, starts the RMI registry, and binds the
object to it.
Generated java
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class Server {
public static void main(String[] args) {
try {
// 1. Create an instance of the remote object
DateTimeServiceImpl dateTimeService = new DateTimeServiceImpl();
// 2. Start the RMI registry on a specific port (e.g., 1099)
LocateRegistry.createRegistry(1099);
// 3. Bind the remote object to the registry with a unique name
Naming.rebind("rmi://localhost:1099/DateTimeService", dateTimeService);
System.out.println("Date Time Server is running and waiting for clients...");
} catch (Exception e) {
System.err.println("Server exception: " + e.getMessage());
e.printStackTrace();
}
}
}
30
10: RMI Application with Primitive Data Types and Logic
Write a complete client-server application using RMI. The client should send two
integers to the server. The server should calculate their sum and return the result to
the client.
1. Calculator.java (The Remote Interface)
import java.rmi.Remote;
import java.rmi.RemoteException;
// Defines the service contract.
public interface Calculator extends Remote {
// A remote method to add two integers.
int add(int a, int b) throws RemoteException;
}
32
11: RMI Application with Custom Serializable Objects
Write a complete client-server application using RMI. The client should send a User
object (containing a username and password) to the server. The server should have
a remote method authenticate(User user) that checks if the credentials are valid and
returns a boolean.
1. User.java (The Custom Data Type)
import java.io.Serializable;
33
// Simple, hard-coded validation logic for the example.
if ("admin".equals(user.getUsername()) &&
"password123".equals(user.getPassword())) {
System.out.println("Server: Authentication successful.");
return true;
} else {
System.out.println("Server: Authentication failed.");
return false;
}
}
}
4. Server.java
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class Server {
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099);
Naming.rebind("AuthService", new AuthenticatorImpl());
System.out.println("Authentication Server is ready.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
5. Client.java
import java.rmi.Naming;
public class Client {
public static void main(String[] args) {
try {
// Look up the remote service.
Authenticator authService = (Authenticator)
Naming.lookup("rmi://localhost/AuthService");
// Create an instance of the custom Serializable object.
User userToAuth = new User("admin", "password123");
// Pass the custom object as an argument in the remote call.
boolean isAuthenticated = authService.authenticate(userToAuth);
// Check the result from the server.
if (isAuthenticated) {
System.out.println("Client: Login successful!");
} else {
System.out.println("Client: Login failed. Invalid credentials.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
34