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 getDetails(Scanner sc) {
System.out.print("Enter name: ");
name = sc.nextLine();
System.out.print("Enter date of birth (dd-mm-yyyy): ");
dob = sc.nextLine();
System.out.print("Enter ID: ");
id = sc.nextInt();
sc.nextLine();
}
void display() {
System.out.println("Name: " + name);
System.out.println("Date of Birth: " + dob);
System.out.println("ID: " + id);
}
}
class Manager extends Employee {
double salary;
void getDetails(Scanner sc) {
super.getDetails(sc);
System.out.print("Enter salary: ");
salary = sc.nextDouble();
}
void display() {
super.display();
System.out.println("Salary: ₹" + salary);
}
}
class SalesManager extends Manager {
double commission;
void getDetails(Scanner sc) {
super.getDetails(sc);
System.out.print("Enter commission: ");
commission = sc.nextDouble();
}
void display() {
super.display();
System.out.println("Commission: ₹" + commission);
}
}
public class EmployeeHierarchy {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SalesManager sm = new SalesManager();
System.out.println("Enter Sales Manager Details:");
sm.getDetails(sc);
System.out.println("\n--- Employee Details ---");
sm.display();
sc.close();
}
}
2) Implement a java program to manage bank account using object-oriented
programming (OOP) concept like classes, inheritance, encapsulation, and
polymorphism. Include features like account creation, deposit, withdrawal and
balance inquiry.
Ans:
import java.util.Scanner;
// Base class - BankAccount (encapsulation used)
class BankAccount {
private String accountHolder;
private int accountNumber;
private double balance;
public BankAccount(String accountHolder, int accountNumber) {
this.accountHolder = accountHolder;
this.accountNumber = accountNumber;
this.balance = 0.0;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("₹" + amount + " deposited successfully.");
} else {
System.out.println("Invalid deposit amount!");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("₹" + amount + " withdrawn successfully.");
} else {
System.out.println("Insufficient balance or invalid amount!");
}
}
public void displayBalance() {
System.out.println("Current Balance: ₹" + balance);
}
public void displayAccountInfo() {
System.out.println("Account Holder: " + accountHolder);
System.out.println("Account Number: " + accountNumber);
displayBalance();
}
}
// Derived class - SavingsAccount (inheritance and polymorphism)
class SavingsAccount extends BankAccount {
public SavingsAccount(String accountHolder, int accountNumber) {
super(accountHolder, accountNumber);
}
@Override
public void displayAccountInfo() {
System.out.println("--- Savings Account Details ---");
super.displayAccountInfo();
}
}
public class BankApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter account holder name:");
String name = sc.nextLine();
System.out.println("Enter account number:");
int accNum = sc.nextInt();
SavingsAccount account = new SavingsAccount(name, accNum);
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.*;
// Custom exception for overdue
class OverdueException extends Exception {
public OverdueException(String message) {
super(message);
}
}
// Base class - Book
class Book {
String title;
String author;
boolean isIssued;
int dueDays;
Book(String title, String author) {
this.title = title;
this.author = author;
this.isIssued = false;
this.dueDays = 0;
}
public void issueBook(int days) throws OverdueException {
if (isIssued) {
throw new OverdueException("Book is already issued!");
}
isIssued = true;
dueDays = days;
System.out.println("Book issued for " + days + " days.");
}
public void returnBook(int actualDays) throws OverdueException {
if (!isIssued) {
throw new OverdueException("Book was not issued!");
}
isIssued = false;
if (actualDays > dueDays) {
int lateDays = actualDays - dueDays;
double fine = lateDays * 2.0; // ₹2 per late day
throw new OverdueException("Returned late by " + lateDays + " days. Fine: ₹"
+ fine);
} else {
System.out.println("Book returned on time. No fine.");
}
dueDays = 0;
}
public void display() {
System.out.println("Title: " + title + ", Author: " + author + ", Issued: " + (isIssued
? "Yes" : "No"));
}
}
// Derived class - Library
class Library {
ArrayList<Book> books = new ArrayList<>();
void addBook(Book book) {
books.add(book);
}
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();
}
}
Book getBook(int index) {
return books.get(index);
}
}
public class LibraryApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Library lib = new Library();
// Adding sample books
lib.addBook(new Book("Java Programming", "James Gosling"));
lib.addBook(new Book("Python Basics", "Guido van Rossum"));
lib.addBook(new Book("Data Structures", "Mark Allen Weiss"));
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;
public interface MyInterface {
void insert(int element);
void delete();
void display();
}
ds/MyStack.java — Stack Class
package ds;
import java.util.*;
public class MyStack implements MyInterface {
Stack<Integer> stack = new Stack<>();
public void insert(int element) {
stack.push(element);
System.out.println("Pushed: " + element);
}
public void delete() {
if (!stack.isEmpty()) {
System.out.println("Popped: " + stack.pop());
} else {
System.out.println("Stack is empty.");
}
}
public void display() {
System.out.println("Stack: " + stack);
}
}
ds/MyQueue.java — Queue Class
package ds;
import java.util.*;
public class MyQueue implements MyInterface {
Queue<Integer> queue = new LinkedList<>();
public void insert(int element) {
queue.add(element);
System.out.println("Enqueued: " + element);
}
public void delete() {
if (!queue.isEmpty()) {
System.out.println("Dequeued: " + queue.remove());
} else {
System.out.println("Queue is empty.");
}
}
public void display() {
System.out.println("Queue: " + queue);
}
}
Main.java — Main Class
import ds.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
MyInterface ds;
int choice, type;
System.out.println("Choose Data Structure:\n1. Stack\n2. Queue");
type = sc.nextInt();
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);
}
}
public class StudentMarks {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter Roll Number: ");
int rollNo = sc.nextInt();
System.out.print("Enter Marks (out of 100): ");
int marks = sc.nextInt();
if (marks > 100) {
throw new MarksOutOfBoundException("Marks cannot be more than
100!");
}
System.out.println("Roll No: " + rollNo + ", Marks: " + marks);
} 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.*;
public class StudentFileManagement {
// File to store student data
private static final String STUDENT_FILE = "students.txt";
// Student class to hold student information
static class Student {
String name;
int rollNumber;
String branch;
// Constructor to initialize student details
public Student(String name, int rollNumber, String branch) {
this.name = name;
this.rollNumber = rollNumber;
this.branch = branch;
}
// Convert student details to a string format for saving to file
@Override
public String toString() {
return name + "," + rollNumber + "," + branch;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Student> students = new ArrayList<>();
// Load existing students from file
loadStudentsFromFile(students);
// Main loop for the student management system
while (true) {
System.out.println("\nStudent Management System");
System.out.println("1. Add Student");
System.out.println("2. View Students");
System.out.println("3. Search Student");
System.out.println("4. Delete Student");
System.out.println("5. Save and Exit");
System.out.print("Enter choice: ");
int choice = getUserChoice(scanner);
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 get user choice and handle invalid input
private static int getUserChoice(Scanner scanner) {
int choice = 0;
try {
choice = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a number.");
}
return choice;
}
// Method to add a new student
private static void addStudent(Scanner scanner, List<Student> students) {
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter roll number: ");
int rollNumber = Integer.parseInt(scanner.nextLine());
System.out.print("Enter branch: ");
String branch = scanner.nextLine();
// Create a new student and add to the list
Student newStudent = new Student(name, rollNumber, branch);
students.add(newStudent);
System.out.println("Student added.");
}
// Method to view all students
private static void viewAllStudents(List<Student> students) {
if (students.isEmpty()) {
System.out.println("No students found.");
return;
}
System.out.println("\n--- Students ---");
for (Student student : students) {
System.out.println(student);
}
}
// Method to search for a student by roll number
private static void searchStudent(Scanner scanner, List<Student> students) {
System.out.print("Enter roll number to search: ");
int rollNumber = Integer.parseInt(scanner.nextLine());
for (Student student : students) {
if (student.rollNumber == rollNumber) {
System.out.println("Found: " + student);
return;
}
}
System.out.println("Student not found.");
}
// 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());
boolean found = false;
for (int i = 0; i < students.size(); i++) {
if (students.get(i).rollNumber == rollNumber) {
students.remove(i);
System.out.println("Student deleted.");
found = true;
break;
}
}
if (!found) {
System.out.println("Student not found.");
}
}
// Method to save students to file and exit
private static void saveAndExit(List<Student> students) {
try (PrintWriter pw = new PrintWriter(new FileWriter(STUDENT_FILE))) {
for (Student student : students) {
pw.println(student); // Write each student to a new line
System.out.println("Saving student: " + student); // Debugging line
}
System.out.println("Data saved.");
} catch (IOException e) {
System.err.println("Error saving data: " + e.getMessage());
}
}
// Method to load students from file
private static void loadStudentsFromFile(List<Student> students) {
File file = new File(STUDENT_FILE);
if (!file.exists()) {
System.out.println("No existing data.");
return;
}
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(",");
if (parts.length == 3) {
try {
String name = parts[0];
int rollNumber = Integer.parseInt(parts[1]);
String branch = parts[2];
students.add(new Student(name, rollNumber, branch));
} catch (NumberFormatException e) {
System.err.println("Skipping invalid line: " + line);
}
} else {
System.err.println("Skipping invalid line: " + line);
}
}
System.out.println("Data loaded.");
} catch (IOException e) {
System.err.println("Error loading data: " + e.getMessage());
}
}
}
7) Create a java-based calculator using AWT component that perform basic arithmetic
operation and handles invalid input gracefully.
Ans:
import java.awt.*;
import java.awt.event.*;
class SLIP7 extends Frame implements ActionListener {
Label l1;
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, badd, bsub, bmul, bdiv, beq;
double num1, num2, result;
int operator;
SLIP7() {
setSize(200, 400);
setLayout(new GridLayout(4, 4));
l1 = new Label("0", Label.RIGHT);
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
b5 = new Button("5");
b6 = new Button("6");
b7 = new Button("7");
b8 = new Button("8");
b9 = new Button("9");
b0 = new Button("0");
badd = new Button("+");
bsub = new Button("-");
bmul = new Button("*");
bdiv = new Button("/");
beq = new Button("=");
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);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
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);
}
}
public static void main(String[] args) {
new SLIP7();
}
}
8) Write a program to design registration process from using AWT components.
Ans:
import java.awt.*;
import java.awt.event.*;
public class RegistrationFormAWT {
// 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();
// Set echo character for password fields (masking the input)
passwordField.setEchoChar('*');
confirmPasswordField.setEchoChar('*');
// Create Checkboxes for gender
maleCheckbox = new Checkbox("Male");
femaleCheckbox = new Checkbox("Female");
// Create Buttons
submitButton = new Button("Submit");
resetButton = new Button("Reset");
// Set Layout
frame.setLayout(new GridLayout(8, 2, 10, 10));
// Add components to frame
frame.add(nameLabel);
frame.add(nameField);
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);
// Event handling for buttons
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String email = emailField.getText();
String password = passwordField.getText();
String confirmPassword = confirmPasswordField.getText();
String gender = maleCheckbox.getState() ? "Male" : "Female";
String address = addressArea.getText();
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);
}
});
// Set frame size and make it visible
frame.setSize(400, 400);
frame.setVisible(true);
}
// Show message in a dialog box
private void showMessage(String message) {
Dialog dialog = new Dialog(frame, "Message", true);
dialog.setSize(250, 100);
dialog.setLayout(new FlowLayout());
Label msgLabel = new Label(message);
dialog.add(msgLabel);
Button closeButton = new Button("Close");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});
dialog.add(closeButton);
dialog.setVisible(true);
}
public static void main(String[] args) {
new RegistrationFormAWT();
}
}
9) Design a java frame to simulate a traffic light system using AWT component. In the
output the light (red, yellow, green) should change based on the timer-based input.
Ans:
import java.awt.*;
import java.awt.event.*;
public class TrafficLightSimulatorAWT extends Frame implements Runnable {
private String currentLight = "RED"; // RED, YELLOW, GREEN
private Thread thread;
public TrafficLightSimulatorAWT() {
setTitle("Traffic Light Simulation");
setSize(300, 400);
setVisible(true);
setBackground(Color.WHITE);
// Start the traffic light simulation
thread = new Thread(this);
thread.start();
// Close window on close button click
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
thread.interrupt();
dispose();
}
});
}
@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.");
}
}
public static void main(String[] args) {
new TrafficLightSimulatorAWT();
}
}
10) Write a program to chat between client and server. Write a servlet code to
demonstrate GET and POST methods with suitable example.
Ans:
Server Code (ChatServer.java)
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server started. Waiting for client...");
Socket socket = serverSocket.accept();
System.out.println("Client connected!");
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new
InputStreamReader(System.in));
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();
}
}
}
Client Code (ChatClient.java)
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5000);
System.out.println("Connected to server.");
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new
InputStreamReader(System.in));
String msg;
while (true) {
System.out.print("You: ");
msg = input.readLine();
writer.println(msg);
String reply = reader.readLine();
System.out.println("Server: " + reply);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Part 2: Servlet Code to Demonstrate GET and POST Methods
You need a Java servlet running on a servlet container like Apache Tomcat.
Servlet Code: FormServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FormServlet extends HttpServlet {
// Handles GET request
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<h2>This is a GET Request</h2>");
out.println("<form method='post'>");
out.println("Name: <input type='text' name='name' />");
out.println("<input type='submit' value='Submit' />");
out.println("</form>");
}
// Handles POST request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<h2>Hello, " + name + "!</h2>");
out.println("<a href='FormServlet'>Go Back</a>");
}
}
Web Deployment Descriptor (web.xml)
Make sure to configure the servlet in your web.xml:
<web-app>
<servlet>
<servlet-name>FormServlet</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormServlet</servlet-name>
<url-pattern>/FormServlet</url-pattern>
</servlet-mapping>
</web-app>
11) Write a program to connect to any database and to execute the SQL query
operation using GUI interface
Ans:
Sure! Here's a complete step-by-step guide to build a Java program with a GUI
(Swing) that connects to a MySQL database and executes SQL queries, including all
installations and setup.
Part 1: Installation and Setup
Tools Required:
1. Java JDK (v8+)
2. IntelliJ IDEA (Community or Ultimate)
3. MySQL Server (with Workbench or CLI)
4. MySQL Connector/J (JDBC driver)
Step 1: Install Java JDK
• Download from: https://www.oracle.com/java/technologies/javase-downloads.html
• Install it and set the JAVA_HOME environment variable.
To verify:
java -version
javac -version
Step 2: Install IntelliJ IDEA
• Download from: https://www.jetbrains.com/idea/download
• Install and run it.
Step 3: Install MySQL
• Download MySQL from: https://dev.mysql.com/downloads/installer/
• During installation, set root password (e.g., root)
• Optionally install MySQL Workbench for GUI
Step 4: Download JDBC Driver
• Download: https://dev.mysql.com/downloads/connector/j/
• Extract the ZIP and note the path to mysql-connector-j-x.x.x.jar
Part 2: Create MySQL Database
Open MySQL CLI or Workbench and run:
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50)
);
Part 3: Java GUI Program to Run SQL Queries
Project Setup in IntelliJ
1. Open IntelliJ → New Project → Java
2. Right-click your project → Open Module Settings (F4) → Libraries → + → Add the
JDBC .jar file
3. Create DatabaseGUIApp.java
DatabaseGUIApp.java (Copy-paste this)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class DatabaseGUIApp extends JFrame {
JTextArea queryArea, resultArea;
JButton executeButton;
Connection conn;
public DatabaseGUIApp() {
setTitle("SQL Query Executor");
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
queryArea = new JTextArea(5, 40);
resultArea = new JTextArea(15, 40);
resultArea.setEditable(false);
executeButton = new JButton("Execute");
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(new JLabel("Enter SQL Query:"), BorderLayout.NORTH);
topPanel.add(new JScrollPane(queryArea), BorderLayout.CENTER);
add(topPanel, BorderLayout.NORTH);
add(new JScrollPane(resultArea), BorderLayout.CENTER);
add(executeButton, BorderLayout.SOUTH);
connectToDatabase();
executeButton.addActionListener(e -> executeQuery());
setVisible(true);
}
private void connectToDatabase() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "your_password"
);
resultArea.setText("Connected to database.\n");
} catch (Exception ex) {
resultArea.setText("Connection failed: " + ex.getMessage());
}
}
private void executeQuery() {
String query = queryArea.getText().trim();
try (Statement stmt = conn.createStatement()) {
if (query.toLowerCase().startsWith("select")) {
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
StringBuilder output = new StringBuilder();
for (int i = 1; i <= cols; i++) {
output.append(meta.getColumnName(i)).append("\t");
}
output.append("\n");
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());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(DatabaseGUIApp::new);
}
}
Example SQL Commands to Test:
• Insert:
• INSERT INTO students VALUES (1, 'Alice');
• Select:
• SELECT * FROM students;
• Delete:
• DELETE FROM students WHERE id = 1;
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.*;
public class SimpleServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(6000);
System.out.println("Server is running... Waiting for client.");
Socket socket = serverSocket.accept();
System.out.println("Client connected!");
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String clientMessage = in.readLine();
System.out.println("Client says: " + clientMessage);
out.println("Hello Client, message received");
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SimpleClient.java
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 6000);
System.out.println("Connected to server.");
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
out.println("Hello Server");
String serverResponse = in.readLine();
System.out.println("Server says: " + serverResponse);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}