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

JAVAlab

The document outlines various Java programming tasks, including creating GUI applications for calculating sums and differences, designing registration forms, and handling mouse and key events. It also includes JDBC operations for database interactions and RMI applications for client-server communication. Each task provides specific requirements and sample code snippets for implementation.

Uploaded by

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

JAVAlab

The document outlines various Java programming tasks, including creating GUI applications for calculating sums and differences, designing registration forms, and handling mouse and key events. It also includes JDBC operations for database interactions and RMI applications for client-server communication. Each task provides specific requirements and sample code snippets for implementation.

Uploaded by

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

Table of Contents

1. Write a GUI application to find sum and difference of two integer numbers. Use two text fields for input
and third text field for output. Your program should display sum if the user presses the mouse and
difference if the user releases the mouse........................................................................................................ 3
2.Design and develop the below registration form and when the user press on the submit button then
fetch the value of elements from the left side and display the results in the right side of JTextArea. ............ 5
3.Write Java Code to display a window with a label and three buttons as shown in the figure. When the
user clicks a button, it should change the background color of the panel that contains the components and
the foreground color of the label. .................................................................................................................... 7
4. Write a Java code and display the window with a JLabel, JButton and JTexField as shown in figure below.
When a user clicks on a button, it should convert the value of Celsius to Fahrenheit and display the result
in text Field....................................................................................................................................................... 9
6.Write a Java code and display the window with textField and register the text field with a KeyListner.
Handle the following key events. a.When user type b in the text field changes the background color of the
window. b.When a user presses any key, display the name of the key in the window. ................................. 10
7.Write a program to prepare one small form containing fields employee id, name, and salary with buttons
view, insert, and delete. And perform the operations as indicated by button names. ................................. 12
8.Write a JDBC program to insert multiple records into a Books table using PreparedStatement. The table
should include the columns: BookID, Title, Author, Price, and Genre. .......................................................... 14
9.Write a JDBC program to update the Salary of employees in the Employees table by 10% if their current
salary is below 30000. .................................................................................................................................... 15
10.Develop a small form using Java Swing connected to JDBC where the user can: i. View a student's full
profile using the RollNo. ii. Update the student’s Major and Division. iii. Add a new student to the Students
table. .............................................................................................................................................................. 16
11. Write a JavaBean program that finds square and cube value in terms of properties. ............................. 20
12.Write a JavaBean program and modify the district name using JavaBean Bound property. .................... 21
13.Write a JavaBean program for students of Texas International college, if the student has scored more
than 40 in Advanced JavaProgramming then set the student as passed otherwise fail. Use JavaBean
Constrained. ................................................................................................................................................... 22
14. Write a JavaBean program and check if odd or even number and save then retrieve the state of the
bean using JavaBean persistence. .................................................................................................................. 23
15.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. ............................................................................................... 25
16.Create a JSP page that contains three textboxes to input three numbers and a button. It should display
the greatest and smallest number among three numbers when the button is clicked. ................................ 26
17.Create JSP web from to take inputs: name, password, gender, email and phone number and submit it to
servlet file which may simply print the values of from submission. .............................................................. 28
18.Write a client/server application using RMI to find sum and difference of two numbers. ....................... 31
19.Write a client-server application in RMI to find the selling price of an item with cost price Rs. 5000 after
a discount of Rs.50. ........................................................................................................................................ 33
20.Create a RMI application such that a client sends an integer number to the server and the server return
the factorial value of that integer................................................................................................................... 34
21.Create a RMI application such that a client sends an String to the server and the server return the
reverse of that String. .................................................................................................................................... 36
22.Write a client/server application using RMI to find division between two numbers and also the
remainder. ...................................................................................................................................................... 38
1. Write a GUI application to find sum and difference of two integer
numbers. Use two text fields for input and third text field for output.
Your program should display sum if the user presses the mouse and
difference if the user releases the mouse.

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

public class SumDifferenceCalculator extends JFrame {


private JTextField inputField1;
private JTextField inputField2;
private JTextField outputField;

public SumDifferenceCalculator()
setTitle("Sum and Difference Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLayout(new GridLayout(4, 2, 10, 10));

JLabel label1 = new JLabel("First Number:");


inputField1 = new JTextField();
JLabel label2 = new JLabel("Second Number:");
inputField2 = new JTextField();
JLabel outputLabel = new JLabel("Result:");
outputField = new JTextField();
outputField.setEditable(false);

add(label1);
add(inputField1);
add(label2);
add(inputField2);
add(outputLabel);
add(outputField);
outputField.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
calculateSum();
}
@Override
public void mouseReleased(MouseEvent e) {
calculateDifference();
}
});

add(new JLabel()); // Empty label for layout


add(new JLabel()); // Empty label for layout
setLocationRelativeTo(null);
}
private void calculateSum() {
try {
int num1 = Integer.parseInt(inputField1.getText());
int num2 = Integer.parseInt(inputField2.getText());
int sum = num1 + num2;
outputField.setText(String.valueOf(sum));
} catch (NumberFormatException ex) {
outputField.setText("Invalid input");
}
}
private void calculateDifference() {
try {
int num1 = Integer.parseInt(inputField1.getText());
int num2 = Integer.parseInt(inputField2.getText());
int difference = num1 - num2;
outputField.setText(String.valueOf(difference));
} catch (NumberFormatException ex) {
outputField.setText("Invalid input");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SumDifferenceCalculator calculator = new SumDifferenceCalculator();
calculator.setVisible(true);
});
}
}
2.Design and develop the below registration form and when the user
press on the submit button then fetch the value of elements from the left
side and display the results in the right side of JTextArea.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RegistrationForm extends JFrame {


private JTextField nameField;
private JTextField mobileField;
private JRadioButton maleRadio;
private JRadioButton femaleRadio;
private JSpinner dobSpinner;
private JTextArea addressArea;
private JCheckBox termsCheck;
private JTextArea resultArea;

public RegistrationForm() {
setTitle("Registration Form");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 500);
setLayout(new GridLayout(1, 2, 10, 10));
JPanel inputPanel = new JPanel(new GridLayout(8, 1, 10, 10));
inputPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
inputPanel.add(new JLabel("Name:"));
nameField = new JTextField();
inputPanel.add(nameField);
inputPanel.add(new JLabel("Mobile:"));
mobileField = new JTextField();
inputPanel.add(mobileField)
inputPanel.add(new JLabel("Gender:"));
JPanel genderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
maleRadio = new JRadioButton("Male", true);
femaleRadio = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleRadio);
genderGroup.add(femaleRadio);
genderPanel.add(maleRadio);
genderPanel.add(femaleRadio);
inputPanel.add(genderPanel);
inputPanel.add(new JLabel("Date of Birth:"));
dobSpinner = new JSpinner(new SpinnerDateModel());
JSpinner.DateEditor dobEditor = new JSpinner.DateEditor(dobSpinner, "dd/MM/yyyy");
dobSpinner.setEditor(dobEditor);
inputPanel.add(dobSpinner)
inputPanel.add(new JLabel("Address:"));
addressArea = new JTextArea(3, 20);
addressArea.setLineWrap(true);
JScrollPane addressScroll = new JScrollPane(addressArea);
inputPanel.add(addressScroll);
termsCheck = new JCheckBox("Accept Terms And Conditions");
inputPanel.add(termsCheck);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
JButton submitButton = new JButton("Submit");
JButton resetButton = new JButton("Reset");
buttonPanel.add(submitButton);
buttonPanel.add(resetButton);
inputPanel.add(buttonPanel);
JPanel resultPanel = new JPanel(new BorderLayout());
resultPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
resultPanel.add(new JLabel("Registration Details:"), BorderLayout.NORTH);
resultArea = new JTextArea();
resultArea.setEditable(false);
JScrollPane resultScroll = new JScrollPane(resultArea);
resultPanel.add(resultScroll, BorderLayout.CENTER);
add(inputPanel);
add(resultPanel);
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!termsCheck.isSelected()) {
JOptionPane.showMessageDialog(RegistrationForm.this,
"Please accept the terms and conditions",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
String name = nameField.getText();
String mobile = mobileField.getText();
String gender = maleRadio.isSelected() ? "Male" : "Female";
Date dob = (Date) dobSpinner.getValue();
String address = addressArea.getText();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String dobStr = dateFormat.format(dob);
String result = "Name: " + name + "\n" +
"Mobile: " + mobile + "\n" +
"Gender: " + gender + "\n" +
"Date of Birth: " + dobStr + "\n" +
"Address: " + address + "\n\n" +
"Terms Accepted: Yes";
resultArea.setText(result);
}
});
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nameField.setText("");
mobileField.setText("");
maleRadio.setSelected(true);
dobSpinner.setValue(new Date());
addressArea.setText("");
termsCheck.setSelected(false);
resultArea.setText("");
}
});
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
RegistrationForm form = new RegistrationForm();
form.setVisible(true);
});
}
}

3.Write Java Code to display a window with a label and three buttons as
shown in the figure. When the user clicks a button, it should change the
background color of the panel that contains the components and the
foreground color of the label.

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

public class ColorChanger extends JFrame {


private JLabel label;
private JPanel mainPanel;
public ColorChanger() {
setTitle("Colors");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
mainPanel = new JPanel(new BorderLayout());
mainPanel.setOpaque(true);
setContentPane(mainPanel); // Set as content pane to affect whole window
label = new JLabel("Click a button to select a color.", SwingConstants.CENTER);
mainPanel.add(label, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonPanel.setOpaque(false);
JButton redButton = createColorButton("Red", Color.RED, Color.BLACK);
JButton blueButton = createColorButton("Blue", Color.BLUE, Color.WHITE);
JButton yellowButton = createColorButton("Yellow", Color.YELLOW, Color.BLACK);
buttonPanel.add(redButton);
buttonPanel.add(blueButton);
buttonPanel.add(yellowButton);

mainPanel.add(buttonPanel, BorderLayout.CENTER);
setLocationRelativeTo(null);
}
private JButton createColorButton(String text, Color bgColor, Color fgColor) {
JButton button = new JButton(text);
button.addActionListener(e -> {
mainPanel.setBackground(bgColor);
label.setForeground(fgColor);
});
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ColorChanger frame = new ColorChanger();
frame.setVisible(true);
});
}
}
4. Write a Java code and display the window with a JLabel, JButton and
JTexField as shown in figure below. When a user clicks on a button, it
should convert the value of Celsius to Fahrenheit and display the result in
text Field.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TemperatureConverter extends JFrame {


private JTextField celsiusField;
private JTextField fahrenheitField;

public TemperatureConverter() {
setTitle("Celsius to Fahrenheit Converter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLayout(new GridLayout(3, 2, 10, 10));
add(new JLabel("Celsius:"));
celsiusField = new JTextField("0");
add(celsiusField);
add(new JLabel("Fahrenheit:"));
fahrenheitField = new JTextField("32.0 F");
fahrenheitField.setEditable(false);
add(fahrenheitField);
JButton convertButton = new JButton("Convert");
add(convertButton);
add(new JLabel()); // Empty cell for layout
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
double celsius = Double.parseDouble(celsiusField.getText());
double fahrenheit = (celsius * 9/5) + 32;
fahrenheitField.setText(String.format("%.1f F", fahrenheit));
} catch (NumberFormatException ex) {
fahrenheitField.setText("Invalid input");
}
}
});
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TemperatureConverter frame = new TemperatureConverter();
frame.setVisible(true);
});
}
}
5. Write a Java code and display the window with registering mouse listeners. Handle the following mouse
event: a.When the user pressed the mouse, change the background color of the window to Red Color.
b.When the mouse enters the window, change the background color of the window to Green Color. c.When
the mouse exited from the window, change the background color of the window to Yellow Color. d.When the
user releases the mouse, change the background color of the window to Gray color.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseEventDemo extends JFrame implements MouseListener {
public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(Color.WHITE);
addMouseListener(this);
setVisible(true);
}
public void mousePressed(MouseEvent e) {
getContentPane().setBackground(Color.RED);
}
public void mouseReleased(MouseEvent e) {
getContentPane().setBackground(Color.GRAY);
}
public void mouseEntered(MouseEvent e) {
getContentPane().setBackground(Color.GREEN);
}
public void mouseExited(MouseEvent e) {
getContentPane().setBackground(Color.YELLOW);
}
public void mouseClicked(MouseEvent e) {}
public static void main(String[] args) {
new MouseEventDemo();
}
}
6.Write a Java code and display the window with textField and register
the text field with a KeyListner. Handle the following key events. a.When
user type b in the text field changes the background color of the window.
b.When a user presses any key, display the name of the key in the
window.

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

public class KeyEventDemo extends JFrame implements KeyListener {


JTextField textField;
JLabel label;
public KeyEventDemo() {
setTitle("Key Event Demo");
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
textField = new JTextField(20);
label = new JLabel("Key Pressed: ");
textField.addKeyListener(this);
add(textField);
add(label);
setVisible(true);
}
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 'b') {
getContentPane().setBackground(Color.PINK);
}
}
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
}
public void keyReleased(KeyEvent e) {}
public static void main(String[] args) {
new KeyEventDemo();
}
}
7.Write a program to prepare one small form containing fields employee
id, name, and salary with buttons view, insert, and delete. And perform
the operations as indicated by button names.

package com.Lab;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class EmployeeForm extends JFrame implements ActionListener {
JTextField txtId, txtName, txtSalary;
JButton btnInsert, btnView, btnDelete;
Connection con;
PreparedStatement pst;
ResultSet rs;
public EmployeeForm() {
setTitle("Employee Form");
setSize(400, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
add(new JLabel("Employee ID:"));
txtId = new JTextField();
add(txtId);
add(new JLabel("Name:"));
txtName = new JTextField();
add(txtName)
add(new JLabel("Salary:"));
txtSalary = new JTextField();
add(txtSalary);
btnInsert = new JButton("Insert");
btnInsert.addActionListener(this);
add(btnInsert);
btnView = new JButton("View");
btnView.addActionListener(this);
add(btnView);
btnDelete = new JButton("Delete");
btnDelete.addActionListener(this);
add(btnDelete);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Company", "root", "shiva");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "DB Connection Failed: " + e);
}
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
int id = Integer.parseInt(txtId.getText());
if (e.getSource() == btnInsert) {
String name = txtName.getText();
double salary = Double.parseDouble(txtSalary.getText());
pst = con.prepareStatement("INSERT INTO Employee VALUES(?, ?, ?)");
pst.setInt(1, id);
pst.setString(2, name);
pst.setDouble(3, salary);
pst.executeUpdate();
JOptionPane.showMessageDialog(this, "Inserted Successfully");
} else if (e.getSource() == btnView) {
pst = con.prepareStatement("SELECT * FROM Employee WHERE EmpID = ?");
pst.setInt(1, id);
rs = pst.executeQuery();
if (rs.next()) {
txtName.setText(rs.getString("Name"));
txtSalary.setText(String.valueOf(rs.getDouble("Salary")));
} else {
JOptionPane.showMessageDialog(this, "No record found");
}
} else if (e.getSource() == btnDelete) {
pst = con.prepareStatement("DELETE FROM Employee WHERE EmpID = ?");
pst.setInt(1, id);
int i = pst.executeUpdate();
if (i > 0) {
JOptionPane.showMessageDialog(this, "Deleted Successfully");
txtName.setText("");
txtSalary.setText("");
} else {
JOptionPane.showMessageDialog(this, "No record to delete");
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex);
}
}
public static void main(String[] args) {
new EmployeeForm();
}
}
8.Write a JDBC program to insert multiple records into a Books table
using PreparedStatement. The table should include the columns: BookID,
Title, Author, Price, and Genre.
package com.Shiva;
import java.sql.*;

public class InsertBooks {


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

String query = "INSERT INTO Books (BookID, Title, Author, Price, Genre) VALUES (?, ?, ?, ?, ?)";

try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement(query);

pst.setInt(1, 104);
pst.setString(2, "Atomic Habits");
pst.setString(3, "James Clear");
pst.setDouble(4, 499.99);
pst.setString(5, "Self-Help");
pst.executeUpdate();

pst.setInt(1, 105);
pst.setString(2, "The Alchemist");
pst.setString(3, "Paulo Coelho");
pst.setDouble(4, 299.00);
pst.setString(5, "Fiction");
pst.executeUpdate();

pst.setInt(1, 106);
pst.setString(2, "Clean Code");
pst.setString(3, "Robert C. Martin");
pst.setDouble(4, 650.00);
pst.setString(5, "Programming");
pst.executeUpdate();

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


pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
9.Write a JDBC program to update the Salary of employees in the
Employees table by 10% if their current salary is below 30000.
package com.Shiva;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UpdateSalary {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/company";
String user = "root";
String password = "shiva";
String updateQuery = "UPDATE Employee SET Salary = Salary * 1.1 WHERE Salary < 30000";

Connection conn = null;


PreparedStatement pstmt = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
pstmt = conn.prepareStatement(updateQuery);
int rowsUpdated = pstmt.executeUpdate();
System.out.println("Number of employees updated: " + rowsUpdated);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
10.Develop a small form using Java Swing connected to JDBC where the
user can: i. View a student's full profile using the RollNo. ii. Update the
student’s Major and Division. iii. Add a new student to the Students
table.

Consider the following table structure:


CREATE TABLE Students (
RollNo INT PRIMARY KEY,
Name VARCHAR(100),
Level VARCHAR(20),
Division VARCHAR(10),
Major VARCHAR(50)
);

package com.Shiva;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class StudentForm extends JFrame {


private JTextField tfRollNo, tfName, tfLevel, tfDivision, tfMajor;
private JButton btnView, btnUpdate, btnAdd;
private Connection conn;
public StudentForm() {
setTitle("Student Profile Manager");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
initDBConnection();
initComponents();
}
private void initDBConnection() {
String url = "jdbc:mysql://localhost:3306/library";
String user = "root";
String password = "shiva";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "DB connection failed: " + e.getMessage());
System.exit(1);
}
}
private void initComponents() {
setLayout(new GridLayout(7, 2, 5, 5));
add(new JLabel("Roll No:"));
tfRollNo = new JTextField();
add(tfRollNo);
add(new JLabel("Name:"));
tfName = new JTextField();
tfName.setEditable(true); // now editable
add(tfName);
add(new JLabel("Level:"));
tfLevel = new JTextField();
tfLevel.setEditable(true); // now editable
add(tfLevel);
add(new JLabel("Division:"));
tfDivision = new JTextField();
add(tfDivision);
add(new JLabel("Major:"));
tfMajor = new JTextField();
add(tfMajor);
btnView = new JButton("View Profile");
btnUpdate = new JButton("Update Profile");
btnAdd = new JButton("Add New Student");
add(btnView);
add(btnUpdate);
add(btnAdd);
btnView.addActionListener(e -> viewProfile());
btnUpdate.addActionListener(e -> updateProfile());
btnAdd.addActionListener(e -> addStudent());
}
private void viewProfile() {
String rollNoStr = tfRollNo.getText().trim();
if (rollNoStr.isEmpty()) {
JOptionPane.showMessageDialog(this, "Enter Roll No.");
return;
}
try {
int rollNo = Integer.parseInt(rollNoStr);
String sql = "SELECT * FROM Students WHERE RollNo = ?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1, rollNo);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
tfName.setText(rs.getString("Name"));
tfLevel.setText(rs.getString("Level"));
tfDivision.setText(rs.getString("Division"));
tfMajor.setText(rs.getString("Major"));
} else {
JOptionPane.showMessageDialog(this, "Student not found.");
clearFieldsExceptRollNo();
}
rs.close();
pst.close();
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid Roll No.");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
private void updateProfile() {
String rollNoStr = tfRollNo.getText().trim();
String name = tfName.getText().trim();
String level = tfLevel.getText().trim();
String division = tfDivision.getText().trim();
String major = tfMajor.getText().trim();
if (rollNoStr.isEmpty() || name.isEmpty() || level.isEmpty() || division.isEmpty() || major.isEmpty()) {
JOptionPane.showMessageDialog(this, "All fields are required.");
return;
}
try {
int rollNo = Integer.parseInt(rollNoStr);
String sql = "UPDATE Students SET Name = ?, Level = ?, Division = ?, Major = ? WHERE RollNo = ?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, name);
pst.setString(2, level);
pst.setString(3, division);
pst.setString(4, major);
pst.setInt(5, rollNo);
int updated = pst.executeUpdate();
if (updated > 0) {
JOptionPane.showMessageDialog(this, "Student profile updated.");
} else {
JOptionPane.showMessageDialog(this, "Student not found.");
}
pst.close();
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid Roll No.");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
private void addStudent() {
String rollNoStr = tfRollNo.getText().trim();
String name = tfName.getText().trim();
String level = tfLevel.getText().trim();
String division = tfDivision.getText().trim();
String major = tfMajor.getText().trim();
if (rollNoStr.isEmpty() || name.isEmpty() || level.isEmpty() || division.isEmpty() || major.isEmpty()) {
JOptionPane.showMessageDialog(this, "All fields are required to add a student.");
return;
}
try {
int rollNo = Integer.parseInt(rollNoStr);
String sql = "INSERT INTO Students (RollNo, Name, Level, Division, Major) VALUES (?, ?, ?, ?, ?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1, rollNo);
pst.setString(2, name);
pst.setString(3, level);
pst.setString(4, division);
pst.setString(5, major);
pst.executeUpdate();
JOptionPane.showMessageDialog(this, "New student added.");
pst.close();
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid Roll No.");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
private void clearFieldsExceptRollNo() {
tfName.setText("");
tfLevel.setText("");
tfDivision.setText("");
tfMajor.setText("");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
StudentForm form = new StudentForm();
form.setVisible(true);
});
}
}
11. Write a JavaBean program that finds square and cube value in terms
of properties.

public class TestBean {


public static void main(String[] args) {
SquareCubeBean bean = new SquareCubeBean();
bean.setNumber(5);
System.out.println(bean.getNumber());
System.out.println(bean.getSquare());
System.out.println(bean.getCube());
}
}

import java.io.Serializable;
public class SquareCubeBean implements Serializable {
private int number;
private int square;
private int cube;
public SquareCubeBean() {
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
calculateSquareAndCube();
}
public int getSquare() {
return square;
}
public int getCube() {
return cube;
}
private void calculateSquareAndCube() {
this.square = number * number;
this.cube = number * number * number;
}
}
12.Write a JavaBean program and modify the district name using
JavaBean Bound property.
DistrictBean.java
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
public class DistrictBean implements Serializable {
private String districtName;
private PropertyChangeSupport support;
public DistrictBean() {
support = new PropertyChangeSupport(this);
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
String oldName = this.districtName;
this.districtName = districtName;
support.firePropertyChange("districtName", oldName, districtName);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
support.addPropertyChangeListener(pcl);
}
public void removePropertyChangeListener(PropertyChangeListener pcl) {
support.removePropertyChangeListener(pcl);
}
}

TestDistrictBean.java

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class TestDistrictBean {
public static void main(String[] args) {
DistrictBean bean = new DistrictBean();
bean.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("District name changed from " + evt.getOldValue() + " to " + evt.getNewValue());
}
});
bean.setDistrictName("Kathmandu");
bean.setDistrictName("Lalitpur");
}
}
13.Write a JavaBean program for students of Texas International college,
if the student has scored more than 40 in Advanced JavaProgramming
then set the student as passed otherwise fail. Use JavaBean Constrained.
import java.beans.*;
import java.io.Serializable;

public class StudentBean implements Serializable {


private int advancedJavaScore;
private String result;
private VetoableChangeSupport vetoSupport;
public StudentBean() {
vetoSupport = new VetoableChangeSupport(this);
result = "Fail"; // default
}
public int getAdvancedJavaScore() {
return advancedJavaScore;
}
public void setAdvancedJavaScore(int score) throws PropertyVetoException {
int oldScore = this.advancedJavaScore;
String oldResult = this.result;
String newResult = (score > 40) ? "Pass" : "Fail";
vetoSupport.fireVetoableChange("result", oldResult, newResult);
this.advancedJavaScore = score;
this.result = newResult;
}
public String getResult() {
return result;
}
public void addVetoableChangeListener(VetoableChangeListener listener) {
vetoSupport.addVetoableChangeListener(listener);
}
public void removeVetoableChangeListener(VetoableChangeListener listener) {
vetoSupport.removeVetoableChangeListener(listener);
}
}
TestStudentBean.java

import java.beans.PropertyVetoException;
public class TestStudentBean {
public static void main(String[] args) {
StudentBean student = new StudentBean();
student.addVetoableChangeListener(evt -> {
// Accept all changes, but you could throw PropertyVetoException to reject
System.out.println("Result changing from " + evt.getOldValue() + " to " + evt.getNewValue());
});
try {
student.setAdvancedJavaScore(45);
System.out.println("Score: " + student.getAdvancedJavaScore() + ", Result: " + student.getResult());
student.setAdvancedJavaScore(35);
System.out.println("Score: " + student.getAdvancedJavaScore() + ", Result: " + student.getResult());
} catch (PropertyVetoException e) {
System.out.println("Change rejected: " + e.getMessage());
}
}
}

14. Write a JavaBean program and check if odd or even number and save
then retrieve the state of the bean using JavaBean persistence.
NumberBean.java
import java.io.*;

public class NumberBean implements Serializable {


private int number;
private String type; // "Odd" or "Even"
public NumberBean() {}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
this.type = (number % 2 == 0) ? "Even" : "Odd";
}
public String getType() {
return type;
}
public void saveBean(String filename) throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(this);
}
}
public static NumberBean loadBean(String filename) throws IOException, ClassNotFoundException {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
return (NumberBean) ois.readObject();
}
}
}
TestNumberBean.java
public class TestNumberBean {
public static void main(String[] args) {
try {
NumberBean bean = new NumberBean();
bean.setNumber(7);
System.out.println("Number: " + bean.getNumber());
System.out.println("Type: " + bean.getType());
bean.saveBean("numberbean.ser");
NumberBean loadedBean = NumberBean.loadBean("numberbean.ser");
System.out.println("Loaded Number: " + loadedBean.getNumber());
System.out.println("Loaded Type: " + loadedBean.getType());

} catch (Exception e) {
e.printStackTrace();
}
}
}
15.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.

FactorialApplication.java
package com.example;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/factorial")
public class FactorialServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int number = Integer.parseInt(request.getParameter("number"));
long fact = 1;
for (int i = 1; i <= number; i++) {
fact *= i;
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Factorial of " + number + " is: " + fact + "</h2>");
out.println("</body></html>");
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Factorial Calculator</title>
</head>
<body>
<h2>Enter a number:</h2>
<form action="factorial" method="post">
<input type="number" name="number" required>
<input type="submit" value="Calculate">
</form>
</body>
</html>

16.Create a JSP page that contains three textboxes to input three


numbers and a button. It should display the greatest and smallest
number among three numbers when the button is clicked.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>Greatest and Smallest Number</title>
</head>
<body>
<h2>Enter Three Numbers:</h2>
<form method="post">
Number 1: <input type="number" name="num1" required><br><br>
Number 2: <input type="number" name="num2" required><br><br>
Number 3: <input type="number" name="num3" required><br><br>
<input type="submit" value="Find">
</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));


int smallest = Math.min(num1, Math.min(num2, num3));
%>
<h3>Greatest Number: <%= greatest %></h3>
<h3>Smallest Number: <%= smallest %></h3>
<%
}
%>
</body>
</html>
17.Create JSP web from to take inputs: name, password, gender, email
and phone number and submit it to servlet file which may simply print
the values of from submission.
form.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Registration Form</title>
</head>
<body>
<h2>User Registration</h2>
<form action="SubmitForm" method="post">
Name: <input type="text" name="name"><br><br>
Password: <input type="password" name="password"><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
Email: <input type="email" name="email"><br><br>
Phone: <input type="text" name="phone"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
SubmitForm.java (Servlet)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/SubmitForm")
public class SubmitForm extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String name = request.getParameter("name");


String password = request.getParameter("password");
String gender = request.getParameter("gender");
String email = request.getParameter("email");
String phone = request.getParameter("phone");

out.println("<html><body>");
out.println("<h2>Form Submission Details:</h2>");
out.println("<p><strong>Name:</strong> " + name + "</p>");
out.println("<p><strong>Password:</strong> " + password + "</p>");
out.println("<p><strong>Gender:</strong> " + gender + "</p>");
out.println("<p><strong>Email:</strong> " + email + "</p>");
out.println("<p><strong>Phone:</strong> " + phone + "</p>");
out.println("</body></html>");
}
}
web.xml

<web-app>

<servlet>

<servlet-name>SubmitForm</servlet-name>

<servlet-class>SubmitForm</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SubmitForm</servlet-name>
<url-pattern>/SubmitForm</url-pattern>

</servlet-mapping>

</web-app>
18.Write a client/server application using RMI to find sum and difference
of two numbers.
Calc.java (Interface)
import java.rmi.*;
public interface Calc extends Remote {
int sum(int a, int b) throws RemoteException;
int diff(int a, int b) throws RemoteException;
}
CalcImpl.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class CalcImpl extends UnicastRemoteObject implements Calc {
public CalcImpl() throws RemoteException {
super();
}
public int sum(int a, int b) throws RemoteException {
return a + b;
}
public int diff(int a, int b) throws RemoteException {
return a - b;
}
}
Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Server {


public static void main(String[] args) {
try {
Registry reg = LocateRegistry.createRegistry(1099);
CalcImpl obj = new CalcImpl();
reg.rebind("CalcService", obj);
System.out.println("Server ready.");
} catch (Exception e) {
System.out.println("Server error: " + e);
}
}
}
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {


public static void main(String[] args) {
try {
Registry reg = LocateRegistry.getRegistry("localhost", 1099);
Calc stub = (Calc) reg.lookup("CalcService");
int a = 10, b = 5;
int sum = stub.sum(a, b);
int diff = stub.diff(a, b);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + diff);
} catch (Exception e) {
System.out.println("Client error: " + e);
}
}
}
19.Write a client-server application in RMI to find the selling price of an
item with cost price Rs. 5000 after a discount of Rs.50.

PriceCalc.java
import java.rmi.*;

public interface PriceCalc extends Remote {


int calculateSellingPrice(int costPrice, int discount) throws RemoteException;
}
PriceCalcImpl.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class PriceCalcImpl extends UnicastRemoteObject implements PriceCalc {
public PriceCalcImpl() throws RemoteException {
super();
}
public int calculateSellingPrice(int costPrice, int discount) throws RemoteException {
return costPrice - discount;
}
}
Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
Registry reg = LocateRegistry.createRegistry(1099);
PriceCalcImpl obj = new PriceCalcImpl();
reg.rebind("PriceService", obj);
System.out.println("Server ready...");
} catch (Exception e) {
System.out.println("Server error: " + e);
}}
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {


public static void main(String[] args) {
try {
Registry reg = LocateRegistry.getRegistry("localhost", 1099);
PriceCalc stub = (PriceCalc) reg.lookup("PriceService");
int costPrice = 5000;
int discount = 50;
int sellingPrice = stub.calculateSellingPrice(costPrice, discount);
System.out.println("Selling Price: " + sellingPrice);
} catch (Exception e) {
System.out.println("Client error: " + e);
}
}
}

20.Create a RMI application such that a client sends an integer number to


the server and the server return the factorial value of that integer.
Factorial.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class FactorialImpl extends UnicastRemoteObject implements Factorial {
public FactorialImpl() throws RemoteException {
super();
}
public long computeFactorial(int num) throws RemoteException {
long fact = 1;
for (int i = 2; i <= num; i++) {
fact *= i;
}
return fact;
}
}
Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Server {


public static void main(String[] args) {
try {
Registry reg = LocateRegistry.createRegistry(1099);
FactorialImpl obj = new FactorialImpl();
reg.rebind("FactService", obj);
System.out.println("Server ready...");
} catch (Exception e) {
System.out.println("Server error: " + e);
}
}
}
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {


public static void main(String[] args) {
try {
Registry reg = LocateRegistry.getRegistry("localhost", 1099);
Factorial stub = (Factorial) reg.lookup("FactService");
int number = 5;
long result = stub.computeFactorial(number);
System.out.println("Factorial of " + number + " is: " + result);
} catch (Exception e) {
System.out.println("Client error: " + e);
}
}
}

21.Create a RMI application such that a client sends an String to the


server and the server return the reverse of that String.
Reverse.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Reverse extends Remote {
String reverseString(String input) throws RemoteException;
}
ReverseImpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class ReverseImpl extends UnicastRemoteObject implements Reverse {


protected ReverseImpl() throws RemoteException {
super();
}
public String reverseString(String input) throws RemoteException {
System.out.println("Server: Received -> " + input);
String reversed = new StringBuilder(input).reverse().toString();
System.out.println("Server: Returning reversed string -> " + reversed);
return reversed;
}
}
Server.java
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class Server {


public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099); // default RMI port
ReverseImpl obj = new ReverseImpl();
Naming.rebind("ReverseService", obj);
System.out.println("Server is ready...");
} catch (Exception e) {
System.out.println("Server exception: " + e);
}
}
}
Client.java
import java.rmi.Naming;

public class Client {


public static void main(String[] args) {
try {
Reverse stub = (Reverse) Naming.lookup("rmi://localhost/ReverseService");

String input = "Hello RMI";


System.out.println("Client: Sending string to server -> " + input);
String response = stub.reverseString(input);
System.out.println("Client: Received from server -> " + response);
} catch (Exception e) {
System.out.println("Client exception: " + e);
}
}
}

22.Write a client/server application using RMI to find division between


two numbers and also the remainder.

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

public interface Division extends Remote {


String divide(int dividend, int divisor) throws RemoteException;
}
DivisionImpl.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class DivisionImpl extends UnicastRemoteObject implements Division {
protected DivisionImpl() throws RemoteException {
super();
}
@Override
public String divide(int dividend, int divisor) throws RemoteException {
if (divisor == 0) {
return "Error: Division by zero is not allowed.";
}
int quotient = dividend / divisor;
int remainder = dividend % divisor;
String result = "Quotient: " + quotient + ", Remainder: " + remainder;
System.out.println("Server: " + result);
return result;
}
}
Server.java
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class Server {


public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099); // Start RMI registry
DivisionImpl obj = new DivisionImpl();
Naming.rebind("DivisionService", obj);
System.out.println("Server is ready...");
} catch (Exception e) {
System.err.println("Server exception: " + e);
}
}
}
Client.java
import java.rmi.Naming;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Division stub = (Division) Naming.lookup("rmi://localhost/DivisionService");

Scanner sc = new Scanner(System.in);


System.out.print("Enter dividend: ");
int a = sc.nextInt();
System.out.print("Enter divisor: ");
int b = sc.nextInt();

String result = stub.divide(a, b);


System.out.println("Client received: " + result);
} catch (Exception e) {
System.err.println("Client exception: " + e);
}
}
}

You might also like