1.
Write a program declaring a class Rectangle with data member’s length and breadth and
member functions Input, Output and CalcArea.
import java.util.Scanner;
class Rectangle {
float length;
float breadth;
public void Input() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length: ");
length = scanner.nextFloat();
System.out.print("Enter breadth: ");
breadth = scanner.nextFloat();
}
public void Output() {
System.out.println("Length: " + length);
System.out.println("Breadth: " + breadth);
}
public float CalcArea() {
return length * breadth;
}
public static void main(String[] args) {
Rectangle rect = new Rectangle();
rect.Input();
rect.Output();
System.out.println("Area of Rectangle: " + rect.CalcArea());
}
}
OUTPUT:
Piyush 06917702023 1
2. Write a program to demonstrate use of method overloading to calculate area of square,
rectangle and triangle.
import java.util.Scanner;
class AreaCalculator {
public float CalcArea(float side) {
return side * side;
}
public float CalcArea(float length, float breadth) {
return length * breadth;
}
public float CalcArea(float base, float height, boolean isTriangle) {
if (isTriangle) {
return 0.5f * base * height;
}
return 0;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
AreaCalculator calc = new AreaCalculator();
System.out.print("Enter side of square: ");
float side = scanner.nextFloat();
System.out.println("Area of Square: " + calc.CalcArea(side));
System.out.print("Enter length of rectangle: ");
float length = scanner.nextFloat();
System.out.print("Enter breadth of rectangle: ");
float breadth = scanner.nextFloat();
System.out.println("Area of Rectangle: " + calc.CalcArea(length, breadth));
System.out.print("Enter base of triangle: ");
float base = scanner.nextFloat();
System.out.print("Enter height of triangle: ");
float height = scanner.nextFloat();
System.out.println("Area of Triangle: " + calc.CalcArea(base, height, true));
}
}
Piyush 06917702023 2
OUTPUT:
Piyush 06917702023 3
3. Write a program to demonstrate the use of static variable, static method and static block
import java.util.Scanner;
class StaticDemo {
static int count;
static
{
count = 0;
}
public StaticDemo() {
count++;
}
public static void displayCount() {
System.out.println("Number of objects : " + count);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StaticDemo obj1 = new StaticDemo();
StaticDemo obj2 = new StaticDemo();
StaticDemo obj3 = new StaticDemo();
StaticDemo.displayCount();
}
}
OUTPUT:
Piyush 06917702023 4
4. Write a program to demonstrate concept of ``this``.
class Const
{
int a,b;
@Override
public String toString()
{
return this.a + "+" + this.b;
}
Const(int a,int b)
{
this.a=a;
this.b=b;
}
Const(int a)
{
this(a,a);
}
Const()
{
this(0);
}
};
class Main
{
public static void main(String[] args)
{
Const one=new Const(10,13);
Const two=new Const(20);
Const three=new Const();
System.out.println(one);
System.out.println(two);
System.out.println(three);
}
}
OUTPUT:
Piyush 06917702023 5
5. Write a program to demonstrate multi-level and hierarchical inheritance
//Multi-level
class Animal {
void speak()
{
System.out.println("this is animal");
}
}
class Dog extends Animal {
void speak()
{
super.speak();
System.out.println("Dog barks");
}
}
class Husky extends Dog {
void speak()
{
super.speak();
System.out.println("Husky is trained");
}
}
public class Main {
public static void main(String[] args) {
Husky one = new Husky();
one.speak();
}
}
OUTPUT:
Piyush 06917702023 6
//Hierarchical
class Animal {
void speak()
{
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void speak()
{
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void speak()
{
System.out.println("cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
dog.speak();
cat.speak();
}
}
OUTPUT:
Piyush 06917702023 7
6. Write a program to use super() to invoke base class constructor.
class Animal {
void speak()
{
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void speak() {
// Using super() to call the speak method of the parent class
super.speak(); // Calls Animal's speak method
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.speak();
}
}
OUTPUT:
Piyush 06917702023 8
7. Write a program to demonstrate run-time polymorphism.
class Animal {
void speak()
{
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void speak()
{
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.speak();
}
}
OUTPUT:
Piyush 06917702023 9
8. Write a program to demonstrate the concept of aggregation.
import java.util.Scanner;
class Address {
String city;
String state;
String country;
Address(String city, String state, String country) {
this.city = city;
this.state = state;
this.country = country;
}
}
class Employee {
int id;
String name;
Address address;
Employee(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public void display() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Address: " + address.city + ", " + address.state + ", " + address.country);
}
}
class AggregationDemo {
public static void main(String[] args) {
Address address1 = new Address("New York", "NY", "USA");
Address address2 = new Address("Los Angeles", "CA", "USA");
Employee emp1 = new Employee(101, "John Doe", address1);
Employee emp2 = new Employee(102, "Jane Smith", address2);
emp1.display();
emp2.display();
}
}
Piyush 06917702023 10
OUTPUT:
Piyush 06917702023 11
9. Write a program to demonstrate the concept of abstract class with constructor and ``final``
method.
abstract class Shape
{
String name;
Shape(String name)
{
this.name = name;
}
abstract void draw();
final void display() {
System.out.println("This is a shape: " + name);
}
}
class Circle extends Shape {
Circle() {
super("Circle");
}
@Override
void draw() {
System.out.println("Drawing a Circle");
}
}
public class AbstractDemo {
public static void main(String[] args) {
Circle circle = new Circle();
circle.draw();
circle.display();
}
}
OUTPUT:
Piyush 06917702023 12
10. Write a program to demonstrate the concept of interface when two interfaces have unique
methods and same data members
abstract class Shape
{
String name;
Shape(String name)
{
this.name = name;
}
abstract void draw();
final void display() {
System.out.println("Shape is : " + name);
}
}
class Circle extends Shape {
Circle() {
super("Circle");
}
@Override
void draw() {
System.out.println("Drawing a Circle");
}
}
public class AbstractDemo {
public static void main(String[] args) {
Circle circle = new Circle();
circle.draw();
circle.display();
}
}
OUTPUT:
Piyush 06917702023 13
11. Write a program to demonstrate checked exception during file handling.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File file = new File("sample.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred: File not found.");
e.printStackTrace();
}
}
}
Output:
Piyush 06917702023 14
12. Write a program to demonstrate unchecked exception.
public class UncheckedExceptionDemo {
public static void main(String[] args) {
int a = 10;
int b = 0;
// This will cause an ArithmeticException (division by zero)
int result = a / b;
System.out.println("Result: " + result);
}
}
Output:
Piyush 06917702023 15
13. Write a program to demonstrate creation of multiple child threads
class MyThread extends Thread {
private String threadName;
MyThread(String name) {
threadName = name;
}
public void run() {
for (int i = 1; i <= 2; i++) {
System.out.println(threadName + " - Count: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
System.out.println(threadName + " finished.");
}
}
public class MultipleThreadsDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread("Child Thread 1");
MyThread t2 = new MyThread("Child Thread 2");
MyThread t3 = new MyThread("Child Thread 3");
// Starting the threads
t1.start();
t2.start();
t3.start();
System.out.println("Main thread finished.");
}
}
Output:
Piyush 06917702023 16
14. Write a program to use Byte stream class to read from a text file and display the
content on the output screen
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ByteStreamReadExample {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("sample.txt");
int byteData;
System.out.println("File Content:");
while ((byteData = fis.read()) != -1) {
System.out.print((char) byteData);
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found.");
} catch (IOException e) {
System.out.println("Error reading the file.");
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
System.out.println("Error closing the file.");
}
}
}
}
Output:
Piyush 06917702023 17
15. Write a program to demonstrate any event handling.
import java.awt.*;
import java.awt.event.*;
public class EventHandlingDemo extends Frame implements ActionListener {
Button btn;
EventHandlingDemo() {
setTitle("Event Handling Example");
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
btn = new Button("Click Me");
btn.addActionListener(this);
add(btn);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
public static void main(String[] args) {
new EventHandlingDemo();
}
}
Output:
Piyush 06917702023 18
16. Create a class employee which have name, age and address of employee, include
methods getdata() and showdata(), getdata() takes the input from the user, showdata()
display the data in following format: Name: Age: Address:
import java.util.Scanner;
class Employee {
String name;
int age;
String address;
void getdata() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
name = sc.nextLine();
System.out.print("Enter age: ");
age = sc.nextInt();
sc.nextLine(); // Consume leftover newline
System.out.print("Enter address: ");
address = sc.nextLine();
}
void showdata() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
}
public class EmployeeDemo {
public static void main(String[] args) {
Employee emp = new Employee();
emp.getdata();
System.out.println("\nEmployee Details:");
emp.showdata();
}
}
Output:
Piyush 06917702023 19
17. Write a Java program to perform basic Calculator operations. Make a menu driven
program to select operation to perform (+ - * / ). Take 2 integers and perform operation
as chosen by user.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice;
int num1, num2;
boolean exit = false;
while (!exit) {
System.out.println("\n--- Basic Calculator ---");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.println("5. Exit");
System.out.print("Choose an operation (1-5): ");
choice = sc.nextInt();
if (choice == 5) {
System.out.println("Exiting the calculator. Goodbye!");
exit = true;
continue;
}
System.out.print("Enter first number: ");
num1 = sc.nextInt();
System.out.print("Enter second number: ");
num2 = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Result = " + (num1 + num2));
break;
case 2:
System.out.println("Result = " + (num1 - num2));
break;
case 3:
System.out.println("Result = " + (num1 * num2));
break;
case 4:
if (num2 == 0) {
System.out.println("Error: Division by zero is not allowed.");
} else {
System.out.println("Result = " + (num1 / num2));
}
break;
default:
System.out.println("Invalid choice! Please choose a valid option (1-5).");
Piyush 06917702023 20
}
}
sc.close();
}
}
Output:
Piyush 06917702023 21
18. Write a program to make use of BufferedStream to read lines from the keyboard
until 'STOP' is typed.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class BufferedStreamExample {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = "";
System.out.println("Enter text (type 'STOP' to quit):");
try {
while (true) {
System.out.print("> ");
inputLine = reader.readLine();
if (inputLine.equalsIgnoreCase("STOP")) {
System.out.println("Exiting the program.");
break;
}
System.out.println("You entered: " + inputLine);
}
} catch (IOException e) {
System.out.println("An error occurred while reading input.");
}
}
}
Output:
Piyush 06917702023 22
19. Write a program declaring a Java class called SavingsAccount with members
``accountNumber`` and ``Balance``. Provide member functions as ``depositAmount ()``
and ``withdrawAmount ()``. If user tries to withdraw an amount greater than their
balance then throw a user-defined exception.
import java.util.Scanner;
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
class SavingsAccount {
private int accountNumber;
private double balance;
public SavingsAccount(int accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public void depositAmount(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: ₹" + amount);
} else {
System.out.println("Invalid deposit amount!");
}
}
public void withdrawAmount(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Withdrawal failed: Insufficient balance!");
} else {
balance -= amount;
System.out.println("Withdrawn: ₹" + amount);
}
}
public void showBalance() {
System.out.println("Account No: " + accountNumber + " | Balance: ₹" + balance);
}
}
public class BankDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter account number: ");
int accNo = sc.nextInt();
System.out.print("Enter initial balance: ");
double initialBal = sc.nextDouble();
Piyush 06917702023 23
SavingsAccount account = new SavingsAccount(accNo, initialBal);
boolean running = true;
while (running) {
System.out.println("\n--- MENU ---");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Show Balance");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
try {
switch (choice) {
case 1:
System.out.print("Enter amount to deposit: ");
double dep = sc.nextDouble();
account.depositAmount(dep);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double wd = sc.nextDouble();
account.withdrawAmount(wd);
break;
case 3:
account.showBalance();
break;
case 4:
running = false;
System.out.println("Thank you for using the banking system!");
break;
default:
System.out.println("Invalid choice!");
}
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
}
}
sc.close();
}
}
Piyush 06917702023 24
Output:
Piyush 06917702023 25
20. Write a program creating 2 threads using Runnable interface. Print your name in
``run ()`` method of first class and "Hello Java" in ``run ()`` method of second thread.
class NamePrinter implements Runnable {
public void run() {
System.out.println("This is First Thread!");
}
}
class HelloPrinter implements Runnable {
public void run() {
System.out.println("This is Second Thread!!");
}
}
public class TwoThreadsDemo {
public static void main(String[] args) {
NamePrinter nameTask = new NamePrinter();
HelloPrinter helloTask = new HelloPrinter();
Thread t1 = new Thread(nameTask);
Thread t2 = new Thread(helloTask);
t1.start();
t2.start();
}
}
Output:
Piyush 06917702023 26
21. Write program that uses swings to display combination of RGB using 3 scrollbars.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RGBColorMixer extends JFrame implements AdjustmentListener {
JScrollBar redBar, greenBar, blueBar;
JPanel colorPanel;
public RGBColorMixer() {
setTitle("RGB Color Mixer");
setSize(400, 300);
setLayout(new BorderLayout());
colorPanel = new JPanel();
colorPanel.setBackground(Color.BLACK);
add(colorPanel, BorderLayout.CENTER);
redBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 256);
greenBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 256);
blueBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 256);
JPanel controlPanel = new JPanel(new GridLayout(3, 2));
controlPanel.add(new JLabel("Red"));
controlPanel.add(redBar);
controlPanel.add(new JLabel("Green"));
controlPanel.add(greenBar);
controlPanel.add(new JLabel("Blue"));
controlPanel.add(blueBar);
add(controlPanel, BorderLayout.SOUTH);
redBar.addAdjustmentListener(this);
greenBar.addAdjustmentListener(this);
blueBar.addAdjustmentListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void adjustmentValueChanged(AdjustmentEvent e) {
int r = redBar.getValue();
int g = greenBar.getValue();
int b = blueBar.getValue();
colorPanel.setBackground(new Color(r, g, b));
}
public static void main(String[] args) {
new RGBColorMixer();
}
}
Piyush 06917702023 27
Output:
Piyush 06917702023 28
22. Write a swing application that uses atleast 5 swing controls
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleForm extends JFrame implements ActionListener {
JTextField nameField;
JComboBox<String> genderBox;
JCheckBox agreeCheckBox;
JButton submitButton;
JTextArea outputArea;
public SimpleForm() {
setTitle("User Form");
setSize(400, 300);
setLayout(new FlowLayout());
add(new JLabel("Enter your name:"));
nameField = new JTextField(20);
add(nameField);
add(new JLabel("Select Gender:"));
String[] genders = {"Male", "Female", "Other"};
genderBox = new JComboBox<>(genders);
add(genderBox);
agreeCheckBox = new JCheckBox("I accept the terms and conditions.");
add(agreeCheckBox);
submitButton = new JButton("Submit");
submitButton.addActionListener(this);
add(submitButton);
outputArea = new JTextArea(5, 30);
outputArea.setEditable(false);
add(outputArea);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (agreeCheckBox.isSelected()) {
String name = nameField.getText();
String gender = (String) genderBox.getSelectedItem();
outputArea.setText("Form Submitted!\nName: " + name + "\nGender: " + gender);
} else {
outputArea.setText("Please accept the terms to proceed.");
Piyush 06917702023 29
}
}
public static void main(String[] args) {
new SimpleForm();
}
}
Output:
23. Write a program to implement border layout using Swing
Piyush 06917702023 30
import javax.swing.*;
import java.awt.*;
public class BorderLayoutExample extends JFrame {
public BorderLayoutExample() {
setTitle("BorderLayout Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set BorderLayout as layout manager
setLayout(new BorderLayout());
// Add components to each region
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("East"), BorderLayout.EAST);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("Center"), BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args) {
new BorderLayoutExample();
}
}
Output:
24. Write a java program to insert and update details data in the database.
Piyush 06917702023 31
//Mysql
CREATE DATABASE myskool;
USE myskool;
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(100),
grade VARCHAR(10)
);
select * from students;
//Java
import java.sql.*;
public class StudentDatabase {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/myskool";
String username = "root";
String password = "yoyo";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
String insertQuery = "INSERT INTO students (id, name, grade) VALUES (?, ?, ?)";
PreparedStatement insertStmt = conn.prepareStatement(insertQuery);
insertStmt.setInt(1, 1);
insertStmt.setString(2, "Rahul Sharma");
insertStmt.setString(3, "8th");
insertStmt.executeUpdate();
System.out.println(" Data inserted.");
String updateQuery = "UPDATE students SET grade = ? WHERE id = ?";
PreparedStatement updateStmt = conn.prepareStatement(updateQuery);
updateStmt.setString(1, "9th");
updateStmt.setInt(2, 1);
updateStmt.executeUpdate();
System.out.println(" Data updated.");
// Close connection
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Piyush 06917702023 32
Output:
25. Write a java program to retrieve data from database and display it on GUI.
Piyush 06917702023 33
//Mysql
CREATE DATABASE schoolDB;
USE schoolDB;
CREATE TABLE students_info (
student_id INT AUTO_INCREMENT PRIMARY KEY,
student_name VARCHAR(100),
student_age INT
);
INSERT INTO students_info (student_name, student_age) VALUES
('John Doe', 20),
('Jane Smith', 22);
select * from students_info;
//Java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.Vector;
public class StudentDatabaseGUI {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new StudentDatabaseGUI().createAndShowGUI());
}
public void createAndShowGUI() {
JFrame frame = new JFrame("Student Database");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
JTable table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
JButton loadButton = new JButton("Load Data");
loadButton.addActionListener(e -> loadData(table));
frame.add(loadButton, BorderLayout.SOUTH);
frame.setVisible(true);
}
public void loadData(JTable table) {
String url = "jdbc:mysql://localhost:3306/schoolDB";
String user = "root";
String password = "yoyo";
String query = "SELECT * FROM students_info";
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Student ID");
model.addColumn("Name");
model.addColumn("Age");
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
Piyush 06917702023 34
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
Vector<Object> row = new Vector<>();
row.add(rs.getInt("student_id")); // Changed column name to student_id
row.add(rs.getString("student_name")); // Changed column name to student_name
row.add(rs.getInt("student_age")); // Changed column name to student_age
model.addRow(row);
}
table.setModel(model);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error loading data: " + e.getMessage());
}
}
}
Output:
Piyush 06917702023 35