1.
"Design and implement a Java Swing application for user registration and
shape drawing. Use various layout managers (BorderLayout, GridLayout),
event handling mechanisms, adapter classes, and basic Swing components.
The app should collect user input and allow drawing 2D shapes in different
colors."
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ShapeDrawingApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new RegistrationFrame());
}
}
class RegistrationFrame extends JFrame {
JTextField nameField, emailField;
JPasswordField passField;
JRadioButton maleBtn, femaleBtn;
JButton registerBtn;
public RegistrationFrame() {
setTitle("User Registration");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel centerPanel = new JPanel(new GridLayout(5, 2, 5, 5));
centerPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
nameField = new JTextField();
emailField = new JTextField();
passField = new JPasswordField();
maleBtn = new JRadioButton("Male");
femaleBtn = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleBtn);
genderGroup.add(femaleBtn);
centerPanel.add(new JLabel("Name:"));
centerPanel.add(nameField);
centerPanel.add(new JLabel("Email:"));
centerPanel.add(emailField);
centerPanel.add(new JLabel("Password:"));
centerPanel.add(passField);
centerPanel.add(new JLabel("Gender:"));
JPanel genderPanel = new JPanel(new FlowLayout());
genderPanel.add(maleBtn);
genderPanel.add(femaleBtn);
centerPanel.add(genderPanel);
registerBtn = new JButton("Register");
add(centerPanel, BorderLayout.CENTER);
add(registerBtn, BorderLayout.SOUTH);
registerBtn.addActionListener(e -> {
if (nameField.getText().isEmpty() || emailField.getText().isEmpty() ||
passField.getPassword().length == 0
|| (!maleBtn.isSelected() && !femaleBtn.isSelected())) {
JOptionPane.showMessageDialog(this, "Please fill all fields.");
} else {
dispose();
new DrawingFrame();
}
});
setVisible(true);
}
}
class DrawingFrame extends JFrame {
private JComboBox<String> shapeBox, colorBox;
private DrawingPanel drawingPanel;
public DrawingFrame() {
setTitle("Shape Drawing Panel");
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
shapeBox = new JComboBox<>(new String[]{"Circle", "Rectangle"});
colorBox = new JComboBox<>(new String[]{"Red", "Green", "Blue", "Black"});
topPanel.add(new JLabel("Shape:"));
topPanel.add(shapeBox);
topPanel.add(new JLabel("Color:"));
topPanel.add(colorBox);
add(topPanel, BorderLayout.NORTH);
drawingPanel = new DrawingPanel(shapeBox, colorBox);
add(drawingPanel, BorderLayout.CENTER);
setVisible(true);
}
}
class DrawingPanel extends JPanel {
private final JComboBox<String> shapeBox, colorBox;
private final ArrayList<ShapeRecord> shapes = new ArrayList<>();
public DrawingPanel(JComboBox<String> shapeBox, JComboBox<String> colorBox) {
this.shapeBox = shapeBox;
this.colorBox = colorBox;
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
String shape = (String) shapeBox.getSelectedItem();
String colorName = (String) colorBox.getSelectedItem();
Color color;
switch (colorName) {
case "Red" -> color = Color.RED;
case "Green" -> color = Color.GREEN;
case "Blue" -> color = Color.BLUE;
default -> color = Color.BLACK;
}
shapes.add(new ShapeRecord(shape, e.getX(), e.getY(), color));
repaint();
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (ShapeRecord s : shapes) {
g.setColor(s.color);
switch (s.shape) {
case "Circle" -> g.fillOval(s.x - 25, s.y - 25, 50, 50);
case "Rectangle" -> g.fillRect(s.x - 30, s.y - 20, 60, 40);
}
}
}
static class ShapeRecord {
String shape;
int x, y;
Color color;
ShapeRecord(String shape, int x, int y, Color color) {
this.shape = shape;
this.x = x;
this.y = y;
this.color = color;
}
}
How It Works
● Starts with a Registration Form – User enters name, email, password, and gender.
● After Registration – Opens a Shape Drawing Window.
● User Picks Shape & Color – Circle or Rectangle; Red, Green, Blue, Black.
● Click on Canvas – Draws the selected shape at the clicked location.
Components & Features:
Component Purpose
JTextField Input for name and email
JPasswordField Password input
JRadioButton Gender selection
JButton Register button
JComboBox Select shape and color
Holds input fields and drawing
JPanel
area
JFrame Main window for each screen
MouseAdapter Detects mouse clicks for drawing
Graphics Draws shapes on the panel
Layouts Used:
● BorderLayout – Main layout of
windows
● GridLayout – Form fields
● FlowLayout – Gender options
OUTPUT:
2. "Develop a JavaBean for storing employee details (name, ID, salary,
department). Demonstrate the use of properties, getter/setter methods, bound
and constrained properties, and the use of BeanInfo interface. Also, create a
GUI application that uses this bean and allows users to set and retrieve the
properties."
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.Serializable;
public class EmployeeBeanApp {
public static class EmployeeBean implements Serializable {
private String name;
private int id;
private double salary;
private String department;
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private final VetoableChangeSupport vcs = new VetoableChangeSupport(this);
public EmployeeBean() {}
public String getName() {
return name;
}
public void setName(String name) {
String old = this.name;
this.name = name;
pcs.firePropertyChange("name", old, name);
}
public int getId() {
return id;
}
public void setId(int id) throws PropertyVetoException {
int old = this.id;
vcs.fireVetoableChange("id", old, id);
this.id = id;
pcs.firePropertyChange("id", old, id);
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
double old = this.salary;
this.salary = salary;
pcs.firePropertyChange("salary", old, salary);
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
String old = this.department;
this.department = department;
pcs.firePropertyChange("department", old, department);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public void addVetoableChangeListener(VetoableChangeListener listener) {
vcs.addVetoableChangeListener(listener);
}
public void removeVetoableChangeListener(VetoableChangeListener listener) {
vcs.removeVetoableChangeListener(listener);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(EmployeeBeanApp::createAndShowGUI);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Employee Bean GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 350);
EmployeeBean bean = new EmployeeBean();
bean.addPropertyChangeListener(evt ->
System.out.println("Property '" + evt.getPropertyName() + "' changed from " +
evt.getOldValue() + " to " + evt.getNewValue()));
try {
bean.addVetoableChangeListener(evt -> {
if ("id".equals(evt.getPropertyName()) && (int) evt.getNewValue() < 0) {
throw new PropertyVetoException("Negative ID not allowed", evt);
}
});
} catch (Exception e) {
e.printStackTrace();
}
JPanel panel = new JPanel(new GridLayout(6, 2, 5, 5));
JTextField nameField = new JTextField();
JTextField idField = new JTextField();
JTextField salaryField = new JTextField();
JTextField deptField = new JTextField();
JButton setBtn = new JButton("Set");
JButton getBtn = new JButton("Get");
JTextArea outputArea = new JTextArea(5, 30);
outputArea.setEditable(false);
panel.add(new JLabel("Name:"));
panel.add(nameField);
panel.add(new JLabel("ID:"));
panel.add(idField);
panel.add(new JLabel("Salary:"));
panel.add(salaryField);
panel.add(new JLabel("Department:"));
panel.add(deptField);
panel.add(setBtn);
panel.add(getBtn);
panel.add(new JLabel("Output:"));
panel.add(new JScrollPane(outputArea));
setBtn.addActionListener(e -> {
try {
bean.setName(nameField.getText());
bean.setId(Integer.parseInt(idField.getText()));
bean.setSalary(Double.parseDouble(salaryField.getText()));
bean.setDepartment(deptField.getText());
JOptionPane.showMessageDialog(frame, "Employee details set successfully!");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Invalid number format", "Error",
JOptionPane.ERROR_MESSAGE);
} catch (PropertyVetoException ex) {
JOptionPane.showMessageDialog(frame, "Vetoed: " + ex.getMessage(), "Veto",
JOptionPane.WARNING_MESSAGE);
}
});
getBtn.addActionListener(e -> {
outputArea.setText("Employee Details:\n");
outputArea.append("Name: " + bean.getName() + "\n");
outputArea.append("ID: " + bean.getId() + "\n");
outputArea.append("Salary: " + bean.getSalary() + "\n");
outputArea.append("Department: " + bean.getDepartment() + "\n");
});
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
How the Code Works:
● EmployeeBean class is a JavaBean with 4 properties: name, id, salary, and department.
● It supports bound properties (notifies listeners when property changes) via
PropertyChangeSupport.
● It supports constrained properties (listeners can veto changes) via
VetoableChangeSupport — here used to prevent negative IDs.
● The GUI allows users to set these properties via text fields and buttons.
● Clicking Set updates the bean properties; invalid input or veto triggers error messages.
● Clicking Get shows current employee details in a non-editable text area.
● Property changes print messages to the console.
Swing Components & Their Properties:
Componen
Purpose Important Properties / Features
t
JFrame Main window Title, size, close operation
JPanel Holds form inputs and buttons Uses GridLayout(6, 2, 5, 5) for neat grid
Input fields for name, id, salary,
JTextField Editable text input
department
JButton Buttons for setting and getting data Action listeners to handle clicks
JLabel Descriptive labels for inputs Displays static text
Non-editable, wrapped in JScrollPane for
JTextArea Displays output employee info
scroll
JScrollPane Scroll container for JTextArea Provides scrolling capability
JavaBeans Features Used:
● Properties: name, id, salary, department with getters/setters.
● Bound Properties: Fires PropertyChangeEvent on changes.
● Constrained Properties: Fires VetoableChangeEvent, e.g., veto if id < 0.
● Listeners: PropertyChangeListener logs changes; VetoableChangeListener prevents
invalid IDs.
OUTPUT:
Q3. Develop a Java RMI-based distributed application that performs basic
arithmetic operations (add, subtract, multiply, divide). Implement the RMI
interfaces and server-client architecture. Demonstrate method invocation
from the client side and explain parameter marshalling and remote object
activation."
i)Arithmetic.java code:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Arithmetic extends Remote {
double add(double a, double b) throws RemoteException;
double subtract(double a, double b) throws RemoteException;
double multiply(double a, double b) throws RemoteException;
double divide(double a, double b) throws RemoteException;
}
ii) ArithmeticImpl.java code:
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class ArithmeticImpl extends UnicastRemoteObject implements Arithmetic {
protected ArithmeticImpl() throws RemoteException {
super();
}
public double add(double a, double b) throws RemoteException {
return a + b;
}
public double subtract(double a, double b) throws RemoteException {
return a - b;
}
public double multiply(double a, double b) throws RemoteException {
return a * b;
}
public double divide(double a, double b) throws RemoteException {
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;
}
}
iii) ArithmeticServer.java code:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class ArithmeticServer {
public static void main(String[] args) {
try {
ArithmeticImpl obj = new ArithmeticImpl();
Registry registry = LocateRegistry.createRegistry(1099); // default RMI registry port
registry.rebind("ArithmeticService", obj);
System.out.println("ArithmeticService bound and ready.");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
iv) ArithmeticClient.java code:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class ArithmeticClient {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
Arithmetic stub = (Arithmetic) registry.lookup("ArithmeticService");
double a = 10.0, b = 5.0;
System.out.println("Add: " + stub.add(a, b));
System.out.println("Subtract: " + stub.subtract(a, b));
System.out.println("Multiply: " + stub.multiply(a, b));
System.out.println("Divide: " + stub.divide(a, b));
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
How the Code Works:
RMI (Remote Method Invocation) allows a Java program to invoke methods on an object
running in another JVM (potentially on another machine).
You define a remote interface (Arithmetic) that declares methods to be called remotely.
You implement this interface on the server side (ArithmeticImpl), extending
UnicastRemoteObject to create a remote object.
The server creates and binds this remote object to the RMI registry under the name
"ArithmeticService".
The client looks up this service in the registry and obtains a stub (a proxy object).
When the client calls methods like add, the call is marshalled (parameters serialized), sent over
the network, executed on the server, and the result is sent back.
Remote object activation happens when the client obtains the stub and makes remote calls
transparently, without worrying about networking details.
Components and Their Properties:
Component Role Key Properties/Details
Remote interface defining Extends java.rmi.Remote; methods throw
Arithmetic
arithmetic methods RemoteException
Server-side implementation of Extends UnicastRemoteObject for remote
ArithmeticImpl
Arithmetic access; implements methods
ArithmeticServe Creates instance of ArithmeticImpl; binds to
RMI server setup
r registry on port 1099
Creates and obtains RMI registry; binds service
LocateRegistry RMI registry management
with a name
Client that invokes remote Looks up registry, retrieves stub, invokes
ArithmeticClient
methods methods remotely
Client-side proxy for remote Marshals method calls and parameters; sends
Stub
object requests to server
Skeleton Server-side dispatcher (Java Receives requests, unmarshals parameters,
(hidden) versions < Java 5) invokes actual methods
4. "Create a simple online feedback system using Servlets and JSP. The user
submits feedback via an HTML form, which is processed using a Servlet. The
servlet stores feedback in a database and forwards the response to a JSP page.
Implement session tracking to show user history and use cookies to store their
username. Compare output using both JSP and Servlet-based responses."
i)HTML Form code:
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form</title>
</head>
<body>
<h2>Submit your Feedback</h2>
<form action="submitFeedback" method="post">
Name: <input type="text" name="username" id="username" required><br><br>
Feedback: <br>
<textarea name="comments" rows="5" cols="40" required></textarea><br><br>
<input type="submit" value="Submit Feedback">
</form>
<script>
window.onload = function() {
const cookies = document.cookie.split(';');
for(let c of cookies) {
let [name, value] = c.trim().split('=');
if(name === 'username') {
document.getElementById('username').value = decodeURIComponent(value);
break;
}
}
}
</script>
</body>
</html>
ii) Servlet to Process Feedback and Forward to JSP code:
package com.example.feedback;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/submitFeedback")
public class FeedbackServlet extends HttpServlet {
private static final String DB_URL = "jdbc:mysql://localhost:3306/feedback_db";
private static final String DB_USER = "root"; // change if needed
private static final String DB_PASS = "yourpassword"; @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String comments = request.getParameter("comments");
try (Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
PreparedStatement ps = con.prepareStatement("INSERT INTO feedbacks(username,
comments) VALUES (?, ?)")) {
ps.setString(1, username);
ps.setString(2, comments);
ps.executeUpdate();
} catch (SQLException e) {
throw new ServletException("DB error", e);
}
HttpSession session = request.getSession();
List<String> history = (List<String>) session.getAttribute("feedbackHistory");
if(history == null) {
history = new ArrayList<>();
}
history.add(comments);
session.setAttribute("feedbackHistory", history);
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(7 * 24 * 60 * 60);
response.addCookie(cookie);
request.setAttribute("username", username);
request.setAttribute("comments", comments);
request.setAttribute("history", history);
RequestDispatcher rd = request.getRequestDispatcher("feedback.jsp");
rd.forward(request, response);
@Override
public void init() throws ServletException {
super.init();
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Load MySQL driver
} catch (ClassNotFoundException e) {
throw new ServletException(e);
}
}
}
iii) JSP page to display feedback and session history code:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<html>
<head>
<title>Feedback Received</title>
</head>
<body>
<h2>Thank you for your feedback, <%= request.getAttribute("username") %>!</h2>
<p>Your comment:</p>
<p><b><%= request.getAttribute("comments") %></b></p>
<h3>Your feedback history this session:</h3>
<ul>
<%
List<String> history = (List<String>) request.getAttribute("history");
if(history != null) {
for(String fb : history) {
%>
<li><%= fb %></li>
<%
}
} else {
%>
<li>No previous feedback in this session.</li>
<%
}
%>
</ul>
<a href="index.html">Submit more feedback</a>
</body>
</html>
iv) Alternative servlet-based response code:
package com.example.feedback;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/submitFeedbackAlt")
public class FeedbackServletResponse extends HttpServlet {
private static final String DB_URL = "jdbc:mysql://localhost:3306/feedback_db";
private static final String DB_USER = "root";
private static final String DB_PASS = "yourpassword";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
String username = request.getParameter("username");
String comments = request.getParameter("comments");
try (Connection con = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASS);
PreparedStatement ps = con.prepareStatement("INSERT INTO feedbacks(username,
comments) VALUES (?, ?)")) {
ps.setString(1, username);
ps.setString(2, comments);
ps.executeUpdate();
} catch (SQLException e) {
throw new ServletException("DB error", e);
}
HttpSession session = request.getSession();
List<String> history = (List<String>) session.getAttribute("feedbackHistory");
if(history == null) {
history = new ArrayList<>();
}
history.add(comments);
session.setAttribute("feedbackHistory", history);
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(7 * 24 * 60 * 60);
response.addCookie(cookie);
response.setContentType("text/html;charset=UTF-8");
try (var out = response.getWriter()) {
out.println("<html><head><title>Feedback Received</title></head><body>");
out.println("<h2>Thank you for your feedback, " + username + "!</h2>");
out.println("<p>Your comment:</p>");
out.println("<p><b>" + comments + "</b></p>");
out.println("<h3>Your feedback history this session:</h3>");
out.println("<ul>");
for(String fb : history) {
out.println("<li>" + fb + "</li>");
}
out.println("</ul>");
out.println("<a href='index.html'>Submit more feedback</a>");
out.println("</body></html>");
}
}
@Override
public void init() throws ServletException {
super.init();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ServletException(e);
}
}
}
v) web.xml Configuration code:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>FeedbackServlet</servlet-name>
<servlet-class>com.example.feedback.FeedbackServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FeedbackServlet</servlet-name>
<url-pattern>/submitFeedback</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>FeedbackServletResponse</servlet-name>
<servlet-class>com.example.feedback.FeedbackServletResponse</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>FeedbackServletResponse</servlet-name>
<url-pattern>/submitFeedbackAlt</url-pattern>
</servlet-mapping>
</web-app>
How It Works:
● User fills a feedback form (HTML).
● Servlet processes the form, saves feedback to the database, and stores feedback history in
the session.
● Servlet sets a cookie with the username for future visits.
● Servlet forwards the request to a JSP page that shows a thank you message and user’s
feedback history.
● Alternatively, the servlet can generate the entire HTML response itself (for comparison).
Components & Key Properties:
Component Purpose Key Properties
Collects username and
HTML Form <form>, POST method, cookies read by JS
feedback
Handles requests, DB doPost(), JDBC insert, session tracking,
Servlet
operations, session, cookies cookie creation, request forwarding
Generates dynamic HTML
JSP Reads request/session data, outputs HTML
response
Database
Stores feedback permanently feedbacks table, SQL INSERT
(MySQL)
Session Tracks user’s feedback history HttpSession to save list
Remembers username
Cookie Stores username, max age set
client-side
5. "Create a Java application using JDBC to perform CRUD (Create, Read, Update,
Delete) operations on a student database. Use different JDBC driver types,
connect to a MySQL/PostgreSQL database, and demonstrate execution of SQL
queries using both Statement.
CRUD using Statement code:
import java.sql.*;
import java.util.Scanner;
public class StudentCRUDApp {
static final String JDBC_URL = "jdbc:mysql://localhost:3306/school";
static final String USER = "root";
static final String PASSWORD = "";
public static void main(String[] args) {
try (
Connection conn = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
Scanner sc = new Scanner(System.in)) {
Class.forName("com.mysql.cj.jdbc.Driver");
while (true) {
System.out.println("\n--- Student CRUD App ---");
System.out.println("1. Add Student");
System.out.println("2. View Students");
System.out.println("3. Update Student");
System.out.println("4. Delete Student");
System.out.println("5. Exit");
System.out.print("Choose: ");
int choice = sc.nextInt();
Statement stmt = conn.createStatement();
switch (choice) {
case 1:
System.out.print("Enter ID: ");
int id = sc.nextInt();
sc.nextLine(); // consume newline
System.out.print("Enter Name: ");
String name = sc.nextLine();
System.out.print("Enter Age: ");
int age = sc.nextInt();
sc.nextLine();
System.out.print("Enter Grade: ");
String grade = sc.nextLine();
String insertQuery = "INSERT INTO student VALUES(" + id + ", '" + name + "',
" + age + ", '"
+ grade + "')";
stmt.executeUpdate(insertQuery);
System.out.println("Student added.");
break;
case 2:
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
System.out.println("ID | Name | Age | Grade");
while (rs.next()) {
System.out.println(rs.getInt("id") + " | " +
rs.getString("name") + " | " +
rs.getInt("age") + " | " +
rs.getString("grade"));
}
break;
case 3:
System.out.print("Enter ID to update: ");
int uid = sc.nextInt();
sc.nextLine();
System.out.print("Enter New Name: ");
String newName = sc.nextLine();
System.out.print("Enter New Age: ");
int newAge = sc.nextInt();
sc.nextLine();
System.out.print("Enter New Grade: ");
String newGrade = sc.nextLine();
String updateQuery = "UPDATE student SET name='" + newName + "', age=" +
newAge + ", grade='"
+ newGrade + "' WHERE id=" + uid;
stmt.executeUpdate(updateQuery);
System.out.println("Student updated.");
break;
case 4:
System.out.print("Enter ID to delete: ");
int did = sc.nextInt();
String deleteQuery = "DELETE FROM student WHERE id=" + did;
stmt.executeUpdate(deleteQuery);
System.out.println("Student deleted.");
break;
case 5:
System.out.println("Exiting...");
stmt.close();
conn.close();
return;
default:
System.out.println("Invalid choice.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
How the Code Works:
● Connects to MySQL database school using JDBC.
● Displays a menu to perform CRUD:
● Add, View, Update, Delete a student.
● Uses Statement to run SQL queries.
● Takes user input with Scanner.
● Handles all operations in a loop until the user exits.
Components Used & Their Properties:
Component Purpose Key Properties / Role
Created with
Connection Connects to the database
DriverManager.getConnection()
Used for INSERT, SELECT, UPDATE,
Statement Executes SQL commands
DELETE
Scanner Reads user input from console Reads int and String values
ResultSet Holds data returned from query Used to display student list
Class.forName
Loads MySQL JDBC driver Ensures the driver class is registered
()
Commands to interact with the Dynamic queries using string
SQL Queries
table concatenation