0% found this document useful (0 votes)
7 views36 pages

Final Advanced Java Programming

The document contains a comprehensive set of theory and practical questions related to Java programming, covering topics such as AWT vs. Swing, JDBC, JavaBeans, Servlets, JSP, and RMI. It includes detailed explanations of concepts like event handling, layout managers, and database interactions, as well as practical coding tasks for GUI applications and database operations. The questions aim to assess both theoretical knowledge and practical skills in Java development.

Uploaded by

aimakeryt99
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)
7 views36 pages

Final Advanced Java Programming

The document contains a comprehensive set of theory and practical questions related to Java programming, covering topics such as AWT vs. Swing, JDBC, JavaBeans, Servlets, JSP, and RMI. It includes detailed explanations of concepts like event handling, layout managers, and database interactions, as well as practical coding tasks for GUI applications and database operations. The questions aim to assess both theoretical knowledge and practical skills in Java development.

Uploaded by

aimakeryt99
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
You are on page 1/ 36

Theory Questions [ Page No: 1-19 ]

1.​ Differentiate between AWT and Swing.


2.​ Explain the Java Delegation Event Model (Event Source, Event Object, Event
Listener).
3.​ What are adapter classes and why are they useful? Provide WindowAdapter
as an example.
4.​ Explain the purpose and behavior of BorderLayout, FlowLayout, and
GridLayout.
5.​ What is the role of JPanel in building a user interface?
6.​ What is a WindowEvent? List and explain at least three key methods from the
WindowListener interface.
7.​ Differentiate between Statement and PreparedStatement.
8.​ Explain the main steps for executing a JDBC query.
9.​ Explain the difference between ResultSet and RowSet.
10.​ What is a disconnected RowSet (like CachedRowSet) and what are its
main advantages?
11.​ Explain the different types of JDBC drivers (Type 1-4).
12.​ Explain scrollable and updatable ResultSets.
13.​ What is a JavaBean? List its main design conventions.
14.​ Explain Simple, Boolean, and Indexed properties in JavaBeans.
15.​ Differentiate between Bounded and Constrained properties.
16.​ What is Introspection and what is the purpose of the BeanInfo interface?
17.​ Differentiate between doGet() and doPost() methods.
18.​ Differentiate between Servlets and JSP.
19.​ What is bean persistence and how is it achieved?
20.​ Explain the life cycle of a servlet (init, service, destroy).
21.​ Explain how HttpSession is used for session tracking.
22.​ Differentiate between RequestDispatcher.forward() and
response.sendRedirect().
23.​ Explain the three types of JSP scripting elements, describing the syntax for
each.
24.​ What is a JSP directive? Explain the purpose of the page and include
directives.
25.​ What are Cookies and how are they created and added to the response in
a servlet?
26.​ What are Java Web Frameworks? Give two examples and explain their
purpose.
27.​ Explain the RMI architecture, defining the roles of the Client, Server, Stub,
Skeleton, and RMI Registry.
28.​ What is the role of the remote interface in RMI? List the rules it must follow.
1
29.​ Explain marshalling and unmarshalling in the context of a distributed
system like RMI.
30.​ Differentiate between RMI and CORBA.
31.​ What is the purpose of the RMI Security Manager?
32.​ Explain how to draw 2D shapes and display images in Swing.

Practical (Code) Questions [ Page No: 20-34 ]

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.

4. Explain the purpose and behavior of BorderLayout, FlowLayout, and


GridLayout.
These are three fundamental layout managers in Swing used to arrange
components within a container.
●​ BorderLayout:
○​ Purpose: Divides a container into five distinct regions: NORTH, SOUTH,
EAST, WEST, and CENTER. It is the default for JFrame.
○​ Behavior: NORTH and SOUTH components expand horizontally. EAST
and WEST components expand vertically. CENTER expands to fill all
remaining space. It is ideal for classic application window layouts
(toolbar, status bar, main content area).
●​ FlowLayout:
○​ Purpose: Arranges components in a row, left to right, like words on a
page. It is the default for JPanel.
○​ Behavior: When a row is full, it "flows" to the next. It respects the
preferred size of components and does not stretch them. The alignment
within the row can be set to left, right, or center. It is perfect for arranging
a series of buttons in a toolbar.
●​ GridLayout:
○​ Purpose: Arranges components in a rectangular grid where every cell is
of equal size.
2
○​ Behavior: It forces every component to be the exact same size,
resizing them to completely fill their cell. It ignores the component's
preferred size.
○​ Use Case: Ideal for layouts where a uniform grid is needed, such as a
calculator keypad or a checkerboard.

5. What is the role of JPanel in building a user interface?


A JPanel is a generic, lightweight container that acts as a fundamental building
block for organizing a Swing GUI. Its key roles are:
1.​ Grouping Components: It is used to group related components together,
creating a logical structure that makes the UI easier to manage. For example,
a login form might have its username and password fields in one panel and its
buttons in another.
2.​ Nesting Layouts: This is its most powerful feature. A single layout manager is
often insufficient for a complex UI. JPanels allow you to nest layouts within
each other. For example, a JFrame with BorderLayout can contain a JPanel in
its center that itself uses a GridLayout. This allows for the creation of
sophisticated and responsive user interfaces.
3.​ Custom Drawing: By extending JPanel and overriding its
paintComponent(Graphics g) method, it can be used as a canvas for custom
2D drawing, such as for charts, games, or other graphics. The drawing logic is
encapsulated within the panel.
4.​ Creating Reusable Components: You can encapsulate a part of your UI into
a JPanel subclass, creating a reusable component that can be easily added to
different windows in your application, promoting modularity and code reuse.

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.

8. Explain the main steps for executing a JDBC query.


Executing a database query using JDBC involves a standard, sequential process to
ensure proper connection, execution, and resource cleanup. There are five main
steps:
1.​ Load and Register the JDBC Driver: This step loads the database-specific
driver class into memory so the DriverManager can use it. This is often done
with Class.forName("com.mysql.cj.jdbc.Driver");, although it's automatic with
modern Type 4 drivers.
2.​ Establish a Connection: A connection session is created with the database
using DriverManager.getConnection(url, user, pass). This method returns a
Connection object, which is the foundation for all subsequent database
communication.
3.​ Create a Statement Object: The Connection object is used to create a
Statement or PreparedStatement object. This object acts as a container for the
SQL query that will be sent to the database. PreparedStatement is the
preferred choice.
4.​ Execute the Query: The Statement object is used to execute the SQL
command.
○​ executeQuery() is used for SELECT statements and returns a ResultSet.
○​ executeUpdate() is used for INSERT, UPDATE, or DELETE statements
and returns an integer count of affected rows.
5.​ Process ResultSet and Close Resources: If data was retrieved, you iterate
through the ResultSet using a while(rs.next()) loop to access the data.
Crucially, all resources (ResultSet, Statement, Connection) must be closed in
a finally block or using a try-with-resources statement to prevent resource
leaks.
4
9. Explain the difference between ResultSet and RowSet.
Feature ResultSet RowSet
1. Connected: Always needs a Can be Disconnected: Can hold data
Connection live database connection. offline without a live connection.
2. Type A simple data cursor. A JavaBean component that can fire
events.
3. Network Not Serializable: Cannot be Serializable: Can be sent over a
sent over a network. network (as a DTO).
4. Scrolling Forward-only by default. Scrollable by default.
5. Data Only from a JDBC database From a database, spreadsheet, or
Source query. other tabular source.

10. What is a disconnected RowSet (like CachedRowSet) and what are its main
advantages?

A disconnected RowSet is a specialized type of RowSet that, after being populated


with data, does not maintain a live connection to the data source. The standard
implementation provided by the JDK is the javax.sql.rowset.CachedRowSet.
How it Works:
1.​ It establishes a connection to a database.
2.​ It executes a query and populates its internal cache by reading all the rows
from the resulting ResultSet.
3.​ It then closes the database connection.
4.​ The application can now work with this in-memory CachedRowSet offline. It
can scroll through it, update values, insert new rows, and delete existing ones.
5.​ Optionally, it can later reconnect to the database and call the acceptChanges()
method to synchronize all modifications back to the original data source.

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.

12. Explain scrollable and updatable ResultSets.


By default, a standard ResultSet is forward-only and read-only. Scrollable and
updatable ResultSets are advanced JDBC features that provide much greater
flexibility.
Scrollable ResultSet:​
A scrollable ResultSet allows the cursor to move freely within its rows, not just
forward. This is specified when creating the Statement.
●​ Key Types:
○​ ResultSet.TYPE_SCROLL_INSENSITIVE: The ResultSet is a static
snapshot of the data. It is "insensitive" to any changes made by other
transactions after it was created.
○​ ResultSet.TYPE_SCROLL_SENSITIVE: The ResultSet is dynamic. It is
"sensitive" to changes and attempts to reflect updates and deletes made
by others.
●​ Navigation Methods: It provides methods like previous(), first(), last(), and
absolute(int row) to navigate the data freely.
Updatable ResultSet:​
An updatable ResultSet allows you to modify the data in the database directly
through the ResultSet object itself.
Creation: It must be created with the ResultSet.CONCUR_UPDATABLE
concurrency type.​
Generated java​
Statement stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
6
●​ Modification Methods:
○​ Updating: Navigate to a row, call updateString("col", "newValue"), and
then call updateRow().
○​ Inserting: Call moveToInsertRow(), use updateXxx() methods to set
values for the new row, and then call insertRow().
○​ Deleting: Navigate to a row and call deleteRow().

13. What is a JavaBean? List its four main design conventions.


A JavaBean is a reusable software component, a special type of Java class
designed to be easily manipulated by visual development tools and integrated into
various application frameworks. Its features are discovered by tools through a
process called introspection, which relies on a set of standard design conventions.
The Four Main Design Conventions are:
Public No-Argument Constructor: The class must have a public constructor that
takes no parameters. This provides a standard way for tools to create an instance of
the bean.
public class MyBean {
public MyBean() { /* ... */ }
}
1.​ Private Properties with Public Getters and Setters: The state of the bean is
held in private instance variables (properties). These properties must be
exposed through public accessor (getter) and mutator (setter) methods that
follow a standard naming convention (e.g., getPropertyName(),
setPropertyName()).
2.​ Serializable Interface: The class must implement the java.io.Serializable
interface. This is a marker interface that signals that the object's state can be
converted into a byte stream, which is essential for persistence and network
transfer.
3.​ public Class: The class itself must be declared with the public access
modifier to be accessible by external tools and frameworks.

14. Explain Simple, Boolean, and Indexed properties in JavaBeans.


JavaBean properties are attributes that represent the state of the bean. They are
defined by their get and set methods.
Simple Property:​
This is the most common type and represents a single value (e.g., String, int,
double). For a property named userName of type String, the convention is:
private String userName;
public String getUserName() { return userName; }
public void setUserName(String name) { this.userName = name; }
Boolean Property:​
This is a special case of a simple property for boolean values. The convention for
the getter method is to prefix it with is instead of get to improve readability. For a
property active of type boolean
private boolean active;
public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }
Indexed Property:​
This represents an array or collection of values. It is managed through methods that
can access the entire array, as well as methods to access individual elements by an
index. For a property testScores of type int[]:
7
private int[] testScores;
public int[] getTestScores() { /*...*/ }
public void setTestScores(int[] scores) { /*...*/ }
public int getTestScores(int index) { /*...*/ }
public void setTestScores(int index, int score) { /*...*/ }

15. Differentiate between Bounded and Constrained properties.


Bounded and constrained properties are advanced features of JavaBeans that add
event handling and validation capabilities.
Feature Bounded Property Constrained Property
Purpose Notification: To notify interested Validation/Veto: To allow
listeners after a property's value interested listeners to approve or
has changed. reject a proposed change before it
happens.
Event Fires a PropertyChangeEvent. Also fires a PropertyChangeEvent,
Object but in a "proposed change" context.
Listener Listeners implement Listeners implement
Interface java.beans.PropertyChangeListen java.beans.VetoableChangeListene
er. r.
Listener The listener's propertyChange() The listener's vetoableChange()
Action method is called to react to the method is called. The listener can
change that has already occurred. throw a PropertyVetoException to
reject the change.
Analogy Like a newsletter subscription: Like a committee vote: members
you are told about news after it get to approve or veto a proposal
happens. before it is enacted.

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

18. Differentiate between Servlets and JSP.


Feature Servlet JSP (JavaServer Pages)
Primary Code-centric: A Servlet is a Page-centric: A JSP is an HTML
Philosophy Java class where you embed page where you embed Java
HTML inside your Java code code using special tags (<% ...
using PrintWriter.println() %>, <%= ... %>).
statements.
Main Best for handling business Best for generating the user
Purpose in logic, request processing, and interface and presenting dynamic
MVC controlling the application data. It excels as the View.
flow. It excels as the
Controller.
Developme Easier for Java developers Easier for web designers who are
nt Role who are comfortable with comfortable with HTML. They
programming logic. It can be can design the page layout and
difficult for web designers to insert dynamic data placeholders.
create or modify the HTML.

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.

19. What is bean persistence and how is it primarily achieved in Java?


Bean Persistence is the mechanism by which the state of a JavaBean object can
be saved to a storage medium (like a file or a database) and then restored at a later
time. This allows an application to save its configuration or data and reload it when it
restarts. For example, if you use a visual GUI builder to customize a JButton (setting
its text, color, and size), the IDE uses persistence to save those property values to a
file. When you run your application, a new JButton object is created and its state is
restored from that saved file.
How it is Achieved: The primary mechanism for achieving persistence in Java is
through Object Serialization. For a bean to be persistent, it must implement the
java.io.Serializable interface.
●​ Serializable is a marker interface, meaning it has no methods to implement. It
simply "marks" the class as being capable of being converted into a byte
stream.
●​ When a bean is serialized, the Java runtime writes out its class metadata and
the values of all its non-transient instance variables to a stream.
●​ This byte stream can then be written to a file or sent across a network.
●​ Later, the process of deserialization can read this byte stream and
reconstruct the original object in memory, with its state fully restored.

20. Explain the life cycle of a servlet (init, service, destroy).


The life cycle of a servlet describes its existence from creation to destruction,
managed entirely by the servlet container (e.g., Tomcat). The container creates a
single instance of a servlet to handle multiple concurrent requests, and this lifecycle
is defined by three core methods:
1. init(ServletConfig config)
●​ When: This method is called by the container only once in the servlet's
lifetime, immediately after the servlet class is instantiated. This happens
before it can handle any requests.
●​ Purpose: It is used for one-time initialization tasks that are expensive or need
to be set up beforehand. This includes loading configuration files, establishing
a database connection pool, or initializing other long-lived resources. The
ServletConfig object provides access to servlet-specific initialization
parameters from web.xml.
2. service(ServletRequest req, ServletResponse res)
●​ When: This method is called by the container for every single request that is
mapped to the servlet. It is the heart of the servlet's request-handling process.
●​ Purpose: It processes the client's request and generates a response. In an
HttpServlet, the service() method automatically inspects the HTTP method
10
(GET, POST, etc.) and dispatches the request to the corresponding doGet() or
doPost() method. Because a single instance handles multiple requests, the
code within this phase must be thread-safe.
3. destroy()
●​ When: This method is called only once at the end of the servlet's life, when
the container is shutting down or undeploying the application.
●​ Purpose: It is used for cleanup and to release any resources that were
allocated in the init() method. This ensures a graceful shutdown and prevents
resource leaks. Common tasks include closing database connections, writing
any cached data to disk, and terminating background threads. After this
method completes, the servlet instance is eligible for garbage collection.

21. Explain how HttpSession is used for session tracking.


The process works as follows:
1.​ Session Creation: When a user first makes a request, the server creates a
unique HttpSession object by calling request.getSession(). The server also
generates a long, random Session ID to uniquely identify this session.
2.​ ID Transmission via Cookie: The server sends this Session ID back to the
user's browser, typically by setting a cookie named JSESSIONID. The browser
automatically stores this cookie.
3.​ Identifying Subsequent Requests: For every future request from that user,
the browser sends the JSESSIONID cookie back to the server. The server
reads this ID to find and retrieve the correct HttpSession object from its
memory, thus recognizing the user.
4.​ Storing State: The HttpSession object acts as a key-value store where the
application can save user-specific data (like a username or a shopping cart
object) using session.setAttribute("key", value). This data persists across
requests.
5.​ Retrieving State: On other pages, the application can retrieve this data using
session.getAttribute("key") to provide a continuous, stateful experience for the
user.

22. Differentiate between RequestDispatcher.forward() and


response.sendRedirect().
Feature RequestDispatcher.forward() response.sendRedirect()
Location Server-side: Happens entirely on the Client-side: The server tells the
server; the browser is unaware. browser to make a new request.
URL in The URL does not change. The URL changes to the new
Browser location.
Request The original request object and its The original request is lost; a new
Data attributes are preserved. request is created.
Speed Faster, as it's a single internal Slower, as it requires a second
request. client-server round trip.
Target Can only go to resources within the Can go to any URL, including
same application. external websites.

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

29. Explain marshalling and unmarshalling in the context of a distributed


system like RMI.
Marshalling and unmarshalling are the core processes that enable communication
between different processes in a distributed system, especially when they are
running on different machines. They handle the conversion of application-level data
structures (like Java objects) into a format that can be transmitted over a network.
Marshalling:
●​ Definition: Marshalling is the process of taking a collection of data structures
(such as method arguments or return values) and packaging them into a
standardized, contiguous byte stream. This byte stream is a format suitable for
transmission over a network socket or for writing to a file.
●​ In RMI: When a client invokes a remote method, the client-side Stub
performs the marshalling. It takes the parameters of the method call (which
could be primitive types or complex Java objects), serializes them, and
bundles them along with metadata that identifies which remote object and
method are being called.
●​ Analogy: Think of it as packing a box for shipping. You take individual items
(the objects), put them in a box (the byte stream), and label the box with the
destination address (the remote object/method info).
Unmarshalling:
●​ Definition: Unmarshalling is the reverse process. It involves receiving a byte
stream from the network and unpacking it to reconstruct the original data
structures in the memory of the receiving process.
●​ In RMI:
○​ The server-side Skeleton receives the request from the client. It
unmarshals the byte stream to recreate the method arguments before
calling the actual method on the remote object.
16
○​ After the remote method executes, the Skeleton marshals the return
value. This response is sent back to the client, where the client-side
Stub unmarshals it to get the final result.
●​ Analogy: This is like receiving the package, opening the box, and taking out
the individual items, restoring them to their original state.
These two processes are fundamental to RMI because two different Java Virtual
Machines (JVMs) do not share the same memory space. Marshalling and
unmarshalling bridge this gap by converting in-memory objects into a portable byte
stream format and back again, handling all the complexities of data representation
and serialization automatically.

30. Differentiate between RMI and CORBA.


Feature RMI (Remote Method CORBA (Common Object Request
Invocation) Broker Architecture)
Language Java-only: Designed for Language-neutral: A standard for
Support communication between integrating systems written in different
Java applications. languages (C++, Java, Python, etc.).
Implementati Simple: Tightly integrated Complex: Requires an Interface
on with Java and easy to use. Definition Language (IDL) and more
setup.
Data Uses Java's native object Uses a language-neutral Common Data
Transfer serialization. Representation (CDR).
Use Case Ideal for distributed Ideal for enterprise-level integration of
systems where all heterogeneous, multi-language systems.
components are Java.
Industry A Java-specific technology. A broader, OMG (Object Management
Standard Group) industry standard.

31. What is the purpose of the RMI Security Manager?


The RMI Security Manager (java.rmi.RMISecurityManager) is a crucial component
for securing RMI applications, especially those that involve dynamically downloading
code from a remote location. Its primary purpose is to define and enforce a security
policy for an RMI application.
Core Purpose:​
In a standard RMI application, a client often downloads the remote object's stub
class from the server. This downloaded code will then run within the client's Java
Virtual Machine (JVM). The RMI Security Manager protects the client machine by
preventing this potentially untrusted, downloaded code from performing malicious or
unauthorized operations.
How it Works:
●​ Sandbox Model: The Security Manager runs the downloaded code in a
"sandbox," which is a restricted environment with limited permissions.
●​ Permission Checks: Before any potentially dangerous operation is performed
by the downloaded code (such as reading or writing a local file, opening a

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.

32. Explain how to draw 2D shapes and display images in Swing.


Drawing 2D shapes and displaying images in Swing is primarily accomplished
through the Java 2D API. The standard approach is to create a custom component,
typically by extending JPanel, and then overriding its paintComponent(Graphics g)
method to perform the drawing operations.
Drawing 2D Shapes
Create a Custom Panel: Extend javax.swing.JPanel. This panel will act as your
drawing canvas.​
Generated java​
class DrawingCanvas extends JPanel { ... }
Override paintComponent(Graphics g): This method is automatically called by the
Swing framework whenever the component needs to be rendered or repainted. The
Graphics object (g) is the "pen" that you use to draw.
Cast to Graphics2D: For advanced drawing, the Graphics object should be cast to
its more powerful subclass, Graphics2D. This provides access to features like
setting line thickness, using anti-aliasing for smooth lines, and drawing complex
Shape objects.​
Generated java​
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // Always call the superclass method first!
Graphics2D g2d = (Graphics2D) g;
// Turn on anti-aliasing for smoother graphics
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
Use Drawing Methods: Use the methods of the Graphics2D object to draw shapes.
You can set the color before drawing.
●​ draw() methods create outlines: g2d.drawRect(x, y, width, height);,
g2d.drawOval(...).

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);
}
}

2. displayUsers.jsp (The View)​


This JSP uses JSTL (JSP Standard Tag Library) for clean iteration, which is the
modern best practice. You would need the jstl-1.2.jar in your WEB-INF/lib folder.
Generated jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head><title>User List</title></head>
<body>
28
<h2>List of Users</h2>
<p>This data was prepared by the UserServlet and displayed by the JSP.</p>
<ul>
<%--
The c:forEach tag iterates over the "users" collection that was set
as an attribute in the servlet. The Expression Language ${users}
retrieves it from the request scope.
--%>
<c:forEach var="user" items="${users}">
<li>${user}</li>
</c:forEach>
</ul>
</body>
</html>

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

4. Client.java (The RMI Client)​


Looks up the remote object in the registry and invokes its method.
Generated java
import java.rmi.Naming;
import java.util.Date;
public class Client {
public static void main(String[] args) {
try {
// 1. Look up the remote object from the RMI registry on the server
DateTimeService dateTimeService = (DateTimeService)
Naming.lookup("rmi://localhost:1099/DateTimeService");
// 2. Invoke the remote method as if it were a local object
Date serverDate = dateTimeService.getCurrentDateTime();
System.out.println("Client received the current date and time from the
server:");
System.out.println(serverDate);
} catch (Exception e) {
System.err.println("Client 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;
}

2. CalculatorImpl.java (The Implementation)


import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
// Implements the remote interface and provides the business logic.
public class CalculatorImpl extends UnicastRemoteObject implements Calculator {
// Constructor must throw RemoteException.
public CalculatorImpl() throws RemoteException {
super();
}
// The actual implementation of the remote method.
@Override
public int add(int a, int b) throws RemoteException {
System.out.println("Server: Received a request to add " + a + " and " + b);
return a + b;
}
}
3. Server.java
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class Server {
public static void main(String[] args) {
try {
// Create an instance of the implementation.
CalculatorImpl calculator = new CalculatorImpl();
// Start the RMI registry on port 1099.
LocateRegistry.createRegistry(1099);
// Bind the remote object to the registry.
Naming.rebind("CalculatorService", calculator);
System.out.println("Calculator Server is ready.");
} catch (Exception e) {
31
System.err.println("Server exception: " + e.getMessage());
e.printStackTrace();
}
}
}
4. Client.java
import java.rmi.Naming;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
// Look up the remote object from the registry.
Calculator calculator = (Calculator)
Naming.lookup("rmi://localhost/CalculatorService");
// Get input from the user.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
// Invoke the remote method.
int sum = calculator.add(num1, num2);
System.out.println("Result from server: " + num1 + " + " + num2 + " = " +
sum);
scanner.close();
} catch (Exception e) {
System.err.println("Client exception: " + e.getMessage());
e.printStackTrace();
}
}
}

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;

public class User implements Serializable {


// Must have a serialVersionUID for version control during serialization.
private static final long serialVersionUID = 1L;
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
2. Authenticator.java (The Remote Interface)
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Authenticator extends Remote {
// This method takes a custom Serializable object as a parameter.
boolean authenticate(User user) throws RemoteException;
}

3. AuthenticatorImpl.java (The Implementation)


import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class AuthenticatorImpl extends UnicastRemoteObject implements
Authenticator {
public AuthenticatorImpl() throws RemoteException {
super();
}
@Override
public boolean authenticate(User user) throws RemoteException {
System.out.println("Server: Authenticating user '" + user.getUsername() + "'...");

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

You might also like