Java (1)
Java (1)
Create a program to accept 10 integers from the user, store them in an array, and calculate
their sum and average using a for-each loop.
Program:
import java.util.Scanner;
public class SumAndAverage {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[10];
int sum = 0;
// take input from user
System.out.println("Enter 10 integers:");
for (int i = 0; i < 10; i++) {
numbers[i] = scanner.nextInt();
}
// calculate sum
for (int num : numbers) {
sum += num;
}
// Calculate the average
double average = (double) sum /numbers.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
scanner.close();
}
}
Output:
2. Design a student class with attributes such as id, name, and marks. Write methods to
calculate the grade based on marks and display student details.
Program:
public class Students {
private int id;
private String name;
private double marks;
// Constructor
public Students(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
// Method to calculate grade based on marks
public String calculateGrade() {
if (marks >= 90) {
return "A";
} else if (marks >= 80) {
return "B";
} else if (marks >= 70) {
return "C";
} else if (marks >= 60) {
return "D";
} else {
return "F";
}
}
// Method to display student details
public void displayDetails() {
System.out.println("Student ID: " + id);
System.out.println("Name of Student: " + name);
System.out.println("Marks Obtained: " + marks);
System.out.println("Grade: " + calculateGrade());
}
public static void main(String[] args) {
// Creating a Student object
Students student = new Students(115, "Mohan Thapa", 81);
student.displayDetails();
}
}
Output:
3. Write a program to demonstrate method overloading by implementing a Calculator class with
overloaded methods for add (supporting 2, 3, and 4 integers).
Program:
return a + b;
return a + b + c;
return a + b + c + d;
}
Output:
4. Demonstrate the use of public, private, protected, and package-private access modifiers in
Java. Use different classes within the same and different packages.
Program;
package package1;
System.out.println("From ClassA:");
}
package package1;
package package2;
import package1.ClassA;
}
package package2;
import package1.ClassA;
import package1.ClassB;
classB.accessClassAFields();
classC.accessClassAFields();
Output:
5. Write a program with an interface Shape containing methods area() and perimeter().
Implement it in two classes, Circle and Rectangle. Include an inner class to calculate
diagonal for the Rectangle
Program:
// Shape interface
interface Shape {
// Constructor
this.radius = radius;
@Override
@Override
// Constructor
this.length = length;
this.width = width;
@Override
@Override
System.out.println("Rectangle:");
// Main class
circle.display();
System.out.println();
// Create a Rectangle object
Rectangle rectangle = new Rectangle(4, 3); // Rectangle with length 4 and width 3
rectangle.display();
Output:
6. Create a class MathConstants with a final variable for PI and a static method to calculate the
area of a circle.
Program:
System.out.println("The area of the circle with radius " + radius + " is: " + area);
Output:
7. Design a base class Employee with attributes name and salary, and a derived class Manager
with additional attributes department. Override a method displayDetails() in both classes.
Program:
// Base class Employee
class Employee {
protected String name; // Name of the employee
protected double salary; // Salary of the employee
// Constructor
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
// Method to display details (can be overridden)
public void displayDetails() {
System.out.println("Employee Details:");
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
}
// Derived class Manager
class Manager extends Employee {
private String department; // Department of the manager
// Constructor
public Manager(String name, double salary, String department) {
super(name, salary); // Call the constructor of the base class
this.department = department;
}
// Override the displayDetails method
@Override
public void displayDetails() {
System.out.println("Manager Details:");
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
System.out.println("Department: " + department);
}
}
// Main class
public class EmployeeManagerDemo {
public static void main(String[] args) {
// Create an Employee object
Employee emp = new Employee("Mohan", 50000);
emp.displayDetails();
System.out.println();
// Create a Manager object
Manager mgr = new Manager("Ram", 75000, "Sales");
mgr.displayDetails();
}
}
Output:
8. Write a program that prompts the user to enter two integers and performs division. Handle
exceptions for invalid inputs (e.g., non-numeric input) and division by zero.
Program:
import java.util.Scanner;
Program:
class Counter {
count++;
return count;
counter.increment();
});
threads[i].start();
try {
threads[i].join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Output:
11.Create a program to read from a text file and write its content to another file, line by line.
Program:
import java.io.*;
String inputFilePath = "input.txt"; // Change this to the path of the input file
String outputFilePath = "output.txt"; // Change this to the path of the output file
String line;
writer.write(line);
} catch (IOException e) {
e.printStackTrace();
}
Output:
12.Create a program to serialize and deserialize an object of a Book class with attributes
title, author, and price.
Program:
import java.io.*;
// Book class that implements Serializable
class Book implements Serializable {
private static final long serialVersionUID = 1L;
private String title;
private String author;
private double price;
// Constructor
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
// Getter methods
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getPrice() {
return price;
}
// toString method for easy printing
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}
Simple Swing:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleSwingGUI {
public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("Swing Example");
// Create components
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Submit");
JLabel response = new JLabel("");
// Set layout
frame.setLayout(new FlowLayout());
// Add components to the frame
frame.add(label);
frame.add(textField);
frame.add(button);
frame.add(response);
// Add action listener to the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = textField.getText();
response.setText("Hello, " + name + "!");
}
});
// Set frame properties
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:
14.Create a Swing application with components like JButton, JLabel, and JTextField added
to a JPanel, which is then added to a JFrame.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingAppWithPanel {
public static void main(String[] args) {
// Create the main JFrame
JFrame frame = new JFrame("Swing Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
// Create a JPanel
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2, 5, 5)); // Use a GridLayout for neat arrangement
// Create components
JLabel nameLabel = new JLabel("Enter your name:");
JTextField nameField = new JTextField();
JButton submitButton = new JButton("Submit");
JLabel greetingLabel = new JLabel("");
// Add components to the panel
panel.add(nameLabel);
panel.add(nameField);
panel.add(submitButton);
panel.add(new JLabel("")); // Placeholder for spacing
panel.add(greetingLabel);
// Add ActionListener to the button
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
if (!name.isEmpty()) {
greetingLabel.setText("Hello, " + name + "!");
} else {
greetingLabel.setText("Please enter your name.");
}
}
});
// Add the panel to the frame
frame.add(panel);
// Make the frame visible
frame.setVisible(true);
}
}
Output:
15.Design a calculator-like GUI using BorderLayout with buttons at different
positions (NORTH, SOUTH, EAST, WEST, and CENTER).
Program:
import javax.swing.*;
import java.awt.*;
public class SimpleCalculatorGUI {
public static void main(String[] args) {
// Create the main JFrame
JFrame frame = new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
// Set BorderLayout for the frame
frame.setLayout(new BorderLayout());
// NORTH: Display area
JTextField display = new JTextField("0");
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
frame.add(display, BorderLayout.NORTH);
// SOUTH: Action buttons
JButton clearButton = new JButton("C");
JButton equalsButton = new JButton("=");
JPanel southPanel = new JPanel();
southPanel.add(clearButton);
southPanel.add(equalsButton);
frame.add(southPanel, BorderLayout.SOUTH);
// EAST: Operator buttons
JPanel eastPanel = new JPanel(new GridLayout(4, 1));
eastPanel.add(new JButton("+"));
eastPanel.add(new JButton("-"));
eastPanel.add(new JButton("*"));
eastPanel.add(new JButton("/"));
frame.add(eastPanel, BorderLayout.EAST);
// CENTER: Number buttons
JPanel centerPanel = new JPanel(new GridLayout(3, 3));
for (int i = 1; i <= 9; i++) {
centerPanel.add(new JButton(String.valueOf(i)));
}
frame.add(centerPanel, BorderLayout.CENTER);
// WEST: Placeholder (optional, can be empty or used for other features)
frame.add(new JLabel(""), BorderLayout.WEST);
// Make the frame visible
frame.setVisible(true);
}
}
Output:
16.Create a menu bar with menus for "File" and "Edit." Add menu items such as "Open,"
"Save," and "Exit." Enable and disable them programmatically.
Program:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MenuBarExample {
public static void main(String[] args) {
// Create the main JFrame
JFrame frame = new JFrame("Menu Bar Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Create a menu bar
JMenuBar menuBar = new JMenuBar();
// Create "File" menu
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem exitItem = new JMenuItem("Exit");
// Add items to "File" menu
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator(); // Adds a separator line
fileMenu.add(exitItem);
// Create "Edit" menu
JMenu editMenu = new JMenu("Edit");
JMenuItem enableItem = new JMenuItem("Enable Save");
JMenuItem disableItem = new JMenuItem("Disable Save");
// Add items to "Edit" menu
editMenu.add(enableItem);
editMenu.add(disableItem);
// Add menus to the menu bar
menuBar.add(fileMenu);
menuBar.add(editMenu);
// Add menu bar to the frame
frame.setJMenuBar(menuBar);
// Add action listeners
saveItem.setEnabled(false); // Initially disable "Save"
enableItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveItem.setEnabled(true);
}
});
disableItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveItem.setEnabled(false);
}
});
exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0); // Exit the application
}
});
// Display the frame
frame.setVisible(true);
}
}
Output:
17.Create a toolbar with buttons for common actions like "New," "Open," and "Save."
Add tooltips for each button.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ToolbarExample {
public static void main(String[] args) {
// Create the main JFrame
JFrame frame = new JFrame("Toolbar Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Create a toolbar
JToolBar toolBar = new JToolBar();
// Create buttons for the toolbar
JButton newButton = new JButton("New");
newButton.setToolTipText("Create a new file"); // Tooltip for "New"
JButton openButton = new JButton("Open");
openButton.setToolTipText("Open an existing file"); // Tooltip for "Open"
JButton saveButton = new JButton("Save");
saveButton.setToolTipText("Save the current file"); // Tooltip for "Save"
// Add buttons to the toolbar
toolBar.add(newButton);
toolBar.add(openButton);
toolBar.add(saveButton);
// Add action listeners for the buttons
newButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "New action clicked!");
}
});
openButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Open action clicked!");
}
});
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Save action clicked!");
}
});
// Add the toolbar to the frame
frame.add(toolBar, BorderLayout.NORTH);
// Set the frame visibility
frame.setVisible(true);
}
}
Output:
18.Create an application that opens a file dialog to select a file and displays its contents
in a JTextArea.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileViewerApp {
public static void main(String[] args) {
// Create the main JFrame
JFrame frame = new JFrame("File Viewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Create a JTextArea to display file contents
JTextArea textArea = new JTextArea();
textArea.setEditable(false); // Make the text area read-only
JScrollPane scrollPane = new JScrollPane(textArea); // Add scroll bars
// Create a JButton to open a file dialog
JButton openButton = new JButton("Open File");
openButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Open a file chooser dialog
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(frame);
// If the user selects a file
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile)))
{
// Read file contents and display in JTextArea
textArea.setText(""); // Clear previous content
String line;
while ((line = reader.readLine()) != null) {
textArea.append(line + "\n");
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(frame, "Error reading file: " + ex.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
});
// Add components to the frame
frame.setLayout(new BorderLayout());
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(openButton, BorderLayout.SOUTH);
// Make the frame visible
frame.setVisible(true);
}
}
Output:
19.Create a GUI with JInternalFrame and a table (JTable) to display a list of students with
their names and grades.
Program:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StudentGradeViewer {
public static void main(String[] args) {
// Create the main JFrame
JFrame frame = new JFrame("Student Grade Viewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
// Set the layout for the frame
frame.setLayout(new BorderLayout());
// Create the desktop pane to hold internal frames
JDesktopPane desktopPane = new JDesktopPane();
frame.add(desktopPane, BorderLayout.CENTER);
// Create a JPanel
JPanel panel = new JPanel();
@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered the panel!");
}
@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited the panel!");
}
});
greenButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.setBackground(Color.GREEN);
}
});
blueButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.setBackground(Color.BLUE);
}
});
// Create a JPanel for buttons and add buttons to it
JPanel buttonPanel = new JPanel();
buttonPanel.add(redButton);
buttonPanel.add(greenButton);
buttonPanel.add(blueButton);
// Set layout for the main frame and add panels
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
// Set frame properties
frame.setSize(400, 300); // Set window size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close on exit
frame.setVisible(true); // Make the frame visible
}
}
Output:
23.Write a program to capture and display keystrokes in a JTextArea.
Program:
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.BorderLayout;
public class DisplayKeystroke {
public static void main(String[] args) {
JFrame frame = new JFrame("Display Keystroke");
JTextArea textArea = new JTextArea(10, 30);
textArea.setEditable(false); // Make the text area non-editable by the user
textArea.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
textArea.append("Key Typed: " + e.getKeyChar() + "\n");
}
@Override
public void keyPressed(KeyEvent e) {
textArea.append("Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode()) + "\n");
}
@Override
public void keyReleased(KeyEvent e) {
textArea.append("Key Released: " + KeyEvent.getKeyText(e.getKeyCode()) +
"\n");
}
});
JScrollPane scrollPane = new JScrollPane(textArea);
frame.setLayout(new BorderLayout());
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Make the frame visible
// Set focus to the text area to capture keystrokes
textArea.requestFocusInWindow();
}
}
Output:
24.Write a program to connect to a MySQL/PostgreSQL database and perform CRUD
operation for a table Students with columns id, name, and grade .Use a
PreparedStatement to query student details based on their grade.
Program:
import java.sql.*;
import java.util.Scanner;
public class StudentCRUD {
private static final String DB_URL = "jdbc:postgresql://localhost:5432/java"; // Replace
with your DB URL
private static final String DB_USER = "postgres"; // Replace with your DB username
private static final String DB_PASSWORD = "9825"; // Replace with your DB password
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD)) {
System.out.println("Connected to the database successfully!");
while (!exit) {
System.out.println("\nChoose an operation:");
System.out.println("1. Create Student");
System.out.println("2. Read Students by Grade");
System.out.println("3. Update Student");
System.out.println("4. Delete Student");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
String query = "INSERT INTO Students (id, name, grade) VALUES (?, ?, ?)";
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// If an error occurs, rollback the transaction to ensure data consistency
if (connection != null) {
try {
System.out.println("Transaction failed. Rolling back...");
connection.rollback();
} catch (SQLException rollbackEx) {
rollbackEx.printStackTrace();
}
}
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.setAutoCommit(true);
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Output:
26.Write a program to display the local IP address and port number of the host machine.
Program:
import java.net.*;
public class LocalIPAddress {
public static void main(String[] args) {
try {
// Get the local host IP address
InetAddress localHost = InetAddress.getLocalHost();
String ipAddress = localHost.getHostAddress();
int port = 8080;
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
Output:
27.Use the InetAddress class to find the hostname and IP address of a given domain name.
Program:
import java.net.*;
public class DomainInfo {
public static void main(String[] args) {
// The domain name for which we need to find the hostname and IP address
String domainName = "www.java.com"; // Replace with any domain name
try {
// Get the InetAddress for the given domain
InetAddress inetAddress = InetAddress.getByName(domainName);
// Get the hostname and IP address
String hostname = inetAddress.getHostName();
String ipAddress = inetAddress.getHostAddress();
// Display the results
System.out.println("Domain Name: " + domainName);
System.out.println("Hostname: " + hostname);
System.out.println("IP Address: " + ipAddress);
} catch (UnknownHostException e) {
System.out.println("Unable to resolve domain name: " + domainName);
e.printStackTrace();
}
}
}
Output:
28.Create a client-server application where the client sends a message, and the server
responds with a reversed version of the message.
Program:
Client Program:
import java.io.*;
import java.net.*;
public class ReversalClient {
public static void main(String[] args) {
String serverAddress = "localhost"; // Server address
int port = 2000; // Server port
try (Socket socket = new Socket(serverAddress, port);
]BufferedReader consoleInput = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true)) {
System.out.println("Connected to the server");
// Read a message from the user
System.out.print("Enter a message: ");
String message = consoleInput.readLine();
// Send the message to the server
output.println(message);
// Read the reversed message from the server
String reversedMessage = input.readLine();
System.out.println("Reversed message from server: " + reversedMessage);
} catch (IOException e) {
System.out.println("Client error: " + e.getMessage());
}
}
}
Server Program:
import java.io.*;
import java.net.*;
public class ReversalServer {
public static void main(String[] args) {
int port = 2000; // Port to listen on
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");
// Handle client communication
try (BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true)) {
String message = input.readLine(); // Read message from the client
System.out.println("Received: " + message);
// Reverse the message
String reversedMessage = new StringBuilder(message).reverse().toString();
// Send the reversed message back to the client
output.println(reversedMessage);
System.out.println("Reversed and sent: " + reversedMessage);
} catch (IOException e) {
System.out.println("Error handling client: " + e.getMessage());
}
}
} catch (IOException e) {
System.out.println("Server error: " + e.getMessage());
}
}
}
Output:
ClientSide:
Server Side:
29.Implement a UDP-based program where the client sends a number, and the server
responds with its square.
Client Program:
import java.net.*;
import java.util.Scanner;
public class UDPClient {
public static void main(String[] args) {
DatagramSocket socket = null;
Scanner scanner = new Scanner(System.in);
try {
// Create a DatagramSocket to send and receive UDP packets
socket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost");
int serverPort = 9876;
// Read the number from the user
System.out.print("Enter a number: ");
int number = scanner.nextInt();
String message = String.valueOf(number);
// Send the number to the server
byte[] sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
serverAddress, serverPort);
socket.send(sendPacket);
// Receive the response from the server (squared number)
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
socket.receive(receivePacket);
// Convert received data to string and print the squared number
String squaredNumber = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("Squared number from server: " + squaredNumber);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) {
socket.close();
}
scanner.close();
}
}
}
Server Program:
import java.net.*;
public class UDPServer {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
// Create a DatagramSocket to receive and send UDP packets
socket = new DatagramSocket(9876);
System.out.println("Server is listening on port 9876...");
while (true) {
byte[] receiveData = new byte[1024];
// Receive data from the client
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
socket.receive(receivePacket);
// Convert received data to string and extract the number
String receivedMessage = new String(receivePacket.getData(), 0,
receivePacket.getLength());
int number = Integer.parseInt(receivedMessage.trim());
System.out.println("Received number: " + number);
// Calculate the square of the number
int square = number * number;
// Send the result back to the client
String response = String.valueOf(square);
byte[] sendData = response.getBytes();
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
// Send the squared value as a response
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, clientAddress, clientPort);
socket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}
}
Output:
Client Side:
Server Side:
30.Create a simple login form using JavaFX.
Program:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class LoginForm extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Login Form");
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
Label userLabel = new Label("Username:");
TextField userTextField = new TextField();
Label passLabel = new Label("Password:");
PasswordField passField = new PasswordField();
Button loginButton = new Button("Login");
Label messageLabel = new Label();
loginButton.setOnAction(e -> {
String username = userTextField.getText();
String password = passField.getText();
if ("admin".equals(username) && "password".equals(password)) {
messageLabel.setText("Login Successful!");
} else {
messageLabel.setText("Login Failed. Try again.");
}
});
grid.add(userLabel, 0, 0);
grid.add(userTextField, 1, 0);
grid.add(passLabel, 0, 1);
grid.add(passField, 1, 1);
grid.add(loginButton, 1, 2);
grid.add(messageLabel, 1, 3);
// BorderPane layout
BorderPane borderPane = new BorderPane();
borderPane.setTop(menuBar);
borderPane.setCenter(flowPane);
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the submitted form data from the request
String name = request.getParameter("name");
String email = request.getParameter("email");
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/RequestHandlerServlet")
public class RequestHandlerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>GET Request Received</h1>");
out.println("<p>This response is generated for a GET request.</p>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>POST Request Received</h1>");
out.println("<p>This response is generated for a POST request.</p>");
out.println("</body></html>");
}
}
Output:
37.Create a servlet that uses cookies to store user preferences and a session to manage login
information
Program:
package org.example.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebServlet("/UserPreferencesServlet")
@Override
response.setContentType("text/html");
if (cookies != null) {
if (cookie.getName().equals("theme")) {
theme = cookie.getValue();
} else if (cookie.getName().equals("language")) {
language = cookie.getValue();
out.println("<html><body>");
if (username != null) {
} else {
out.println("<h1>Welcome, Guest!</h1>");
out.println("<select name='theme'>");
out.println("<option value='light'>Light</option>");
out.println("<option value='dark'>Dark</option>");
out.println("</select><br>");
out.println("<select name='language'>");
out.println("<option value='en'>English</option>");
out.println("<option value='fr'>French</option>");
out.println("<option value='es'>Spanish</option>");
out.println("</select><br>");
out.println("</form>");
out.println("</body></html>");
@Override
response.setContentType("text/html");
PrintWriter out = response.getWriter();
session.setAttribute("username", username);
themeCookie.setMaxAge(7 * 24 * 60 * 60);
languageCookie.setMaxAge(7 * 24 * 60 * 60);
response.addCookie(themeCookie);
response.addCookie(languageCookie);
out.println("<html><body>");
out.println("<h1>Preferences Saved Successfully!</h1>");
out.println("</body></html>");
Output:
38.Create a JSP page to display the current date and time using JSP declarations and
expressions.
Program:
webapp
<%--
Created by IntelliJ IDEA.
User: mohanthapa
Date: 28/01/2025
Time: 09:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Current Date and Time</title>
</head>
<body>
<h1>Current Date and Time</h1>
<p>
<%-- JSP declaration to create a Date object --%>
<%
java.util.Date currentDate = new java.util.Date();
%>
<%-- JSP expression to display the date and time --%>
Current Date and Time: <%= currentDate %>
</p>
</body>
</html>
Output:
39.Write a JSP page that demonstrates the use of implicit objects like request, response,
and session.
Program:
Implicit.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.*" %>
<html>
<head>
</head>
<body>
<form method="post">
</form>
<%
session.setAttribute("username", name);
response.setContentType("text/html");
// Output a message using the implicit response object
} else {
if (storedName != null) {
} else {
%>
</body>
</html>
Output:
40.Implement a JSP page to process a login form and display a welcome message for the user.
Program:
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login</h1>
<form method="post">
</form>
<%
session.setAttribute("username", username);
} else {
// Invalid credentials
%>
</body>
</html>
Output:
41.Create an RMI application where the client sends a number, and the server responds
with its factorial.
Program:
FactorialInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface FactorialInterface extends Remote {
long calculateFactorial(int number) throws RemoteException;
}
FactorialServer.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.registry.LocateRegistry;
import java.rmi.Naming;
public class FactorialServer extends UnicastRemoteObject implements
FactorialInterface {
// Constructor for the server
public FactorialServer() throws RemoteException {
super();
}
FactorialClient.java
import java.rmi.Naming;
public class FactorialClient {
public static void main(String[] args) {
try {
// Lookup the remote object
FactorialInterface stub = (FactorialInterface)
Naming.lookup("rmi://localhost/FactorialInterface");
Semester: Seventh
Level:Bachelor
Program:CSIT