0% found this document useful (0 votes)
8 views98 pages

Java (1)

The document contains multiple Java programming tasks, including accepting user input to calculate sum and average, designing a student class with grading methods, demonstrating method overloading in a calculator class, and showcasing access modifiers. It also includes examples of multithreading, exception handling, file operations, and serialization of a Book class. Each task is presented with code snippets and expected outputs.

Uploaded by

susank baniya
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)
8 views98 pages

Java (1)

The document contains multiple Java programming tasks, including accepting user input to calculate sum and average, designing a student class with grading methods, demonstrating method overloading in a calculator class, and showcasing access modifiers. It also includes examples of multithreading, exception handling, file operations, and serialization of a Book class. Each task is presented with code snippets and expected outputs.

Uploaded by

susank baniya
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/ 98

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:

public class MethodOverloading {

// Method to add two integers

public int add(int a, int b) {

return a + b;

// Method to add three integers

public int add(int a, int b, int c) {

return a + b + c;

// Method to add four integers

public int add(int a, int b, int c, int d) {

return a + b + c + d;

public static void main(String[] args) {

MethodOverloading calculate = new MethodOverloading();

System.out.println("Sum of 2 numbers (10 + 20): " + calculate.add(10, 20));

System.out.println("Sum of 3 numbers (5 + 10 + 15): " + calculate.add(5, 10, 15));

System.out.println("Sum of 4 numbers (5 + 10 +15 + 20): " + calculate.add(5, 10, 15, 20));

}
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;

public class ClassA {

public String publicField = "Public Field";

private String privateField = "Private Field";

protected String protectedField = "Protected Field";

String packagePrivateField = "Package-Private Field";

public void displayFields() {

System.out.println("From ClassA:");

System.out.println("Public Field: " + publicField);

System.out.println("Private Field: " + privateField);

System.out.println("Protected Field: " + protectedField);

System.out.println("Package-Private Field: " + packagePrivateField);

}
package package1;

public class ClassB {

public void accessClassAFields() {

ClassA classA = new ClassA();

System.out.println("From ClassB (Same Package):");

System.out.println("Public Field: " + classA.publicField);

// System.out.println("Private Field: " + classA.privateField); // Not accessible

System.out.println("Protected Field: " + classA.protectedField);

System.out.println("Package-Private Field: " + classA.packagePrivateField);

package package2;

import package1.ClassA;

public class ClassC extends ClassA {

public void accessClassAFields() {

ClassA classA = new ClassA();

System.out.println("From ClassC (Different Package, Non-Subclass):");

System.out.println("Public Field: " + classA.publicField);

System.out.println("From ClassC (Accessing Protected Field Through Subclass):");

System.out.println("Protected Field: " + this.protectedField); // Accessible because it's a


subclass

}
package package2;

import package1.ClassA;

import package1.ClassB;

public class Main {

public static void main(String[] args) {

ClassA classA = new ClassA();

ClassB classB = new ClassB();

ClassC classC = new ClassC();

// Access fields from ClassA in Main (Different Package, Non-Subclass)

System.out.println("From Main (Different Package):");

System.out.println("Public Field: " + classA.publicField);

// Private and protected field are not accessible

// Access ClassB (Same Package as ClassA)

classB.accessClassAFields();

// Access ClassC (Different Package, Subclass of ClassA)

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 {

double area(); // Method to calculate area

double perimeter(); // Method to calculate perimeter

// Circle class implementing Shape

class Circle implements Shape {

private double radius;

// Constructor

public Circle(double radius) {

this.radius = radius;

@Override

public double area() {

return Math.PI * radius * radius; // Area = πr²

@Override

public double perimeter() {

return 2 * Math.PI * radius; // Perimeter = 2πr

public void display() {


System.out.println("Circle:");

System.out.println("Radius: " + radius);

System.out.println("Area: " + area());

System.out.println("Perimeter: " + perimeter());

// Rectangle class implementing Shape

class Rectangle implements Shape {

private double length;

private double width;

// Constructor

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

@Override

public double area() {

return length * width; // Area = length × width

@Override

public double perimeter() {

return 2 * (length + width); // Perimeter = 2 × (length + width)

// Inner class to calculate diagonal


class DiagonalCalculator {

public double calculateDiagonal() {

return Math.sqrt((length * length) + (width * width)); // Diagonal = √(length² +


width²)

public void display() {

System.out.println("Rectangle:");

System.out.println("Length: " + length);

System.out.println("Width: " + width);

System.out.println("Area: " + area());

System.out.println("Perimeter: " + perimeter());

// Using the inner class to calculate the diagonal

DiagonalCalculator diagonalCalculator = new DiagonalCalculator();

System.out.println("Diagonal: " + diagonalCalculator.calculateDiagonal());

// Main class

public class ShapeInterface{

public static void main(String[] args) {

// Create a Circle object

Circle circle = new Circle(5); // Circle with radius 5

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:

public class MathConstants {

static final double PI = 3.14159;

// Static method to calculate the area of a circle

public static double calculateArea(double radius) {

return PI * radius * radius;

public static void main(String[] args) {

double radius = 2.0;

double area = MathConstants.calculateArea(radius);

// Display the result

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;

public class DivisionWithExceptionHandling {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Prompt the user to enter the first integer
System.out.print("Enter the first integer: ");
int num1 = Integer.parseInt(scanner.nextLine()); // Parse input as integer
// Prompt the user to enter the second integer
System.out.print("Enter the second integer: ");
int num2 = Integer.parseInt(scanner.nextLine()); // Parse input as integer
// Perform division and display the result
int result = num1 / num2;
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
// Handle invalid (non-numeric) input
System.out.println("Error: Invalid input. Please enter numeric values.");
} catch (ArithmeticException e) {
// Handle division by zero
System.out.println("Error: Division by zero is not allowed.");
} finally {
// Close the scanner
scanner.close();
System.out.println("Program execution completed.");
}
}
}
Output:
9.​ Write a multithreaded program to print numbers from 1 to 10 using two threads, where one
thread prints odd numbers and the other prints even numbers.
Program:
class NumberPrinter {
private boolean oddTurn = true; // Flag to indicate whose turn it is
// Method for printing odd numbers
public synchronized void printOdd(int number) {
while (!oddTurn) { // Wait if it's not the odd thread's turn
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Odd: " + number);
oddTurn = false; // Switch to even thread
notify(); // Notify the even thread
}
// Method for printing even numbers
public synchronized void printEven(int number) {
while (oddTurn) { // Wait if it's not the even thread's turn
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Even: " + number);
oddTurn = true; // Switch to odd thread
notify(); // Notify the odd thread
}
}

public class OddEvenThreads {


public static void main(String[] args) {
NumberPrinter printer = new NumberPrinter();
// Thread for odd numbers
Thread oddThread = new Thread(() -> {
for (int i = 1; i <= 10; i += 2) {
printer.printOdd(i);
}
});
// Thread for even numbers
Thread evenThread = new Thread(() -> {
for (int i = 2; i <= 10; i += 2) {
printer.printEven(i);
}
});
// Start the threads
oddThread.start();
evenThread.start();
// Wait for threads to finish
try {
oddThread.join();
evenThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Printing complete!");
}
}
Output:
10.​Create a program where multiple threads update a shared counter. Use synchronization to
ensure thread-safe operations.

Program:

class Counter {

private int count = 0; // Shared counter

// Synchronized method to increment the counter

public synchronized void increment() {

count++;

// Synchronized method to get the current value of the counter

public synchronized int getCount() {

return count;

public class ThreadSafeCounter {

public static void main(String[] args) {

Counter counter = new Counter(); // Shared counter object

int numberOfThreads = 5; // Number of threads

int incrementsPerThread = 1000; // Number of increments per thread

// Create and start multiple threads

Thread[] threads = new Thread[numberOfThreads];

for (int i = 0; i < numberOfThreads; i++) {

threads[i] = new Thread(() -> {


for (int j = 0; j < incrementsPerThread; j++) {

counter.increment();

});

threads[i].start();

// Wait for all threads to finish

for (int i = 0; i < numberOfThreads; i++) {

try {

threads[i].join();

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

// Print the final counter value

System.out.println("Final counter value: " + counter.getCount());

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.*;

public class FileCopy {

public static void main(String[] args) {

// Input and output file paths

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

// Use try-with-resources to ensure streams are closed automatically

try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));

BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {

String line;

while ((line = reader.readLine()) != null) {

writer.write(line);

writer.newLine(); // Write a newline character

System.out.println("File copied successfully!");

} catch (IOException e) {

System.out.println("An error occurred while processing the file:");

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 +
'}';
}
}

public class BookSerialization {


public static void main(String[] args) {
// Create a Book object
Book book = new Book("POM", "Henry Fayol", 20.00);

// File to store the serialized object


String filename = "book.ser";

// Serialize the Book object


serializeBook(book, filename);

// Deserialize the Book object


Book deserializedBook = deserializeBook(filename);

// Print the deserialized Book object


if (deserializedBook != null) {
System.out.println("Deserialized Book:");
System.out.println(deserializedBook);
}
}

// Method to serialize a Book object


private static void serializeBook(Book book, String filename) {
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
oos.writeObject(book);
System.out.println("Book serialized successfully!");
} catch (IOException e) {
System.err.println("Error during serialization: " + e.getMessage());
}
}

// Method to deserialize a Book object


private static Book deserializeBook(String filename) {
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(filename))) {
return (Book) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
System.err.println("Error during deserialization: " + e.getMessage());
}
return null;
}
}
Output:
13.​Create a simple GUI using AWT and then implement the same using Swing.
Program:
Simple AWT :
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleAWTGUI {
public static void main(String[] args) {
// Create a Frame
Frame frame = new Frame("AWT Example");
// Create components
Label label = new Label("Enter your name:");
TextField textField = new TextField(20);
Button button = new Button("Submit");
Label response = new Label("");
// 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.setVisible(true);
// Add a window listener to close the frame
frame.addWindowListener(new java.awt.event.WindowAdapter() {
​ public void windowClosing(java.awt.event.WindowEvent windowEvent) ​ ​
​ ​ {
System.exit(0);
}
});
}
}
Output:

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 an internal frame to hold the JTable


JInternalFrame internalFrame = new JInternalFrame("Student Grades", true, true, true, true);
internalFrame.setSize(500, 300);
internalFrame.setLayout(new BorderLayout());

// Create column names and data for the JTable


String[] columns = {"Name", "Grade"};
Object[][] data = {
{"Mohan", "A+"},
{"Ram", "B"},
{"Sita", "C"},
{"Aarush", "A+"},
{"Bista", "B+"}
};

// Create a JTable with the data and columns


DefaultTableModel model = new DefaultTableModel(data, columns);
JTable table = new JTable(model);

// Add the table to the internal frame inside a JScrollPane


JScrollPane scrollPane = new JScrollPane(table);
internalFrame.add(scrollPane, BorderLayout.CENTER);

// Add the internal frame to the desktop pane


desktopPane.add(internalFrame);

// Make the internal frame visible


internalFrame.setVisible(true);

// Create a button to refresh the table (optional)


JButton refreshButton = new JButton("Refresh Data");
refreshButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Sample code to update the table data dynamically
model.setValueAt("A", 0, 1); // Change grade for John Doe
model.setValueAt("B+", 1, 1); // Change grade for Jane Smith
model.setValueAt("A-", 2, 1); // Change grade for Mark Lee
}
});
frame.add(refreshButton, BorderLayout.SOUTH);
// Make the frame visible
frame.setVisible(true);
}
}
Output:
20.​Create a GUI with a button. When the button is clicked, display "Button Clicked!" in a
JLabel.
Program:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
public class ButtonClicked {
public static void main(String[] args) {
// Create the main JFrame container
JFrame frame = new JFrame("Button Click Demo");
// Create a JLabel to display the message
JLabel label = new JLabel("Click the button!");
// Create a JButton
JButton button = new JButton("Click Me");
// Add an ActionListener to the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!"); // Change the label text when button is clicked
}
});
// Set the layout and add components
frame.setLayout(new FlowLayout());
frame.add(button);
frame.add(label);
// Set frame properties
frame.setSize(300, 150); // Set window size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close on exit
frame.setVisible(true); // Make the frame visible
}
}
Output:
21.​Implement a mouse listener using an adapter class to handle mouse events like
mouseClicked() and mouseEntered().
Program:
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
public class MouseListenerUsingAdapter {
public static void main(String[] args) {
// Create the main JFrame container
JFrame frame = new JFrame("Mouse Listener Using Adapter");

// Create a JLabel to display messages


JLabel label = new JLabel("Interact with the panel!");

// Create a JPanel
JPanel panel = new JPanel();

// Add a MouseAdapter to handle mouse events


panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")");
}

@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered the panel!");
}

@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited the panel!");
}
});

// Set the layout and add components


frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.add(label, 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:
22.​Create a GUI with buttons labeled "Red," "Green," and "Blue." Change the
background color of a panel based on the button clicked.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BackgroundColorChange {
public static void main(String[] args) {
// Create the main JFrame container
JFrame frame = new JFrame("Background Color Change");
// Create a JPanel to change background color
JPanel panel = new JPanel();
// Create buttons for Red, Green, and Blue colors
JButton redButton = new JButton("Red");
JButton greenButton = new JButton("Green");
JButton blueButton = new JButton("Blue");
// Add ActionListeners to the buttons
redButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.setBackground(Color.RED);
}
});

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!");

Scanner scanner = new Scanner(System.in);


boolean exit = false;

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: ");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume newline
switch (choice) {
case 1 -> createStudent(connection, scanner);
case 2 -> readStudentsByGrade(connection, scanner);
case 3 -> updateStudent(connection, scanner);
case 4 -> deleteStudent(connection, scanner);
case 5 -> exit = true;
default -> System.out.println("Invalid choice. Please try again.");
}
}

} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}

private static void createStudent(Connection connection, Scanner scanner) {


System.out.print("Enter student id: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter student name: ");
String name = scanner.nextLine();
System.out.print("Enter student grade: ");
String grade = scanner.nextLine();

String query = "INSERT INTO Students (id, name, grade) VALUES (?, ?, ?)";

try (PreparedStatement preparedStatement = connection.prepareStatement(query))


{
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setString(3, grade);
int rowsInserted = preparedStatement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("Student added successfully!");
}
} catch (SQLException e) {
System.err.println("Error adding student: " + e.getMessage());
}
}

private static void readStudentsByGrade(Connection connection, Scanner scanner) {


System.out.print("Enter grade to search: ");
String grade = scanner.nextLine();

String query = "SELECT * FROM Students WHERE grade = ?";

try (PreparedStatement preparedStatement = connection.prepareStatement(query))


{
preparedStatement.setString(1, grade);
ResultSet resultSet = preparedStatement.executeQuery();

System.out.println("\nStudents with grade " + grade + ":");


while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id") + ", Name: " +
resultSet.getString("name") + ", Grade: " + resultSet.getString("grade"));
}
} catch (SQLException e) {
System.err.println("Error reading students: " + e.getMessage());
}
}

private static void updateStudent(Connection connection, Scanner scanner) {


System.out.print("Enter student ID to update: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline

System.out.print("Enter new name: ");


String name = scanner.nextLine();
System.out.print("Enter new grade: ");
String grade = scanner.nextLine();

String query = "UPDATE Students SET name = ?, grade = ? WHERE id = ?";

try (PreparedStatement preparedStatement = connection.prepareStatement(query))


{
preparedStatement.setString(1, name);
preparedStatement.setString(2, grade);
preparedStatement.setInt(3, id);
int rowsUpdated = preparedStatement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("Student updated successfully!");
} else {
System.out.println("Student not found.");
}
} catch (SQLException e) {
System.err.println("Error updating student: " + e.getMessage());
}
}

private static void deleteStudent(Connection connection, Scanner scanner) {


System.out.print("Enter student ID to delete: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
String query = "DELETE FROM Students WHERE id = ?";

try (PreparedStatement preparedStatement = connection.prepareStatement(query))


{
preparedStatement.setInt(1, id);
int rowsDeleted = preparedStatement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("Student deleted successfully!");
} else {
System.out.println("Student not found.");
}
} catch (SQLException e) {
System.err.println("Error deleting student: " + e.getMessage());
}
}
}
Output:
25.​Write a program to perform a transaction with multiple SQL statements. Rollback the
transaction in case of an error.
Program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TransactionExample {
public static void main(String[] args) {
// JDBC URL, username, and password of PostgreSQL server
String url = "jdbc:postgresql://localhost:5432/java";
String user = "postgres";
String password = "9825";

// SQL queries for inserting records into the Students table


String insertStudent1 = "INSERT INTO Students (id, name, grade) VALUES (?, ?, ?)";
String insertStudent2 = "INSERT INTO Students (id, name, grade) VALUES (?, ?, ?)";

// SQL queries for update and delete (optional for demonstration)


// String updateStudent = "UPDATE Students SET grade = ? WHERE name = ?";
// String deleteStudent = "DELETE FROM Students WHERE name = ?";

Connection connection = null;

try {
connection = DriverManager.getConnection(url, user, password);

// Disable auto-commit to start a transaction


connection.setAutoCommit(false);

// Insert first student


try (PreparedStatement pstmt1 = connection.prepareStatement(insertStudent1)) {
pstmt1.setInt(1, 3);
pstmt1.setString(2, "John Doe");
pstmt1.setString(3, "A");
pstmt1.executeUpdate();
}
try (PreparedStatement pstmt2 = connection.prepareStatement(insertStudent2)) {
pstmt2.setInt(1, 4);
pstmt2.setString(2, "Jane Doe");
pstmt2.setString(3, "B");
pstmt2.executeUpdate();
}

// Commit the transaction if no error occurs


connection.commit();
System.out.println("Transaction completed successfully.");

} 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;

// Display the IP address and port number


System.out.println("Local IP Address: " + ipAddress);
System.out.println("Port Number: " + port);

} 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);

Scene scene = new Scene(grid, 300, 200);


primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:
31.​Design a GUI with a FlowPane to arrange buttons and a BorderPane to place a menu bar
at the top and buttons at the center.
Program:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class FlowPaneBorder extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("FlowPane and BorderPane Example");
// MenuBar at the top
MenuBar menuBar = new MenuBar();
Menu fileMenu = new Menu("File");
MenuItem openItem = new MenuItem("Open");
MenuItem saveItem = new MenuItem("Save");
MenuItem exitItem = new MenuItem("Exit");
fileMenu.getItems().addAll(openItem, saveItem, exitItem);
menuBar.getMenus().add(fileMenu);
// FlowPane with buttons in the center
FlowPane flowPane = new FlowPane();
flowPane.setHgap(10);
flowPane.setVgap(10);
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");
flowPane.getChildren().addAll(button1, button2, button3);

// BorderPane layout
BorderPane borderPane = new BorderPane();
borderPane.setTop(menuBar);
borderPane.setCenter(flowPane);

Scene scene = new Scene(borderPane, 400, 300);


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}
Output:
32.​Design a calculator interface using a GridPane layout.
Program:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class CalculatorGridPane extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Calculator");
// Create the TextField to display calculations
TextField display = new TextField();
display.setEditable(false);
display.setAlignment(Pos.CENTER_RIGHT);
// Create a GridPane layout
GridPane grid = new GridPane();
grid.setVgap(10); // Vertical gap
grid.setHgap(10); // Horizontal gap
grid.setAlignment(Pos.CENTER);
// Define the buttons
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};
// Add buttons to the grid
int row = 1, col = 0;
for (String label : buttonLabels) {
Button button = new Button(label);
button.setPrefSize(60, 60);
grid.add(button, col, row);
col++;
if (col > 3) {
col = 0;
row++;
}
}
// Add the display TextField at the top
grid.add(display, 0, 0, 4, 1);
Scene scene = new Scene(grid, 300, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:
33.​Create a form with Label, TextField, Button, and CheckBox. Display the entered data on
a button click.
Program:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class FormWithCheckBox extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Form with Checkbox");
// Create the Label, TextField, CheckBox, and Button
Label instructionLabel = new Label("Enter your name:");
TextField nameField = new TextField();
CheckBox checkBox = new CheckBox("Subscribe to newsletter");
Button submitButton = new Button("Submit");
// Label to display the entered data
Label resultLabel = new Label();
// Button click action
submitButton.setOnAction(e -> {
String name = nameField.getText();
boolean isSubscribed = checkBox.isSelected();
resultLabel.setText("Name: " + name + ", Subscribed: " + isSubscribed);
});
// Layout with VBox
VBox vbox = new VBox(10); // Vertical spacing of 10
vbox.getChildren().addAll(instructionLabel, nameField, checkBox, submitButton,
resultLabel);

// Set the scene and show the stage


Scene scene = new Scene(vbox, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:
34.​Write a servlet that displays "Hello, World!" in the browser.
Program:
package org.example.servlet;
import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
@WebServlet(value = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
// Get the output stream to write the response
PrintWriter out = response.getWriter();
// Display "Hello, World!" in the browser
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
}
Output:
35.​Create a servlet that processes a form submission and displays the submitted data (e.g.,
name, email).
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Submission</title>
</head>
<body>
<h1>Submit Your Details</h1>
<form action="processForm" method="post">
Name: <input type="text" name="name"><br><br>
Email: <input type="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
FormServlet.java
package org.example.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "FormServlet", value = "/processForm")


public class FormServlet extends HttpServlet {

@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");

// Set the content type of the response


response.setContentType("text/html");

// Get the PrintWriter to write the response


PrintWriter out = response.getWriter();

// Output the submitted data in a simple HTML page


out.println("<html><body>");
out.println("<h1>Form Submission Successful!</h1>");
out.println("<p><strong>Name:</strong> " + name + "</p>");
out.println("<p><strong>Email:</strong> " + email + "</p>");
out.println("</body></html>");
}
}
Output:
36.​Write a servlet that distinguishes between GET and POST requests and processes them
accordingly.
Program:
package org.example.servlet;

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")

public class UserPreferencesServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

// Get session and cookies

HttpSession session = request.getSession();

String username = (String) session.getAttribute("username");


Cookie[] cookies = request.getCookies();

// Display user preferences if cookies are available

String theme = "default";

String language = "en";

if (cookies != null) {

for (Cookie cookie : cookies) {

if (cookie.getName().equals("theme")) {

theme = cookie.getValue();

} else if (cookie.getName().equals("language")) {

language = cookie.getValue();

out.println("<html><body>");

if (username != null) {

out.println("<h1>Welcome, " + username + "!</h1>");

} else {

out.println("<h1>Welcome, Guest!</h1>");

out.println("<p>Current Theme: " + theme + "</p>");


out.println("<p>Language Preference: " + language + "</p>");

out.println("<form action='UserPreferencesServlet' method='post'>");

out.println("<label for='theme'>Select Theme:</label>");

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("<label for='language'>Select Language:</label>");

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("<input type='submit' value='Save Preferences'>");

out.println("</form>");

out.println("</body></html>");

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

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

// Handle login information using session

HttpSession session = request.getSession();

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

if (username != null && !username.isEmpty()) {

session.setAttribute("username", username);

// Handle user preferences using cookies

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

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

Cookie themeCookie = new Cookie("theme", theme);

Cookie languageCookie = new Cookie("language", language);

// Set cookies expiry to 7 days

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("<p><a href='UserPreferencesServlet'>Go Back</a></p>");

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>

<title>JSP Implicit Objects Example</title>

</head>

<body>

<h1>JSP Implicit Objects Example</h1>

<form method="post">

Name: <input type="text" name="username" />

<input type="submit" value="Submit" />

</form>

<%

// Check if the user has already submitted a name

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

if (name != null && !name.isEmpty()) {

// Store the username in the session

session.setAttribute("username", name);

response.setContentType("text/html");
// Output a message using the implicit response object

out.println("<h3>Hello, " + name + "!</h3>");

out.println("<p>Your name has been stored in the session.</p>");

} else {

// If the name is not provided, retrieve it from the session

String storedName = (String) session.getAttribute("username");

if (storedName != null) {

out.println("<h3>Welcome back, " + storedName + "!</h3>");

} else {

out.println("<h3>Welcome! Please enter your name.</h3>");

%>

</body>

</html>

Output:
40.​Implement a JSP page to process a login form and display a welcome message for the user.
Program:

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

<%@ page import="java.util.*" %>

<html>

<head>

<title>Login Page</title>

</head>

<body>

<h1>Login</h1>

<!-- Displaying a login form -->

<form method="post">

Username: <input type="text" name="username" required /><br><br>

Password: <input type="password" name="password" required /><br><br>

<input type="submit" value="Login" />

</form>

<%

// Retrieve form parameters

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

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

// Check if the form has been submitted

if (username != null && password != null) {

// Validate username and password (Example with hardcoded values)

if ("mohan".equals(username) && "password".equals(password)) {


// If valid, display the welcome message

session.setAttribute("username", username);

out.println("<h3>Welcome, " + username + "!</h3>");

} else {

// Invalid credentials

out.println("<p style='color: red;'>Invalid username or password. Please try


again.</p>");

%>

</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();
}

// Method to calculate factorial


@Override
public long calculateFactorial(int number) throws RemoteException {
if (number == 0 || number == 1) {
return 1;
} else {
return number * calculateFactorial(number - 1);
}
}
public static void main(String[] args) {
try {
// Disable the security manager to suppress the deprecation warning
System.setProperty("java.rmi.server.useCodebaseOnly", "false");

// Create the RMI registry on a specific port (default is 1099)


LocateRegistry.createRegistry(1099);

// Create an instance of the FactorialServer


FactorialServer server = new FactorialServer();

// Bind the server to the registry


Naming.rebind("rmi://localhost/FactorialInterface", server);
System.out.println("Factorial Server is ready.");
} catch (Exception e) {
e.printStackTrace();
}
}
}

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");

// Get the number to calculate factorial for


int number = 5; // You can change this number to test with different values
long result = stub.calculateFactorial(number);
// Display the result
System.out.println("Factorial of " + number + " is " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
COLLEGE OF APPLIED BUSINESS AND TECHNOLOGY

Ganaghity, Chabahil, Kathmandu-07, Nepal

(Affiliated to Tribhuvan University)

Laboratory Assignment Report of

Advance Java Programming

Submitted by:​ ​ ​ ​ ​ ​ Submitted to:

Name: Mohan Thapa Mashrangi​ ​ ​ ​ Instructor:Chet Raj Ojha

Roll no: 115

Semester: Seventh

Faculty:Science and Technology

Level:Bachelor

Program:CSIT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy