2017
2017
2. Why do we need a top-level container like JFrame to write Java programs with GUI? How can we
display two-dimensional objects in Java?
Answer:
Why JFrame?
o A top-level container like JFrame is essential for creating graphical user interfaces (GUIs) in
Java because it provides the foundation for a standalone window. It acts as the main window of
the application, where other GUI components (like buttons, text fields, labels, etc.) are placed.
o JFrame manages the window's properties, such as its title, size, and close behavior. Without a
top-level container, you wouldn't have a visible window to hold and organize your GUI
elements.
o It is the base for the window where the user interacts with the application.
Displaying Two-Dimensional Objects:
o In Java, you can display two-dimensional objects using the java.awt.Graphics or
java.awt.Graphics2D classes.
o The Graphics class provides basic drawing capabilities, while Graphics2D offers more
advanced features like transformations and rendering.
o To draw 2D objects (like rectangles, circles, lines, images), you typically override the paint()
or paintComponent() method of a JPanel or a custom component.
o Inside the paint() or paintComponent() method, you obtain a Graphics or Graphics2D object
and use its methods to draw the desired shapes.
o Example:
Java
import javax.swing.*;
import java.awt.*;
Answer:
JTextField:
o JTextField is a lightweight component that allows the user to enter and edit a single line of text.
o It's commonly used for input fields like names, addresses, or simple search queries.
o Key methods:
getText(): Retrieves the text from the text field.
setText(String text): Sets the text of the text field.
setEditable(boolean editable): Makes the text field editable or read-only.
addActionListener(ActionListener listener): Adds an action listener to handle
events when the user presses Enter.
JTextArea:
o JTextArea is a multi-line text component that allows the user to enter and edit multiple lines of
text.
o It's suitable for displaying or editing larger blocks of text, such as comments, descriptions, or
code snippets.
o Key methods:
getText(): Retrieves the text from the text area.
setText(String text): Sets the text of the text area.
append(String text): Appends text to the end of the text area.
setRows(int rows): Sets the number of rows in the text area.
setColumns(int columns): Sets the number of columns in the text area.
setLineWrap(boolean wrap): Enables or disables line wrapping.
setWrapStyleWord(boolean word): Sets the word wrap style.
addKeyListener(KeyListener listener): Adds a key listener to handle keyboard
events.
o Example:
Java
import javax.swing.*;
import java.awt.*;
add(textField);
add(new JScrollPane(textArea)); // Add scroll pane for scrolling
setVisible(true);
}
Answer:
1. unmaskingtech.com
unmaskingtech.com
Execution Steps:
1. Load the JDBC Driver: Load the appropriate JDBC driver for the database you want to connect
to.
2. Establish a Connection: Use the DriverManager.getConnection() method to establish a
connection to the database.
3. Create a Statement: Create a Statement or PreparedStatement object to execute SQL
statements.
4. Execute the Query: Use the executeQuery() method for SELECT statements or the
executeUpdate() method for INSERT, UPDATE, or DELETE statements.
5. Process the Result Set (if applicable): If you executed a SELECT statement, process the results
using a ResultSet object.
6. Close the Connection: Close the connection to release database resources.
Example:
Java
import java.sql.*;
try {
// 1. Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. Establish a connection
Connection connection = DriverManager.getConnection(url, username,
password);
// 3. Create a statement
Statement statement = connection.createStatement();
// 4. Execute a query
ResultSet resultSet = statement.executeQuery("SELECT * FROM employees");
Answer:
Java
import java.sql.*;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username,
password);
6. How do you set and get a Cookie in Servlet? Explain using a suitable Java program.
Cookies are used in Servlets to store small amounts of data on the client side. Below is an explanation along
with a Java program to demonstrate setting and retrieving cookies in a servlet.
1. Setting a Cookie:
o Create a Cookie object.
o Set the maximum age of the cookie.
o Add the cookie to the response object.
2. Retrieving a Cookie:
o Retrieve all cookies from the request.
o Loop through cookies and fetch the desired one.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Setting a Cookie
Cookie userCookie = new Cookie("username", "Abdul");
userCookie.setMaxAge(60 * 60 * 24); // 1-day expiry
response.addCookie(userCookie);
// Retrieving Cookies
Cookie[] cookies = request.getCookies();
if (cookies != null) {
out.println("<h3>Stored Cookies:</h3>");
for (Cookie cookie : cookies) {
out.println(cookie.getName() + " = " + cookie.getValue() + "<br>");
}
}
}
}
Explanation:
The servlet sets a cookie named "username" with the value "Abdul".
The cookie is added to the response.
The servlet then retrieves all cookies and displays them.
JSP (JavaServer Pages) provides scripting elements that allow Java code to be embedded within HTML pages.
There are three main types:
✅ Example:
Contains Java code that gets executed every time the page is requested.
Can be used for loops, conditions, and method calls.
✅ Example:
<%
int num = 10;
out.println("Number is: " + num);
%>
✅ Example:
Explanation:
Java web frameworks simplify the development of web applications by providing built-in libraries and
components. Some popular Java web frameworks are:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
CORBA is a middleware technology that enables communication between applications written in different
programming languages over a network. It uses:
✅ Example: A Java application using CORBA can call methods of a C++ application remotely.
A Bound Property in JavaBeans notifies registered listeners when its value changes. This is useful for
implementing event-driven programming.
✅ Example:
import java.beans.*;
public class Person {
private String name;
private PropertyChangeSupport support;
public Person() {
support = new PropertyChangeSupport(this);
}
9. Write a GUI application to find the sum and difference of two integers.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public SumDifferenceGUI() {
// Set up the JFrame
setTitle("Sum and Difference Calculator");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
// Create components
JLabel num1Label = new JLabel("Enter Number 1:");
JLabel num2Label = new JLabel("Enter Number 2:");
JLabel resultLabel = new JLabel("Result:");
@Override
public void mouseReleased(MouseEvent e) {
performOperation(false); // Difference when mouse is released
}
});
setVisible(true);
}
✅ Explanation:
The Bean Design Pattern in Java is used to create reusable software components called JavaBeans.
✅ Characteristics of JavaBeans:
1. Simple Property
A single property with getter and setter methods.
✅ Example:
2. Boolean Property
3. Indexed Property
Represents an array of values, with methods to get/set individual and entire values.
✅ Example:
✅ Use Case: This is useful when an object contains multiple related values, like a student’s subjects.
✅ Stub:
The client-side proxy that forwards method calls to the remote object on the server.
✅ Parameter Marshalling:
The process of converting Java objects into a format that can be transmitted over the network.
2018
2. Why do we use Panels while creating GUI applications in Java? Explain the components of the event
handling model in Java.
Answer:
Why Panels?
o Organization: JPanel is a lightweight container used to organize and group GUI components
within a JFrame or another JPanel. They help create structured layouts and make it easier to
manage the placement and arrangement of components.
o Layout Management: Panels can have their own layout managers (e.g., FlowLayout,
BorderLayout, GridLayout), allowing for more flexible and complex layouts within specific
sections of the GUI.
o Reusability: Panels can be reused across different parts of an application, promoting modularity
and reducing code duplication.
o Visual Grouping: They can be used to visually group related components, improving the user
interface's clarity.
Event Handling Model Components:
o Event Source: An object that generates an event (e.g., a button, a text field).
o Event Object: An object that encapsulates information about the event (e.g., ActionEvent,
MouseEvent).
o Event Listener: An object that is notified when an event occurs. It must implement the
appropriate listener interface (e.g., ActionListener, MouseListener).
o Event Registration: The process of associating an event listener with an event source using
methods like addActionListener() or addMouseListener().
o Event Handling Method: A method within the event listener that is executed when the event
occurs (e.g., actionPerformed(), mouseClicked()).
3. What are adapter classes? What is the benefit of using adapter classes in Java while creating events in
GUI programs? Explain with an example.
Answer:
Adapter Classes:
o Adapter classes are provided in the java.awt.event package as default implementations of
event listener interfaces.
o They provide empty method bodies for all methods defined in the corresponding listener
interface.
o For example, MouseAdapter implements MouseListener, KeyAdapter implements
KeyListener, etc.
Benefit:
o Convenience: Adapter classes allow you to implement only the event handling methods you
need, rather than having to provide empty implementations for all methods in the listener
interface. This reduces boilerplate code and makes your code more concise.
o Readability: Your code becomes more focused on the specific event handling logic, improving
readability.
Example:
Java
import javax.swing.*;
import java.awt.event.*;
add(panel);
setVisible(true);
}
4. How the data can be accessed through a ResultSet object? Explain forward only, scroll-insensitive, and
scroll-sensitive ResultSets.
Answer:
Answer:
JavaBean:
o A JavaBean is a reusable software component written in Java.
o It follows certain design conventions, such as having a no-argument constructor, providing getter
and setter methods for its properties, and implementing the Serializable interface.
o JavaBeans are used to encapsulate data and functionality and can be easily integrated into
various applications.
Types of Properties:
o Simple Properties: A single value of a specific data type (e.g., String, int, boolean).
Getter: getX()
Setter: setX(X x)
o Indexed Properties: An array or collection of values of a specific data type.
Getter: getX(int index)
Setter: setX(int index, X x)
o Bound Properties: A property that notifies listeners when its value changes.
Uses PropertyChangeSupport and PropertyChangeListener.
o Constrained Properties: A property that allows listeners to veto changes to its value.
Uses VetoableChangeSupport and VetoableChangeListener.
6. What are the differences between servlets and Java applications? Explain different methods used for
handling cookies in Java.
Answer:
7. What are marshalling and unmarshalling of arguments in RMI? Differentiate between CORBA and
RMI.
Answer:
Java Swing provides 2D graphics using the Graphics and Graphics2D classes in the java.awt package.
import javax.swing.*;
import java.awt.*;
MouseEvent is triggered when a user interacts with a mouse (click, press, release, move, enter, exit).
MouseListener is an interface in java.awt.event that handles mouse events.
Method Description
mouseClicked(MouseEvent e) Called when the mouse is clicked
mousePressed(MouseEvent e) Called when the mouse button is pressed
mouseReleased(MouseEvent e) Called when the mouse button is released
mouseEntered(MouseEvent e) Called when the mouse enters a component
mouseExited(MouseEvent e) Called when the mouse exits a component
✅ Example:
import javax.swing.*;
import java.awt.event.*;
public MouseEventDemo() {
label = new JLabel("Click the button");
JButton button = new JButton("Click Me");
button.addMouseListener(this);
add(label);
add(button);
setLayout(new java.awt.FlowLayout());
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
import java.sql.*;
try {
Connection con = DriverManager.getConnection(url, user, password);
String query = "SELECT * FROM Student WHERE Division = 'Distinction' AND Major
= 'Data Science'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println("Roll No: " + rs.getInt("Rollno"));
System.out.println("Name: " + rs.getString("Name"));
System.out.println("Level: " + rs.getString("Level"));
System.out.println("Major: " + rs.getString("Major"));
System.out.println("-----------------------------");
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
<%
String n1 = request.getParameter("num1");
String n2 = request.getParameter("num2");
String n3 = request.getParameter("num3");
RMI Components:
2019
2. What is the role of Event Listener in event handling? List different event listeners provided by Java.
Answer:
Answer:
KeyEvent:
o A KeyEvent is an event object that represents a keyboard event.
o It is generated when a key is pressed, released, or typed.
oIt provides information about the key that was pressed, its character code, and modifiers (e.g.,
Shift, Ctrl, Alt).
Example:
Java
import javax.swing.*;
import java.awt.event.*;
public KeyEventExample() {
setTitle("Key Event Example");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(textField);
setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
System.out.println("Key Typed: " + e.getKeyChar());
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("Key Released: " + e.getKeyCode());
}
}
4. What is the use of RowSet interface? Explain connected and disconnected RowSets.
Answer:
5. What are bounded and constrained properties in JavaBeans? Explain the advantages of JavaBeans.
Answer:
Bounded Properties:
o A bounded property is a property that notifies listeners when its value changes.
o It uses the PropertyChangeSupport class and the PropertyChangeListener interface.
o When a bounded property's value is modified, a PropertyChangeEvent is fired to all registered
listeners.
Constrained Properties:
o A constrained property is a property that allows listeners to veto changes to its value.
o It uses the VetoableChangeSupport class and the VetoableChangeListener interface.
o When a constrained property's value is about to change, a PropertyChangeEvent is fired to the
listeners.
o Listeners can throw a PropertyVetoException to prevent the change.
Advantages of JavaBeans:
o Reusability: JavaBeans are reusable software components that can be easily integrated into
various applications.
o Modularity: They promote modularity by encapsulating data and functionality.
o Tool Support: Many IDEs and tools provide support for creating and using JavaBeans.
o Component-Based Development: They facilitate component-based development, where
applications are built by assembling reusable components.
6. What are the key methods provided in HttpSession interface for handling session? Explain.
Answer:
HttpSession Interface:
o The HttpSession interface represents a user's session in a web application.
o It allows you to store and retrieve data associated with a specific user across multiple requests.
Key Methods:
o setAttribute(String name, Object value): Stores an object in the session under the
specified name.
o getAttribute(String name): Retrieves an object from the session with the specified name.
o removeAttribute(String name): Removes an object from the session with the specified name.
o getId(): Returns the unique identifier for the session.
o getCreationTime(): Returns the time when the session was created.
o getLastAccessedTime(): Returns the time when the session was last accessed.
o invalidate(): Invalidates the session, removing all associated data.
o setMaxInactiveInterval(int interval): Sets the maximum time (in seconds) that the
session can remain inactive before it is invalidated.
Answer:
RMI Architecture:
o RMI (Remote Method Invocation) is a Java API that allows objects running in different JVMs to
communicate with each other.
o It uses a stub/skeleton architecture to facilitate remote method calls.
Components:
o Stub: A client-side proxy for the remote object. It implements the same interface as the remote
object and forwards method calls to the skeleton.
o Skeleton: A server-side proxy that receives method calls from the stub, unmarshals the
arguments, invokes the actual method on the remote object, and marshals the return value or
exception back to the stub.
o Remote Reference Layer: Manages the communication between the stub and the skeleton.
o Transport Layer: Handles the network connection and data transfer.
o RMI Registry: A naming service that allows clients to locate remote objects by name.
Process:
a) Adapter classes:
Adapter classes are provided in the java.awt.event package as default implementations of event
listener interfaces.
They provide empty method bodies for all methods defined in the corresponding listener interface.
This allows you to implement only the event handling methods you need, rather than having to provide
empty implementations for all methods in the listener interface.
Examples: MouseAdapter, KeyAdapter, WindowAdapter.
b) CORBA:
CORBA (Common Object Request Broker Architecture) is a standard for distributed object computing.
It allows objects written in different programming languages and running on different platforms to
communicate with each other.
CORBA uses an Object Request Broker (ORB) as middleware to facilitate communication.
It uses IDL (Interface Definition Language) to define the interfaces of remote objects.
9. How frame can be created in Java? Explain. Write a program to create a GUI application
in Java that identifies the smaller and greater number between two input numbers taken
through two text fields and displays the result in a label. If the user presses the mouse it
should display the smaller number and if the user releases the mouse it should display the
greater number.
A frame is a top-level container that provides a window for GUI applications in Java. It is created using the
JFrame class from the javax.swing package.
public NumberComparator() {
setTitle("Number Comparator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
addMouseListener(this);
setVisible(true);
}
if (isSmaller) {
resultLabel.setText("Smaller: " + Math.min(num1, num2));
} else {
resultLabel.setText("Greater: " + Math.max(num1, num2));
}
} catch (NumberFormatException ex) {
resultLabel.setText("Invalid input!");
}
}
✅ Expected Output:
10. Explain JDBC architecture. Write a program to insert three records into a table Item
which is in the database Shop and contains the columns ItemID, Name, UnitPrice, Units and
Expiry Date.
✅ JDBC Architecture
JDBC (Java Database Connectivity) is an API that allows Java applications to interact with databases.
✅ JDBC Components
try {
Connection con = DriverManager.getConnection(url, user, password);
String query = "INSERT INTO Item (ItemID, Name, UnitPrice, Units, ExpiryDate)
VALUES (?, ?, ?, ?, ?)";
pstmt.setInt(1, 101);
pstmt.setString(2, "Milk");
pstmt.setDouble(3, 50.0);
pstmt.setInt(4, 10);
pstmt.setString(5, "2025-12-31");
pstmt.executeUpdate();
pstmt.setInt(1, 102);
pstmt.setString(2, "Bread");
pstmt.setDouble(3, 30.0);
pstmt.setInt(4, 20);
pstmt.setString(5, "2025-12-15");
pstmt.executeUpdate();
pstmt.setInt(1, 103);
pstmt.setString(2, "Eggs");
pstmt.setDouble(3, 10.0);
pstmt.setInt(4, 50);
pstmt.setString(5, "2025-12-10");
pstmt.executeUpdate();
✅ Expected Output:
11. Differentiate between Servlet and JSP. Create a servlet that computes and displays
factorial of an input number entered from a page when the button from that page is pressed
by the user.
out.println("<html><body>");
out.println("<h2>Factorial of " + num + " is: " + fact + "</h2>");
out.println("</body></html>");
}
}
<web-app>
<servlet>
<servlet-name>FactorialServlet</servlet-name>
<servlet-class>FactorialServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FactorialServlet</servlet-name>
<url-pattern>/FactorialServlet</url-pattern>
</servlet-mapping>
</web-app>
✅ Expected Output:
If user enters 5, output will be: