Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY

SHRI BALWANT INSTITUTE OF TECHNOLOGY


JAVA
PRACTICAL FILE
BCA-202

Submitted By: Submitted To:


Name: Nikhil Singh
Class: BCA IV SEM
Enrolment no:
INDEX
S. Detailed Statement Mapping to
No. CO #
1. Write a program declaring a class Rectangle with data members length CO1
and breadth and member functions Input, Output, and Calc Area.
2. Write a program to demonstrate the use of method overloading to CO1
calculate the area of a square, rectangle, and triangle.
3. Write a program to demonstrate the use of static variables, static CO1
methods, and static blocks.
4. Write a program to demonstrate the concept of “this”. CO1
5. Write a program to demonstrate multi-level and hierarchical CO2
inheritance.
6. Write a program to use “super()” to invoke the base class CO2
constructor.
7. Write a program to demonstrate run-time polymorphism. CO1
8. Write a program to demonstrate the concept of aggregation. CO2
9. Write a program to demonstrate the concept of an abstract CO2
class with a constructor and “final” method.
10. Write a program to demonstrate the concept of interface when CO1
two interfaces have unique methods and the same data
members.
11. Write a program to demonstrate a checked exception during
file handling.
12. Write a program to demonstrate an unchecked exception. CO4
13. Write a program to demonstrate the creation of multiple child CO6
threads.
14. Write a program to use Byte stream class to read from a text CO5
file and display the content on the output screen.
15. Write a program to demonstrate any event handling. CO7
16 Create a class Employee with attributes name, age, and address. COI
Implement methods getData() and showData(). The
getData() method should take input from the user, and
showData() should display the data in the format:
Name:
Age:
Address:

17 Write a Java program to perform basic calculator operations. CO5


Implement a menu-driven program to select an operation (+,
-, *, /).
18 Write a program to make use of BufferedStream to read lines CO4, CO6
from the keyboard until 'STOP' is typed.
19 Declare a Java class Savings Account with members “account C07
Number” and “Balance”. Provide member functions as
“deposit Amount()” and “withdraw Amount ()”. If the user
tries to withdraw an amount greater than their balance, throw
a user-defined exception.
20 Write a program creating 2 threads using Runnable interface. C07
Print your name in the “run ()” method of the first class and
"Hello Java" in the “run ()” method of the second thread.
21 Write a program using Swing to display a combination of RGB C07
using 3 scrollbars.
22 Write a Swing application that uses at least 5 Swing controls. C07
23 Write a program to implement border layout using Swing. C07
24 Write a Java program to insert and update details data in the C07
database.
25 Write a Java program to retrieve data from a database and C07, CO
display it on GUI.

PROGRAM1
Aim: Write a program declaring a class Rectangle with data members length and breadth
and member functions Input, Output, and Calc Area.

CODE:
import java.util.Scanner;

public class Rectangle {

private double length;

private double breadth;


public void input() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the length of the rectangle: ");

length = scanner.nextDouble();

System.out.print("Enter the breadth of the rectangle: ");

breadth = scanner.nextDouble();

public double calcArea() {

return length * breadth;

public void output() {

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

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

System.out.println("Breadth: " + breadth);

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

public static void main(String[] args) {

Rectangle rectangle = new Rectangle();

rectangle.input();

rectangle.output();

}
}

OUTPUT:

PROGRAM2
Aim: Write a program to demonstrate the use of method overloading to calculate the area
of a square, rectangle, and triangle.

CODE:
public class AreaCalculator {

public double calculateArea(double side) {

return side * side; // Area of square}


public double calculateArea(double length, double breadth) {

return length * breadth; // Area of rectangle}

public double calculateArea(double base, double height, boolean isTriangle) {

if (isTriangle) {

return 0.5 * base * height; // Area of triangle

return -1; // Invalid input for triangle

public static void main(String[] args) {

AreaCalculator calculator = new AreaCalculator();

System.out.println("Area of square: " + calculator.calculateArea(5));

System.out.println("Area of rectangle: " + calculator.calculateArea(5, 10));

System.out.println("Area of triangle: " + calculator.calculateArea(5, 10, true));

}}

OUTPUT:

PROGRAM3
Aim: Write a program to demonstrate the use of static variables, static methods, and static
blocks.

CODE:
public class StaticDemo {

static int staticVariable;


static {

staticVariable = 10;

System.out.println("Static block executed. Static variable initialized to: " +


staticVariable);

static void staticMethod() {

System.out.println("Static method called. Static variable is: " + staticVariable);

public static void main(String[] args) {

StaticDemo.staticMethod();

OUTPUT:

PROGRAM4
Aim: Write a program to demonstrate the concept of “this”.
CODE:
public class ThisDemo {

private int value;


public ThisDemo(int value) {

this.value = value;

public void setValue(int value) {

this.value = value;

public void displayValue() {

System.out.println("Value: " + this.value);

public static void main(String[] args) {

ThisDemo demo = new ThisDemo(10);

demo.displayValue();

demo.setValue(20);

demo.displayValue();

}}

OUTPUT:

PROGRAM5
Aim: Write a program to demonstrate multi-level and hierarchical inheritance.
CODE:
class Animal {

void eat() {
System.out.println("This animal eats food.");

class Mammal extends Animal {

void walk() {

System.out.println("This mammal walks.");

class Dog extends Mammal {

void bark() {

System.out.println("This dog barks.");

class Cat extends Mammal {

void meow() {

System.out.println("This cat meows.");

public class InheritanceDemo {

public static void main(String[] args) {

Dog dog = new Dog();


Cat cat = new Cat();

dog.eat();

dog.walk();

dog.bark();

cat.eat();

cat.walk();

cat.meow();

OUTPUT:

PROGRAM6
Aim: Write a program to use “super()” to invoke the base class constructor.
CODE:
class Parent {

Parent() {

System.out.println("Parent class constructor called.");

class Child extends Parent {

Child() {

super();

System.out.println("Child class constructor called.");

public class SuperDemo {

public static void main(String[] args) {

Child child = new Child();

OUTPUT:

PROGRAM7
Aim: Write a program to demonstrate run-time polymorphism.
CODE:
class Animal {

void sound() {

System.out.println("Animal makes a sound.");

class Dog extends Animal {

void sound() {

System.out.println("Dog barks.");

class Cat extends Animal {

void sound() {

System.out.println("Cat meows.");

public class PolymorphismDemo {

public static void main(String[] args) {

Animal myAnimal;

myAnimal = new Dog();

myAnimal.sound();
myAnimal = new Cat();

myAnimal.sound();

OUTPUT:

PROGRAM8
Aim: Write a program to demonstrate the concept of aggregation.
CODE:
class Address {

String city, state, 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;

void display() {

System.out.println(id + " " + name);

System.out.println(address.city + " " + address.state + " " + address.country);


}

public class AggregationDemo {

public static void main(String[] args) {

Address address = new Address("New York", "New York", "USA");

Employee employee = new Employee(101, "John Doe", address);

employee.display();

OUTPUT:

PROGRAM9
Aim: Write a program to demonstrate the concept of an abstract class with a
constructor and “final” method.
CODE:
abstract class Animal {

Animal() {

System.out.println("Animal is created.");

abstract void sound();

final void sleep() {

System.out.println("Animal is sleeping.");

class Dog extends Animal {

void sound() {

System.out.println("Dog barks.");

public class AbstractDemo {

public static void main(String[] args) {

Animal animal = new Dog();

animal.sound();

animal.sleep(); }}
OUTPUT:

PROGRAM10
Aim: Write a program to demonstrate the concept of interface when two
interfaces have unique methods and the same data members.
CODE:
interface A {

int data = 10;

void methodA();

interface B {

int data = 20;

void methodB();

class ImplementingClass implements A, B {

public void methodA() {

System.out.println("Method A from Interface A");

public void methodB() {

System.out.println("Method B from Interface B");


}

void displayData() {

System.out.println("Data from Interface A: " + A.data);

System.out.println("Data from Interface B: " + B.data);

public class InterfaceDemo {

public static void main(String[] args) {

ImplementingClass obj = new ImplementingClass();

obj.methodA();

obj.methodB();

obj.displayData();

OUTPUT:
PROGRAM11
Aim: Write a program to demonstrate a checked exception during file handling.
CODE:
import java.io.*;

public class CheckedExceptionDemo {

public static void main(String[] args) {

try {

FileReader file = new FileReader("example.txt");

BufferedReader reader = new BufferedReader(file);

String line;

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

System.out.println(line);

reader.close();

} catch (IOException e) {

System.out.println("An IOException occurred: " + e.getMessage());

OUTPUT:
PROGRAM12
Aim: Write a program to demonstrate an unchecked exception.
CODE:
public class UncheckedExceptionDemo {

public static void main(String[] args) {

try {

int a = 10;

int b = 0;

int result = a / b;

System.out.println("Result: " + result);

} catch (ArithmeticException e) {

System.out.println("An ArithmeticException occurred: " + e.getMessage());

OUTPUT:
PROGRAM13
Aim: Write a program to demonstrate the creation of multiple child threads.
CODE:
class ChildThread extends Thread {

private String threadName;

ChildThread(String name) {

threadName = name;

public void run() {

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

System.out.println(threadName + ": " + i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(e.getMessage());

}
public class MultipleThreadsDemo {

public static void main(String[] args) {

ChildThread thread1 = new ChildThread("Thread 1");

ChildThread thread2 = new ChildThread("Thread 2");

thread1.start();

thread2.start();

OUTPUT:
PROGRAM14
Aim: Write a program to demonstrate the creation of multiple child threads.
CODE:
import java.io.*;

public class ByteStreamDemo {

public static void main(String[] args) {

try (FileInputStream fis = new FileInputStream("example.txt")) {

int content;

while ((content = fis.read()) != -1) {

System.out.print((char) content);

} catch (IOException e) {

System.out.println("An IOException occurred: " + e.getMessage());

OUTPUT:
PROGRAM15
Aim: Write a program to use Byte stream class to read from a text file and display
the content on the output screen.
CODE:
import java.awt.*;

import java.awt.event.*;

public class EventHandlingDemo extends Frame implements ActionListener {

TextField textField;

EventHandlingDemo() {

textField = new TextField();

textField.setBounds(50, 50, 150, 20);

Button button = new Button("Click Me");

button.setBounds(50, 100, 60, 30);

button.addActionListener(this);

add(button);

add(textField);

setSize(300, 200);
setLayout(null);

setVisible(true);

public void actionPerformed(ActionEvent e) {

textField.setText("Hello, World!");

public static void main(String[] args) {

new EventHandlingDemo(); }}

PROGRAM16
Aim: Create a class Employee with attributes name, age, and address. Implement
methods getData() and showData(). The getData() method should take input from
the user, and showData() should display the data in the format:
Name:
Age:
Address:
CODE:
import java.util.Scanner;

public class Employee {

private String name;

private int age;

private String address;

// Method to get data from the user

public void getData() {

Scanner scanner = new Scanner(System.in);


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

this.name = scanner.nextLine();

System.out.print("Enter age: ");

this.age = scanner.nextInt();

scanner.nextLine(); // Consume newline character

System.out.print("Enter address: ");

this.address = scanner.nextLine();

// Method to display employee data

public void showData() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Address: " + address);

public static void main(String[] args) {

Employee employee = new Employee();

employee.getData();

System.out.println("\nEmployee Details:");

employee.showData();

}
}

OUTPUT:

PROGRAM17
Aim: Write a Java program to perform basic calculator operations. Implement a
menu-driven program to select an operation (+, -, *, /).
CODE:
import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Display menu

System.out.println("Select operation:");

System.out.println("1. Addition (+)");


System.out.println("2. Subtraction (-)");

System.out.println("3. Multiplication (*)");

System.out.println("4. Division (/)");

System.out.print("Enter your choice: ");

// Read user's choice

int choice = scanner.nextInt();

// Read two integers

System.out.print("Enter first number: ");

int num1 = scanner.nextInt();

System.out.print("Enter second number: ");

int num2 = scanner.nextInt();

// Perform operation based on choice

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("Result: " + ((double) num1 / num2));

} else {

System.out.println("Cannot divide by zero!");

break;

default:

System.out.println("Invalid choice!");

scanner.close();

OUTPUT:
PROGRAM18
Aim: Write a program to make use of BufferedStream to read lines from the
keyboard until 'STOP' is typed.
CODE:
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));

System.out.println("Enter lines of text. Type 'STOP' to exit.");

try {

String line;

while (!(line = reader.readLine()).equals("STOP")) {

System.out.println("You entered: " + line);

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

reader.close();

} catch (IOException e) {
e.printStackTrace();

OUTPUT:

PROGRAM19
Aim: Declare a Java class Savings Account with members “account Number” and
“Balance”. Provide member functions as “deposit Amount()” and “withdraw Amount
()”. If the user tries to withdraw an amount greater than their balance, throw a
user-defined exception.
CODE:
public class SavingsAccount {

private int accountNumber;

private double balance;


public SavingsAccount(int accountNumber, double balance) {

this.accountNumber = accountNumber;

this.balance = balance;

public void depositAmount(double amount) {

balance += amount;

public void withdrawAmount(double amount) throws InsufficientBalanceException {

if (amount > balance) {

throw new InsufficientBalanceException("Insufficient balance.");

balance -= amount;

public int getAccountNumber() {

return accountNumber;

public double getBalance() {

return balance;

}
class InsufficientBalanceException extends Exception {

public InsufficientBalanceException(String message) {

super(message);

PROGRAM20
Aim: Write a program creating 2 threads using Runnable interface. Print your
name in the “run ()” method of the first class and "Hello Java" in the “run ()”
method of the second thread.
CODE:
public class NamePrinter implements Runnable {

@Override

public void run() {

System.out.println("Your Name");

public class MessagePrinter implements Runnable {

@Override

public void run() {

System.out.println("Hello Java");

}
public class Main {

public static void main(String[] args) {

Thread t1 = new Thread(new NamePrinter());

Thread t2 = new Thread(new MessagePrinter());

t1.start();

t2.start();

OUTPUT:

PROGRAM21
Aim: Write a program using Swing to display a combination of RGB using 3
scrollbars.
CODE:
import javax.swing.*;

import java.awt.*;
public class RGBDisplay extends JFrame {

private JScrollBar redBar;

private JScrollBar greenBar;

private JScrollBar blueBar;

private JPanel colorPanel;

public RGBDisplay() {

setTitle("RGB Color Display");

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

redBar = new JScrollBar(JScrollBar.HORIZONTAL);

greenBar = new JScrollBar(JScrollBar.HORIZONTAL);

blueBar = new JScrollBar(JScrollBar.HORIZONTAL);

colorPanel = new JPanel();

colorPanel.setBackground(Color.BLACK);

redBar.addAdjustmentListener(e -> updateColor());

greenBar.addAdjustmentListener(e -> updateColor());

blueBar.addAdjustmentListener(e -> updateColor());

add(redBar, BorderLayout.NORTH);
add(greenBar, BorderLayout.CENTER);

add(blueBar, BorderLayout.SOUTH);

add(colorPanel, BorderLayout.CENTER);

setVisible(true);

private void updateColor() {

int red = redBar.getValue();

int green = greenBar.getValue();

int blue = blueBar.getValue();

colorPanel.setBackground(new Color(red, green, blue));

public static void main(String[] args) {

new RGBDisplay();

PROGRAM22
Aim: Write a Swing application that uses at least 5 Swing controls.
CODE:
import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class SwingControlsExample extends JFrame {

public SwingControlsExample() {

setTitle("Swing Controls Example");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridLayout(6, 1)); // 6 rows, 1 column

// JLabel

JLabel label = new JLabel("Enter your name:");

add(label);

// JTextField

JTextField textField = new JTextField();

add(textField);

// JButton

JButton button = new JButton("Click Me");

add(button);
// JCheckBox

JCheckBox checkBox = new JCheckBox("I agree to the terms and conditions");

add(checkBox);

// JRadioButton

JRadioButton radioButton1 = new JRadioButton("Option 1");

JRadioButton radioButton2 = new JRadioButton("Option 2");

ButtonGroup group = new ButtonGroup();

group.add(radioButton1);

group.add(radioButton2);

add(radioButton1);

add(radioButton2);

// ActionListener for JButton

button.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

String name = textField.getText();

JOptionPane.showMessageDialog(SwingControlsExample.this, "Hello, " +


name + "!");

});

setVisible(true);

}
public static void main(String[] args) {

SwingControlsExample example = new SwingControlsExample();

OUTPUT:
PROGRAM23
Aim: Write a program to implement border layout using Swing.
CODE:
import javax.swing.*;

import java.awt.*;

public class BorderLayoutExample extends JFrame {

public BorderLayoutExample() {

setTitle("BorderLayout Example");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create buttons

JButton northButton = new JButton("North");

JButton southButton = new JButton("South");

JButton eastButton = new JButton("East");

JButton westButton = new JButton("West");

JButton centerButton = new JButton("Center");

// Add buttons to the frame with BorderLayout

add(northButton, BorderLayout.NORTH);

add(southButton, BorderLayout.SOUTH);

add(eastButton, BorderLayout.EAST);
add(westButton, BorderLayout.WEST);

add(centerButton, BorderLayout.CENTER);

setVisible(true);

public static void main(String[] args) {

new BorderLayoutExample();

You might also like