[go: up one dir, main page]

0% found this document useful (0 votes)
9 views28 pages

2017

The document provides a comprehensive overview of Java GUI programming, including the use of JFrame for creating windows, JTextField and JTextArea for text input, and JDBC for database connectivity. It explains how to work with cookies in servlets, scripting elements in JSP, and compares ResultSet with RowSet while detailing the PreparedStatement. Additionally, it covers JavaBeans, GUI applications for arithmetic operations, and the Bean Design Pattern, highlighting their characteristics and examples.

Uploaded by

ABDUL HALEEM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views28 pages

2017

The document provides a comprehensive overview of Java GUI programming, including the use of JFrame for creating windows, JTextField and JTextArea for text input, and JDBC for database connectivity. It explains how to work with cookies in servlets, scripting elements in JSP, and compares ResultSet with RowSet while detailing the PreparedStatement. Additionally, it covers JavaBeans, GUI applications for arithmetic operations, and the Bean Design Pattern, highlighting their characteristics and examples.

Uploaded by

ABDUL HALEEM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

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.*;

public class Draw2D extends JFrame {


public Draw2D() {
setTitle("2D Drawing");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new DrawPanel());
setVisible(true);
}

public static void main(String[] args) {


new Draw2D();
}
}

class DrawPanel extends JPanel {


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillRect(50, 50, 100, 100); // Draw a red rectangle
g2d.setColor(Color.BLUE);
g2d.fillOval(200, 50, 100, 100); // Draw a blue circle
}
}
3. Explain JTextField and JTextArea components of Java Swing library.

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.*;

public class TextComponents extends JFrame {


public TextComponents() {
setTitle("Text Components");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

JTextField textField = new JTextField(20);


JTextArea textArea = new JTextArea(5, 20);

add(textField);
add(new JScrollPane(textArea)); // Add scroll pane for scrolling

setVisible(true);
}

public static void main(String[] args) {


new TextComponents();
}
}
4. How do you execute SQL statements using JDBC? Explain with example.

Answer:

 JDBC (Java Database Connectivity):


o JDBC is a Java API that allows Java programs to interact with relational databases.
o It provides a set 1 of classes and interfaces for connecting to databases, executing SQL
statements, and processing results.

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.*;

public class JDBCExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";

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

// 5. Process the result set


while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}

// 6. Close the connection


resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}

5. Compare ResultSet with RowSet. Explain PreparedStatement with example.

Answer:

 ResultSet vs. RowSet:


o ResultSet:
 Represents the result of a database query.
 Forward-only or scrollable (depending on the driver).
 Connected to the database; it maintains an open connection.
 Not serializable.
o RowSet:
 A wrapper around a ResultSet.
 Scrollable and updatable.
 Can be connected or disconnected from the database.
 Serializable (can be passed between components).
 Provides more flexibility and control over data.
 PreparedStatement:
o PreparedStatement is a precompiled SQL statement.
o It's more efficient than a regular Statement because the database parses and compiles the SQL
query only once.
o It helps prevent SQL injection attacks by treating user input as data, not executable code.
o Example:

Java

import java.sql.*;

public class PreparedStatementExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";

try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username,
password);

Here are the answers to your questions:

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.

Steps to Work with Cookies in Servlets:

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.

Java Servlet Program to Set and Get Cookies

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

out.println("<h2>Cookie has been set!</h2>");

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

7. Explain different scripting elements of JSP with an example.

JSP (JavaServer Pages) provides scripting elements that allow Java code to be embedded within HTML pages.
There are three main types:

1. Declaration Tag (<%! %>)

 Used to declare variables and methods.


 These variables/methods can be used anywhere in the JSP page.

✅ Example:

<%! int count = 0; %>


<%! public int getCount() { return ++count; } %>

2. Scriptlet Tag (<% %>)

 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);
%>

3. Expression Tag (<%= %>)

 Used to print the result of an expression directly in the response.

✅ Example:

<p>Today's Date: <%= new java.util.Date() %></p>

✅ Full Example Using All Elements:

<%@ page language="java" %>


<html>
<body>
<%! int count = 0; %>
<p>Visitor Count: <%= ++count %></p>
<%
String name = "Abdul";
out.println("<p>Welcome, " + name + "!</p>");
%>
</body>
</html>

Explanation:

 <%! %> declares a variable (count).


 <%= %> prints the value of count.
 <% %> contains Java code that prints a welcome message.

8. Write short notes on (Any Two)

(a) Java Web Frameworks

Java web frameworks simplify the development of web applications by providing built-in libraries and
components. Some popular Java web frameworks are:

1. Spring Boot – Simplifies Java web development with minimal configuration.


2. JSF (JavaServer Faces) – A component-based UI framework.
3. Struts – Follows the MVC (Model-View-Controller) architecture.

✅ Example (Spring Boot Controller):

@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}

(b) CORBA (Common Object Request Broker Architecture)

CORBA is a middleware technology that enables communication between applications written in different
programming languages over a network. It uses:

 ORB (Object Request Broker) to handle method calls between objects.


 IDL (Interface Definition Language) to define the structure of remote objects.

✅ Example: A Java application using CORBA can call methods of a C++ application remotely.

(c) Bean Bound Property

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

public void addPropertyChangeListener(PropertyChangeListener listener) {


support.addPropertyChangeListener(listener);
}

public void setName(String newName) {


String oldName = this.name;
this.name = newName;
support.firePropertyChange("name", oldName, newName);
}
}

9. Write a GUI application to find the sum and difference of two integers.

This Java Swing application provides:

 Two text fields for input.


 One text field for output.
 Mouse Pressed: Displays the sum of the two numbers.
 Mouse Released: Displays the difference.

✅ Java Swing Program:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SumDifferenceGUI extends JFrame {


private JTextField num1Field, num2Field, resultField;

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:");

num1Field = new JTextField();


num2Field = new JTextField();
resultField = new JTextField();
resultField.setEditable(false); // Output field should not be editable

// Create a button with mouse listeners


JButton calculateButton = new JButton("Calculate");
calculateButton.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
performOperation(true); // Sum when mouse is pressed
}

@Override
public void mouseReleased(MouseEvent e) {
performOperation(false); // Difference when mouse is released
}
});

// Add components to frame


add(num1Label); add(num1Field);
add(num2Label); add(num2Field);
add(resultLabel); add(resultField);
add(calculateButton);

setVisible(true);
}

private void performOperation(boolean isSum) {


try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = isSum ? (num1 + num2) : (num1 - num2);
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
resultField.setText("Invalid Input");
}
}

public static void main(String[] args) {


new SumDifferenceGUI();
}
}

✅ Explanation:

 mousePressed() → Calculates sum.


 mouseReleased() → Calculates difference.
 Uses JTextField, JButton, and JLabel to create the GUI.

10. What is the Bean Design Pattern?

The Bean Design Pattern in Java is used to create reusable software components called JavaBeans.

✅ Characteristics of JavaBeans:

1. Encapsulation: Private fields with getter and setter methods.


2. Serialization: Implements Serializable interface for object persistence.
3. No-Argument Constructor: Ensures easy instantiation.

Types of Bean Properties:

1. Simple Property
 A single property with getter and setter methods.
✅ Example:

public class Person {


private String name;

public String getName() { return name; }


public void setName(String name) { this.name = name; }
}

2. Boolean Property

 Uses isPropertyName() instead of getPropertyName().


✅ Example:

public class Light {


private boolean on;

public boolean isOn() { return on; }


public void setOn(boolean on) { this.on = on; }
}

3. Indexed Property

 Represents an array of values, with methods to get/set individual and entire values.
✅ Example:

public class Student {


private String[] subjects = new String[5];

public String getSubject(int index) { return subjects[index]; }


public void setSubject(int index, String subject) { subjects[index] = subject; }

public String[] getSubjects() { return subjects; }


public void setSubjects(String[] subjects) { this.subjects = subjects; }
}

✅ Use Case: This is useful when an object contains multiple related values, like a student’s subjects.

11. Define RMI. What is Stub and Parameter Marshalling?

✅ RMI (Remote Method Invocation):


RMI is a Java API that allows methods to be called remotely between different JVMs. It is used for distributed
applications.

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

RMI Client/Server Application for Multiplication

✅ Steps to Implement RMI:

1. Create a remote interface.


2. Implement the remote interface on the server.
3. Create an RMI client.
4. Run rmic, rmiregistry, and execute the application.

1. Remote Interface (Multiplication.java)


import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Multiplication extends Remote {


int multiply(int a, int b) throws RemoteException;
}

2. Server Implementation (MultiplicationServer.java)


import java.rmi.*;
import java.rmi.server.*;

public class MultiplicationServer extends UnicastRemoteObject implements Multiplication {


public MultiplicationServer() throws RemoteException {
super();
}

public int multiply(int a, int b) throws RemoteException {


return a * b;
}

public static void main(String[] args) {


try {
MultiplicationServer server = new MultiplicationServer();
Naming.rebind("rmi://localhost/MultiplyService", server);
System.out.println("Server is running...");
} catch (Exception e) {
System.out.println("Server error: " + e);
}
}
}

3. Client Program (MultiplicationClient.java)


import java.rmi.*;

public class MultiplicationClient {


public static void main(String[] args) {
try {
Multiplication obj = (Multiplication)
Naming.lookup("rmi://localhost/MultiplyService");
int result = obj.multiply(5, 10);
System.out.println("Multiplication Result: " + result);
} catch (Exception e) {
System.out.println("Client error: " + e);
}
}
}

How to Run the RMI Application?

1. Compile all Java files


2. javac *.java
3. Generate Stub using rmic
4. rmic MultiplicationServer
5. Start RMI Registry
6. rmiregistry
7. Run Server
8. java MultiplicationServer
9. Run Client
10. java MultiplicationClient

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.*;

public class MouseAdapterExample extends JFrame {


public MouseAdapterExample() {
setTitle("Mouse Adapter Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();


panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: (" + e.getX() + ", " +
e.getY() + ")");
}
});

add(panel);
setVisible(true);
}

public static void main(String[] args) {


new MouseAdapterExample();
}
}

4. How the data can be accessed through a ResultSet object? Explain forward only, scroll-insensitive, and
scroll-sensitive ResultSets.

Answer:

 Accessing Data through ResultSet:


o The ResultSet interface provides methods to retrieve data from the result of a database query.
o You can use methods like getString(), getInt(), getDouble(), etc., to retrieve values from
specific columns.
o You can move the cursor through the result set using methods like next(), previous(),
first(), last(), and absolute().
 Forward-Only ResultSet:
o The default type of ResultSet.
o Allows you to move the cursor only in the forward direction, one row at a time.
o Efficient for processing large result sets sequentially.
o Created using createStatement().
 Scroll-Insensitive ResultSet:
o Allows you to move the cursor in both forward and backward directions.
o Changes made to the database after the ResultSet is created are not visible in the ResultSet.
o Created using createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY).
 Scroll-Sensitive ResultSet:
o Allows you to move the cursor in both forward and backward directions.
o Changes made to the database after the ResultSet is created are visible in the ResultSet.
o Created using createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY).

5. What is a JavaBean? Explain different types of properties in JavaBeans.

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:

 Differences between Servlets and Java Applications:


o Execution Environment:
 Servlets run within a web container (e.g., Tomcat, Jetty).
 Java applications run as standalone programs on the operating system.
o Purpose:
 Servlets are used to handle HTTP requests and generate dynamic web content.
 Java applications can be used for various purposes, including desktop applications,
command-line tools, and server-side applications.
o Lifecycle:
 Servlets have a lifecycle managed by the web container.
 Java applications have a lifecycle managed by the operating system.
o Input/Output:
 Servlets receive input from HTTP requests and send output as HTTP responses.
 Java applications can use various input/output mechanisms (e.g., console input, file I/O).
 Methods for Handling Cookies in Java:
o Setting a Cookie:
 Create a Cookie object with a name and a value.
 Set cookie properties (e.g., max age, domain, path).
 Add the cookie to the HTTP response using response.addCookie().
o Getting a Cookie:
 Retrieve the array of Cookie objects from the HTTP request using
request.getCookies().
 Iterate through the array to find the desired cookie by name.
 Retrieve the cookie's value using cookie.getValue().

7. What are marshalling and unmarshalling of arguments in RMI? Differentiate between CORBA and
RMI.

Answer:

 Marshalling and Unmarshalling in RMI:


o Marshalling: The process of converting objects into a stream of bytes so that they can be
transmitted over a network.
o Unmarshalling: The process of converting a stream of bytes back into objects.
o In RMI, arguments and return values of remote method invocations are marshalled and
unmarshalled.
 Differences between CORBA and RMI:
o Language Support:
 CORBA supports multiple programming languages (e.g., Java, C++, Python).
 RMI is primarily designed for Java-to-Java communication.
o Architecture:
 CORBA uses an Object Request Broker (ORB) as middleware.
 RMI uses a stub/skeleton architecture.
o Complexity:
 CORBA is generally more complex than RMI.
 RMI is simpler and easier to use for Java-based distributed applications.
o Interoperability:
 CORBA is designed for interoperability between different languages and platforms.
 RMI is primarily focused on Java interoperability.

8. Write Short Notes on (Any Two)

(a) 2D Shapes in Swing

Java Swing provides 2D graphics using the Graphics and Graphics2D classes in the java.awt package.

✅ Common 2D Shapes in Swing:

 Rectangle → drawRect(x, y, width, height)


 Oval → drawOval(x, y, width, height)
 Line → drawLine(x1, y1, x2, y2)
 Arc → drawArc(x, y, width, height, startAngle, arcAngle)

✅ Example: Drawing a Circle and Rectangle

import javax.swing.*;
import java.awt.*;

public class DrawShapes extends JPanel {


public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(50, 50, 100, 50); // Draw Rectangle
g.drawOval(200, 50, 100, 100); // Draw Circle
}

public static void main(String[] args) {


JFrame frame = new JFrame("2D Shapes");
DrawShapes panel = new DrawShapes();
frame.add(panel);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

(b) MouseEvent and MouseListener

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

✅ Methods of MouseListener Interface:

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 class MouseEventDemo extends JFrame implements MouseListener {


JLabel label;

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

public void mouseClicked(MouseEvent e) { label.setText("Mouse Clicked!"); }


public void mousePressed(MouseEvent e) { label.setText("Mouse Pressed!"); }
public void mouseReleased(MouseEvent e) { label.setText("Mouse Released!"); }
public void mouseEntered(MouseEvent e) { label.setText("Mouse Entered!"); }
public void mouseExited(MouseEvent e) { label.setText("Mouse Exited!"); }

public static void main(String[] args) { new MouseEventDemo(); }


}

9. Layout Managers and Database Application in Java

Why Use Layout Managers?

 Arranges UI components dynamically.


 Handles resizing across different screen sizes.
 Java provides several layout managers:
o FlowLayout (Default for JPanel)
o BorderLayout (Default for JFrame)
o GridLayout (Rows and Columns)
o GridBagLayout (Flexible positioning)

✅ Key Interfaces for Java Database Development:

1. Connection → Connects Java with the database.


2. Statement → Executes SQL queries.
3. ResultSet → Stores query results.
4. PreparedStatement → Prevents SQL injection.

✅ Program to Display Distinction Students with Major in Data Science:

import java.sql.*;

public class StudentRecords {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/College";
String user = "root"; // Change as per your database
String password = "password";

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

10. JSP Declaration vs Expression Tags

✅ Difference Between Declaration and Expression Tags:

Feature Declaration (<%! %>) Expression (<%= %>)


Purpose Declares variables/methods Prints output directly
Scope Class level Within service() method
Example <%! int x = 10; %> <%= x * 5 %>

✅ JSP Program to Find the Greatest Number Among Three:

<%@ page language="java" %>


<html>
<head>
<title>Find Greatest Number</title>
</head>
<body>
<form method="post">
Enter Number 1: <input type="text" name="num1"><br>
Enter Number 2: <input type="text" name="num2"><br>
Enter Number 3: <input type="text" name="num3"><br>
<input type="submit" value="Find Greatest">
</form>

<%
String n1 = request.getParameter("num1");
String n2 = request.getParameter("num2");
String n3 = request.getParameter("num3");

if (n1 != null && n2 != null && n3 != null) {


int num1 = Integer.parseInt(n1);
int num2 = Integer.parseInt(n2);
int num3 = Integer.parseInt(n3);
int greatest = Math.max(num1, Math.max(num2, num3));
%>
<h3>Greatest Number: <%= greatest %></h3>
<%
}
%>
</body>
</html>

11. RMI Components and Selling Price Calculation

RMI Components:

1. Stub → Client-side proxy for a remote object.


2. Skeleton → Server-side proxy (obsolete after Java 5).
3. RMI Registry → Stores remote object references.
4. Remote Interface → Defines remote methods.
5. Remote Object → Implements the remote interface.

✅ RMI Program to Find Selling Price (Rs. 5000, Rs. 50 Discount):

1. Remote Interface (SellingPrice.java)


import java.rmi.*;

public interface SellingPrice extends Remote {


double getSellingPrice(double costPrice, double discount) throws RemoteException;
}

2. Server Implementation (SellingPriceServer.java)


import java.rmi.*;
import java.rmi.server.*;

public class SellingPriceServer extends UnicastRemoteObject implements SellingPrice {


public SellingPriceServer() throws RemoteException {
super();
}

public double getSellingPrice(double costPrice, double discount) throws


RemoteException {
return costPrice - discount;
}

public static void main(String args[]) {


try {
Naming.rebind("rmi://localhost/SellingService", new SellingPriceServer());
System.out.println("Server is running...");
} catch (Exception e) {
System.out.println(e);
}
}
}
3. Client Program (SellingPriceClient.java)
import java.rmi.*;

public class SellingPriceClient {


public static void main(String args[]) {
try {
SellingPrice obj = (SellingPrice)
Naming.lookup("rmi://localhost/SellingService");
double result = obj.getSellingPrice(5000, 50);
System.out.println("Selling Price: " + result);
} catch (Exception e) {
System.out.println(e);
}
}
}

2019

2. What is the role of Event Listener in event handling? List different event listeners provided by Java.

Answer:

 Role of Event Listeners:


o In Java's event-driven programming model, event listeners are objects that "listen" for specific
events generated by components (like buttons, text fields, etc.).
o When an event occurs, the event source notifies the registered listeners by invoking the
appropriate methods defined in the listener interface.
o This allows for decoupling the event source from the event handler, making the code more
modular and maintainable.
 Different Event Listeners:
o ActionListener: Handles action events (e.g., button clicks, menu selections).
o MouseListener: Handles mouse events (e.g., clicks, presses, releases, enters, exits).
o MouseMotionListener: Handles mouse movement events (e.g., drags, moves).
o KeyListener: Handles keyboard events (e.g., key presses, releases, typed).
o FocusListener: Handles focus events (e.g., gaining or losing focus).
o WindowListener: Handles window events (e.g., opening, closing, iconifying).
o ItemListener: Handles item selection events (e.g., checkboxes, lists).
o TextListener: Handles text change events (e.g., text fields).

3. What is KeyEvent? Explain with proper example.

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 class KeyEventExample extends JFrame implements KeyListener {


private JTextField textField;

public KeyEventExample() {
setTitle("Key Event Example");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

textField = new JTextField(20);


textField.addKeyListener(this);

add(textField);
setVisible(true);
}

public static void main(String[] args) {


new KeyEventExample();
}

@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:

 Use of RowSet Interface:


o The RowSet interface is a wrapper around a ResultSet that provides more flexibility and control
over data.
o It allows you to work with data in a disconnected manner, making it suitable for distributed
applications and situations where database connections are not always available.
 Connected RowSet:
o A RowSet that maintains an active connection to the database.
o Changes made to the RowSet are immediately reflected in the database.
o Example: JdbcRowSet
 Disconnected RowSet:
o A RowSet that retrieves data from the database and then disconnects.
o Changes made to the RowSet are not immediately reflected in the database.
o You need to explicitly update the database using methods like acceptChanges().
o Example: CachedRowSet

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.

7. Explain RMI architecture in Java in detail.

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:

1. The client looks up the remote object in the RMI registry.


2. The client receives the stub for the remote object.
3. The client invokes a method on the stub.
4. The stub marshals the method arguments and sends them to the skeleton.
5. The skeleton unmarshals the arguments and invokes the method on the remote object.
6. The remote object executes the method and returns the result.
7. The skeleton marshals the return value or exception and sends it back to the stub.
8. The stub unmarshals the result and returns it to the client.

8. Write short notes on (any two):

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.

c) Life cycle of a servlet:

 A servlet's lifecycle is managed by the web container.


 The container creates an instance of the servlet, initializes it, calls its service method to handle client
requests, and eventually destroys it.
 The lifecycle consists of the following stages:
o Loading and Instantiation: The container loads the servlet class and creates an instance of it.
o Initialization: The container calls the init() method to initialize the servlet.
o Service: The container calls the service() method to handle

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.

✅ Explanation of Frame in Java

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.

✅ Steps to Create a Frame in Java

1. Create an instance of JFrame


2. Set its size → setSize(width, height);
3. Set the layout → setLayout(new FlowLayout());
4. Define close operation → setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
5. Make it visible → setVisible(true);

✅ Java Program to Compare Two Numbers Using Mouse Events


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class NumberComparator extends JFrame implements MouseListener {


JTextField num1Field, num2Field;
JLabel resultLabel;

public NumberComparator() {
setTitle("Number Comparator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

add(new JLabel("Enter Number 1:"));


num1Field = new JTextField(10);
add(num1Field);

add(new JLabel("Enter Number 2:"));


num2Field = new JTextField(10);
add(num2Field);

resultLabel = new JLabel("Press/Release the mouse to compare");


add(resultLabel);

addMouseListener(this);
setVisible(true);
}

public void mousePressed(MouseEvent e) {


compareNumbers(true);
}

public void mouseReleased(MouseEvent e) {


compareNumbers(false);
}

private void compareNumbers(boolean isSmaller) {


try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());

if (isSmaller) {
resultLabel.setText("Smaller: " + Math.min(num1, num2));
} else {
resultLabel.setText("Greater: " + Math.max(num1, num2));
}
} catch (NumberFormatException ex) {
resultLabel.setText("Invalid input!");
}
}

public void mouseClicked(MouseEvent e) {}


public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

public static void main(String[] args) {


new NumberComparator();
}
}

✅ Expected Output:

 Press Mouse: Displays the smaller number.


 Release Mouse: Displays the greater number.

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

1. JDBC Driver Manager → Loads the driver.


2. JDBC Driver → Establishes a connection.
3. Connection → Connects Java with the database.
4. Statement → Executes SQL queries.
5. ResultSet → Stores query results.

✅ Java Program to Insert Records into the Item Table


import java.sql.*;

public class InsertItems {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/Shop";
String user = "root"; // Change as per your database
String password = "password";

try {
Connection con = DriverManager.getConnection(url, user, password);
String query = "INSERT INTO Item (ItemID, Name, UnitPrice, Units, ExpiryDate)
VALUES (?, ?, ?, ?, ?)";

PreparedStatement pstmt = con.prepareStatement(query);

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

System.out.println("Records inserted successfully.");


con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

✅ Expected Output:

Records inserted successfully.

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.

✅ Difference Between Servlet and JSP

Feature Servlet JSP


Extension .java .jsp
Execution Compiled into bytecode Converted into Servlets
Used For Business logic Presentation layer (HTML + Java)
Feature Servlet JSP
Performance Faster (Compiled once) Slightly slower (Converted into Servlet)

✅ JSP Page to Take Input for Factorial Calculation (factorial.jsp)


<%@ page language="java" %>
<html>
<head><title>Factorial Calculator</title></head>
<body>
<form action="FactorialServlet" method="post">
Enter Number: <input type="text" name="number">
<input type="submit" value="Calculate Factorial">
</form>
</body>
</html>

✅ Servlet to Compute Factorial (FactorialServlet.java)


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FactorialServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

int num = Integer.parseInt(request.getParameter("number"));


int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}

out.println("<html><body>");
out.println("<h2>Factorial of " + num + " is: " + fact + "</h2>");
out.println("</body></html>");
}
}

✅ Steps to Deploy the Servlet:

1. Compile the Servlet:


2. javac -cp servlet-api.jar FactorialServlet.java
3. Place the .class file inside WEB-INF/classes/
4. Configure web.xml

<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:

Factorial of 5 is: 120

You might also like