JAVA Practical
JAVA Practical
1) Create a hierarchy of employee, manager, sales manager, they should have the
following functionality:
a. Employee: display name, date of birth and id of employee.
b. Manager: display all above information with salary drawn
c. Sales manager: display all above information and commission if applicable.
Ans:
import java.util.Scanner;
class Employee {
String name;
String dob;
int id;
void display() {
System.out.println("Name: " + name);
System.out.println("Date of Birth: " + dob);
System.out.println("ID: " + id);
}
}
void display() {
super.display();
System.out.println("Commission: ₹" + commission);
}
}
@Override
public void displayAccountInfo() {
System.out.println("--- Savings Account Details ---");
super.displayAccountInfo();
}
}
int choice;
do {
System.out.println("\n--- Menu ---");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Check Balance");
System.out.println("4. Account Info");
System.out.println("5. Exit");
System.out.print("Enter choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter amount to deposit: ");
double deposit = sc.nextDouble();
account.deposit(deposit);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double withdraw = sc.nextDouble();
account.withdraw(withdraw);
break;
case 3:
account.displayBalance();
break;
case 4:
account.displayAccountInfo();
break;
case 5:
System.out.println("Thank you for banking with us!");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 5);
sc.close();
}
}
3) Develop a java-based library management system that demonstrate OOP principle
and use exception handling to handle cases like issuing books, returning books, and
managing overdue penalties.
Ans:
import java.util.*;
void listBooks() {
System.out.println("\n--- Book List ---");
for (int i = 0; i < books.size(); i++) {
System.out.print((i + 1) + ". ");
books.get(i).display();
}
}
int choice;
do {
System.out.println("\n--- Library Menu ---");
System.out.println("1. List Books");
System.out.println("2. Issue Book");
System.out.println("3. Return Book");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
try {
switch (choice) {
case 1:
lib.listBooks();
break;
case 2:
lib.listBooks();
System.out.print("Enter book number to issue: ");
int issueIndex = sc.nextInt() - 1;
System.out.print("Enter number of days to borrow: ");
int days = sc.nextInt();
lib.getBook(issueIndex).issueBook(days);
break;
case 3:
lib.listBooks();
System.out.print("Enter book number to return: ");
int returnIndex = sc.nextInt() - 1;
System.out.print("Enter actual days kept: ");
int actualDays = sc.nextInt();
lib.getBook(returnIndex).returnBook(actualDays);
break;
case 4:
System.out.println("Thank you for using the library system.");
break;
default:
System.out.println("Invalid choice!");
}
} catch (OverdueException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Something went wrong. Please try again.");
}
} while (choice != 4);
sc.close();
}
}
4) Implementing the operation of stack and queue using package and interface.
Ans:
ds/MyInterface.java — Interface
package ds;
import java.util.*;
import java.util.Scanner;
if (type == 1)
ds = new MyStack();
else
ds = new MyQueue();
do {
System.out.println("\n--- Menu ---");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter element: ");
int element = sc.nextInt();
ds.insert(element);
break;
case 2:
ds.delete();
break;
case 3:
ds.display();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice.");
}
} while (choice != 4);
sc.close();
}
}
5) Write a program to accept roll no. marks from user. Throw user define exception
marks out of bound of marks are 100.
Ans:
import java.util.Scanner;
// User-defined exception
class MarksOutOfBoundException extends Exception {
public MarksOutOfBoundException(String message) {
super(message);
}
}
try {
System.out.print("Enter Roll Number: ");
int rollNo = sc.nextInt();
} catch (MarksOutOfBoundException e) {
System.out.println("Error: " + e.getMessage());
}
sc.close();
}
}
6) Write a program to implement student information in a file and perform the
operation on it.
Ans:
import java.io.*;
import java.util.*;
switch (choice) {
case 1:
addStudent(scanner, students);
break;
case 2:
viewAllStudents(students);
break;
case 3:
searchStudent(scanner, students);
break;
case 4:
deleteStudent(scanner, students);
break;
case 5:
saveAndExit(students);
System.out.println("Exiting.");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
// Method to delete a student by roll number using simple for loop by index
private static void deleteStudent(Scanner scanner, List<Student> students) {
System.out.print("Enter roll number to delete: ");
int rollNumber = Integer.parseInt(scanner.nextLine());
if (!found) {
System.out.println("Student not found.");
}
}
import java.awt.*;
import java.awt.event.*;
SLIP7() {
setSize(200, 400);
setLayout(new GridLayout(4, 4));
add(l1);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
add(b0);
add(badd);
add(bsub);
add(bmul);
add(bdiv);
add(beq);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
badd.addActionListener(this);
bsub.addActionListener(this);
bmul.addActionListener(this);
bdiv.addActionListener(this);
beq.addActionListener(this);
setSize(300, 300);
setVisible(true);
}
if (str.equals("1")) {
l1.setText(l1.getText() + "1");
} else if (str.equals("2")) {
l1.setText(l1.getText() + "2");
} else if (str.equals("3")) {
l1.setText(l1.getText() + "3");
} else if (str.equals("4")) {
l1.setText(l1.getText() + "4");
} else if (str.equals("5")) {
l1.setText(l1.getText() + "5");
} else if (str.equals("6")) {
l1.setText(l1.getText() + "6");
} else if (str.equals("7")) {
l1.setText(l1.getText() + "7");
} else if (str.equals("8")) {
l1.setText(l1.getText() + "8");
} else if (str.equals("9")) {
l1.setText(l1.getText() + "9");
} else if (str.equals("0")) {
l1.setText(l1.getText() + "0");
} else if (str.equals("+")) {
num1 = Double.parseDouble(l1.getText());
l1.setText("");
operator = 1;
} else if (str.equals("-")) {
num1 = Double.parseDouble(l1.getText());
l1.setText("");
operator = 2;} else if (str.equals("*")) {
num1 = Double.parseDouble(l1.getText());
l1.setText("");
operator = 3;
} else if (str.equals("/")) {
num1 = Double.parseDouble(l1.getText());
l1.setText("");
operator = 4;
} else if (str.equals("=")) {
num2 = Double.parseDouble(l1.getText());
switch (operator) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
result = num1 / num2;
break;
}
l1.setText("" + result);
}
}
// Declare components
private Frame frame;
private Label nameLabel, emailLabel, passwordLabel, confirmPasswordLabel,
genderLabel;
private TextField nameField, emailField, passwordField, confirmPasswordField;
private TextArea addressArea;
private Checkbox maleCheckbox, femaleCheckbox;
private Button submitButton, resetButton;
public RegistrationFormAWT() {
// Create Frame
frame = new Frame("Registration Form");
// Create Labels
nameLabel = new Label("Name:");
emailLabel = new Label("Email:");
passwordLabel = new Label("Password:");
confirmPasswordLabel = new Label("Confirm Password:");
genderLabel = new Label("Gender:");
// Create TextFields
nameField = new TextField();
emailField = new TextField();
passwordField = new TextField(); // Use TextField for password input
confirmPasswordField = new TextField(); // Use TextField for confirm password
input
addressArea = new TextArea();
// Create Buttons
submitButton = new Button("Submit");
resetButton = new Button("Reset");
// Set Layout
frame.setLayout(new GridLayout(8, 2, 10, 10));
frame.add(emailLabel);
frame.add(emailField);
frame.add(passwordLabel);
frame.add(passwordField);
frame.add(confirmPasswordLabel);
frame.add(confirmPasswordField);
frame.add(genderLabel);
Panel genderPanel = new Panel();
genderPanel.add(maleCheckbox);
genderPanel.add(femaleCheckbox);
frame.add(genderPanel);
frame.add(new Label("Address:"));
frame.add(addressArea);
frame.add(submitButton);
frame.add(resetButton);
if (password.equals(confirmPassword)) {
// Show registration success
showMessage("Registration Successful\nName: " + name + "\nEmail: " +
email + "\nGender: " + gender);
} else {
// Show error message if passwords don't match
showMessage("Password mismatch. Please try again.");
}
}
});
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Reset all fields
nameField.setText("");
emailField.setText("");
passwordField.setText("");
confirmPasswordField.setText("");
addressArea.setText("");
maleCheckbox.setState(false);
femaleCheckbox.setState(false);
}
});
public TrafficLightSimulatorAWT() {
setTitle("Traffic Light Simulation");
setSize(300, 400);
setVisible(true);
setBackground(Color.WHITE);
@Override
public void paint(Graphics g) {
// Draw the signal box
g.setColor(Color.BLACK);
g.drawRect(100, 80, 100, 240);
// Red light
g.setColor(currentLight.equals("RED") ? Color.RED : Color.GRAY);
g.fillOval(120, 100, 60, 60);
// Yellow light
g.setColor(currentLight.equals("YELLOW") ? Color.YELLOW : Color.GRAY);
g.fillOval(120, 170, 60, 60);
// Green light
g.setColor(currentLight.equals("GREEN") ? Color.GREEN : Color.GRAY);
g.fillOval(120, 240, 60, 60);
}
@Override
public void run() {
try {
while (true) {
currentLight = "RED";
repaint();
Thread.sleep(3000); // 3 seconds red
currentLight = "YELLOW";
repaint();
Thread.sleep(1000); // 1 second yellow
currentLight = "GREEN";
repaint();
Thread.sleep(3000); // 3 seconds green
}
} catch (InterruptedException e) {
System.out.println("Simulation stopped.");
}
}
String msg;
while ((msg = reader.readLine()) != null) {
System.out.println("Client: " + msg);
System.out.print("You: ");
String reply = input.readLine();
writer.println(reply);
}
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String msg;
while (true) {
System.out.print("You: ");
msg = input.readLine();
writer.println(msg);
USE testdb;
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50)
);
Connection conn;
public DatabaseGUIApp() {
setTitle("SQL Query Executor");
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
connectToDatabase();
setVisible(true);
}
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
output.append(rs.getString(i)).append("\t");
}
output.append("\n");
}
resultArea.setText(output.toString());
} else {
int rows = stmt.executeUpdate(query);
resultArea.setText("Query executed. Rows affected: " + rows);
}
} catch (SQLException ex) {
resultArea.setText("SQL Error: " + ex.getMessage());
}
}
Final Tips
• Replace "your_password" in the code with your actual MySQL root password.
• If you use a different DB (like PostgreSQL or SQLite), the driver and URL will change.
Would you like me to send you a ZIP file with all this ready to run in IntelliJ?
12) Write a program to demonstrate socket programming, e.g. send hello to server
from client.
Ans:
SimpleServer.java
import java.io.*;
import java.net.*;
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SimpleClient.java
import java.io.*;
import java.net.*;
out.println("Hello Server");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}