0% found this document useful (0 votes)
3 views

Practical V

The document contains a series of Java programming practical exercises, each with a specific aim and corresponding code. Examples include finding the maximum of three numbers, reversing digits, adding matrices, generating prime numbers, and demonstrating the use of various Java concepts such as classes, constructors, and string methods. Each practical exercise is accompanied by code snippets and expected outputs.

Uploaded by

vrajc2810
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Practical V

The document contains a series of Java programming practical exercises, each with a specific aim and corresponding code. Examples include finding the maximum of three numbers, reversing digits, adding matrices, generating prime numbers, and demonstrating the use of various Java concepts such as classes, constructors, and string methods. Each practical exercise is accompanied by code snippets and expected outputs.

Uploaded by

vrajc2810
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 85

AOOP 4340701

PRACTICAL-: 1(B)
AIM-: Write a program in Java to find maximum of three
Numbers using conditional operator.

CODE-:
public class MaxOfThree {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;

// Using conditional operator to find the maximum


int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

System.out.println("The maximum number is: " + max);


}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT:-

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 1(C)
AIM-: Write a program in Java to reverse the digits of a
Number using while loop

CODE:-
import java.util.Scanner;

public class ReverseDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}

System.out.println("Reversed Number: " + reversed);


scanner.close(); }
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 2(A)
AIM-: Write a program in Java to add two 3*3 matrices.
CODE-:
public class AddMatrices {
public static void main(String[] args) {
int[][] matrixA = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int[][] matrixB = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};

int[][] sum = new int[3][3];

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


for (int j = 0; j < 3; j++) {
sum[i][j] = matrixA[i][j] + matrixB[i][j];
}
}

System.out.println("Sum of the two matrices:");

236470307020 PAGE:
AOOP 4340701

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


for (int j = 0; j < 3; j++) {
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 2(B)
AIM-: Write a program in Java to generate first N prime
numbers.
CODE-:
import java.util.Scanner;

public class GeneratePrimes {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of N: ");
int N = scanner.nextInt();
int count = 0;
int number = 2; // Starting from the first prime number

System.out.println("First " + N + " prime numbers:");

while (count < N) {


if (isPrime(number)) {
System.out.print(number + " ");
count++;
}
number++;
}
scanner.close();
}

236470307020 PAGE:
AOOP 4340701

public static boolean isPrime(int num) {


for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 3(A)
AIM-: Write a program in Java which has a class Student having two instance
variables enrollment No and name. Create 3 objects of Student class main
method and display student’s name.

CODE-:
class Student {
// Instance variables
private String enrollmentNo;
private String name;

// Constructor
public Student(String enrollmentNo, String name) {
this.enrollmentNo = enrollmentNo;
this.name = name;
}

// Getter for name


public String getName() {
return name;
}
}

public class Main {


public static void main(String[] args) {

// Creating three Student objects

236470307020 PAGE:
AOOP 4340701

Student student1 = new Student("EN001", "Alice");


Student student2 = new Student("EN002", "Bob");
Student student3 = new Student("EN003", "Charlie");

System.out.println("Student 1 Name: " + student1.getName());


System.out.println("Student 2 Name: " + student2.getName());
System.out.println("Student 3 Name: " + student3.getName());
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 3(B)
AIM-: Write a program in Java which has a class
Rectangle having two instance variables height and
weight. Initialize the class using constructor.
CODE-:
import java.util.Scanner;

public class Rectangle {


// Instance variables
private double height;
private double width;

// Constructor to initialize the Rectangle


public Rectangle(double height, double width) {
this.height = height;
this.width = width;
}

// Getter for height


public double getHeight() {
return height;
}

// Getter for width


public double getWidth() {
return width;

236470307020 PAGE:
AOOP 4340701

// Method to calculate the area of the rectangle


public double calculateArea() {
return height * width;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Prompt user for height and width


System.out.print("Enter the height of the rectangle: ");
double height = scanner.nextDouble();

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


double width = scanner.nextDouble();

// Creating a Rectangle object with user input


Rectangle rectangle = new Rectangle(height, width);

// Displaying the properties and area of the rectangle


System.out.println("Rectangle: Height = " + rectangle.getHeight() + ",
Width = " + rectangle.getWidth() + ", Area = " + rectangle.calculateArea());

// Close the scanner


scanner.close();
}}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 3(B)
AIM-: Write a program in Java demonstrate the use of “this”
keyword.
CODE-:
class ThisKeywordDemo {
int a;
int b;

ThisKeywordDemo(int a, int b) {
this.a = a;
this.b = b;
}

void display() {
System.out.println("Value of a: " + this.a);
System.out.println("Value of b: " + this.b);
}

public static void main(String[] args) {


ThisKeywordDemo obj = new ThisKeywordDemo(10, 20);
obj.display();
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 3(C)
AIM-: Write a program in Java to demonstrate the use of “static”
keyword.
CODE-:
class StaticKeywordDemo {
static int count = 0;

StaticKeywordDemo() {
count++;
}

static void displayCount() {


System.out.println("Count: " + count);
}

public static void main(String[] args) {


StaticKeywordDemo obj1 = new StaticKeywordDemo();
StaticKeywordDemo obj2 = new StaticKeywordDemo();
StaticKeywordDemo obj3 = new StaticKeywordDemo();
StaticKeywordDemo.displayCount();
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 3(D)
AIM-:Write a program in Java to demonstrate the use of “static”
keyword.
CODE-:
public class StaticDemo {

// Static variable
static int staticCounter = 0;

// Instance variable
int instanceCounter = 0;

// Static block
static {
System.out.println("Static block is executed.");
}

// Static method
static void displayStaticMessage() {
System.out.println("This is a static method.");
// Accessing static variable inside static method
System.out.println("Static counter: " + staticCounter);
}

// Instance method
void displayInstanceMessage() {

236470307020 PAGE:
AOOP 4340701

System.out.println("This is an instance method.");


// Accessing static variable inside instance method
System.out.println("Static counter: " + staticCounter);
}

// Constructor
public StaticDemo() {
staticCounter++; // Incrementing static variable
instanceCounter++; // Incrementing instance variable
System.out.println("Instance created. Static Counter: " + staticCounter + ",
Instance Counter: " + instanceCounter);
}

public static void main(String[] args) {


// Accessing static method without creating an instance
StaticDemo.displayStaticMessage();

// Creating instances
StaticDemo obj1 = new StaticDemo();
StaticDemo obj2 = new StaticDemo();

// Accessing instance method using objects


obj1.displayInstanceMessage();
obj2.displayInstanceMessage();

// Accessing static variable without creating an instance

236470307020 PAGE:
AOOP 4340701

System.out.println("Static Counter accessed from main: " +


StaticDemo.staticCounter);
}
}
OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 4(A)
AIM-: Write a program in Java to demonstrate the use of "final"
keyword.
CODE-:
class FinalDemo {
final int finalVariable = 100;

final void displayMessage() {


System.out.println("This is a final method.");
}
}

public class Main {


public static void main(String[] args) {
FinalDemo obj = new FinalDemo();
System.out.println("Final Variable: " + obj.finalVariable);
obj.displayMessage();
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 4(B)
AIM-: Write a program in Java which has a class Shape having 2
overloaded methods area(float radius) and area(float length, float
width). Display the area of circle and rectangle using overloaded
methods.
CODE-:
class Shape {

// Method to calculate the area of a circle


float area(float radius) {
return 3.14159f * radius * radius;
}

// Method to calculate the area of a rectangle


float area(float length, float width) {
return length * width;
}
}

public class Main {


public static void main(String[] args) {
Shape shape = new Shape();

// Calculating the area of a circle


float circleArea = shape.area(5.0f); // Radius = 5.0

236470307020 PAGE:
AOOP 4340701

System.out.println("Area of Circle: " + circleArea);

// Calculating the area of a rectangle


float rectangleArea = shape.area(4.0f, 6.0f); // Length = 4.0,
Width = 6.0
System.out.println("Area of Rectangle: " + rectangleArea);
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 4(C)
AIM-: Write a program in Java to demonstrate the constructor
overloading.
CODE-:
class Car {
String model;
int year;
String color;

// Constructor with no parameters (default constructor)


Car() {
model = "Unknown";
year = 0;
color = "Unknown";
System.out.println("Default Constructor Called");
}

// Constructor with one parameter


Car(String model) {
this.model = model;
year = 2023; // Default year
color = "Black"; // Default color
System.out.println("Constructor with model parameter Called");
}

236470307020 PAGE:
AOOP 4340701

// Constructor with two parameters


Car(String model, int year) {
this.model = model;
this.year = year;
color = "White"; // Default color
System.out.println("Constructor with model and year
parameters Called");
}

// Constructor with three parameters


Car(String model, int year, String color) {
this.model = model;
this.year = year;
this.color = color;
System.out.println("Constructor with model, year, and color
parameters Called");
}

void displayDetails() {
System.out.println("Model: " + model + ", Year: " + year + ",
Color: " + color);
}
}

236470307020 PAGE:
AOOP 4340701

public class Main {


public static void main(String[] args) {
Car car1 = new Car(); // Calls default constructor
Car car2 = new Car("Tesla"); // Calls constructor with
model
Car car3 = new Car("BMW", 2021); // Calls constructor
with model and year
Car car4 = new Car("Audi", 2022, "Red"); // Calls constructor
with all parameters

car1.displayDetails();
car2.displayDetails();
car3.displayDetails();
car4.displayDetails();
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:
Write a java program to demonstrate use of “String” class methods

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 4(D)
AIM-: Write a java program to demonstrate use of “String” class methods
CODE-:
public class StringMethodsDemo {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = " Java Programming ";

// 1. Concatenation
String concatResult = str1.concat(str2);
System.out.println("Concatenation: " + concatResult);

// 2. Length of the string


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

// 3. Character at a specific index


System.out.println("Character at index 1 of str1: " + str1.charAt(1));

// 4. Comparison
System.out.println("str1 equals str2: " + str1.equals(str2));
System.out.println("str1 equals 'Hello': " + str1.equals("Hello"));

// 5. Substring
System.out.println("Substring of str3 (from index 3 to 7): " +
str3.substring(3, 7));

236470307020 PAGE:
AOOP 4340701

// 6. Trim spaces
System.out.println("Trimmed str3: '" + str3.trim() + "'");

// 7. Convert to uppercase and lowercase


System.out.println("Uppercase str1: " + str1.toUpperCase());
System.out.println("Lowercase str2: " + str2.toLowerCase());

// 8. Replace characters
System.out.println("Replace 'l' with 'x' in str1: " + str1.replace('l', 'x'));

// 9. Check if string contains a substring


System.out.println("str3 contains 'Java': " + str3.contains("Java"));

// 10. Index of a character


System.out.println("Index of 'o' in str1: " + str1.indexOf('o'));

// 11. Checking if string starts or ends with a specific substring


System.out.println("str1 starts with 'He': " + str1.startsWith("He"));
System.out.println("str2 ends with 'ld': " + str2.endsWith("ld"));
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 5(A)
AIM-: Write a program in Java to demonstrate single inheritance

CODE-:
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Child class inheriting from Animal


class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog(); // Creating an object of the child class
myDog.eat(); // Inherited method from Animal
myDog.bark(); // Method of the Dog class
}}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 5(B)
AIM-: Write a program in Java to demonstrate multilevel inheritance
CODE-:
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Child class inheriting from Animal


class Mammal extends Animal {
void walk() {
System.out.println("This mammal walks on land.");
}
}

// Grandchild class inheriting from Mammal


class Dog extends Mammal {
void bark() {
System.out.println("The dog barks.");
}
}

236470307020 PAGE:
AOOP 4340701

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog(); // Creating an object of the Dog class
myDog.eat(); // Inherited from Animal
myDog.walk(); // Inherited from Mammal
myDog.bark(); // Specific to Dog
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 5(C)
AIM-: Write a program in Java to demonstrate hierarchical
inheritance.
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Child class 1 inheriting from Animal


class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

// Child class 2 inheriting from Animal


class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}

236470307020 PAGE:
AOOP 4340701

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog(); // Object of Dog class
Cat myCat = new Cat(); // Object of Cat class

myDog.eat(); // Inherited from Animal


myDog.bark(); // Specific to Dog

myCat.eat(); // Inherited from Animal


myCat.meow(); // Specific to Cat
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 5(D)
AIM-: Write a program in Java to demonstrate method overriding.
CODE-:
// Parent class
class Animal {
void sound() {
System.out.println("This animal makes a sound.");
}
}
// Child class overriding the sound() method
class Dog extends Animal {
@Override
void sound() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Parent class object
Dog myDog = new Dog(); // Child class object

myAnimal.sound(); // Calls Animal's sound() method


myDog.sound(); // Calls Dog's overridden sound()
method

236470307020 PAGE:
AOOP 4340701

}
}

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 5(E)
AIM-: Write a program in Java which has a class Car having two
instance variables topSpeed and name. Override toString() method in
Car class. Create 3 instances of Car class and print the instances.
CODE-:
class Car {
int topSpeed;
String name;

// Constructor to initialize Car objects


Car(String name, int topSpeed) {
this.name = name;
this.topSpeed = topSpeed;
}

// Overriding the toString() method


@Override
public String toString() {
return "Car Name: " + name + ", Top Speed: " + topSpeed + "
km/h";
}
}

public class Main {


public static void main(String[] args) {

236470307020 PAGE:
AOOP 4340701

// Creating 3 instances of Car


Car car1 = new Car("Ferrari", 350);
Car car2 = new Car("Lamborghini", 330);
Car car3 = new Car("Porsche", 310);

// Printing the instances


System.out.println(car1);
System.out.println(car2);
System.out.println(car3);
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 6(A)
AIM-: Write a program in Java to implement multiple inheritance
using interfaces.
CODE-:
// First interface
interface Drivable {
void drive();
}

// Second interface
interface Flyable {
void fly();
}

// Class implementing both interfaces


class FlyingCar implements Drivable, Flyable {
public void drive() {
System.out.println("The flying car is driving on the road.");
}

public void fly() {


System.out.println("The flying car is flying in the sky.");
}
}

236470307020 PAGE:
AOOP 4340701

public class Main {


public static void main(String[] args) {
FlyingCar myFlyingCar = new FlyingCar(); // Object of FlyingCar
class
myFlyingCar.drive(); // Calling drive() method from Drivable
interface
myFlyingCar.fly(); // Calling fly() method from Flyable interface
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 6(B)
AIM-: Write a program in Java which has an abstract class Shape
having three subclasses: Triangle, Rectangle, and Circle
CODE-:
// Abstract class
abstract class Shape {
abstract double area(); // Abstract method to be implemented by
subclasses
}

// Triangle class
class Triangle extends Shape {
double base, height;

Triangle(double base, double height) {


this.base = base;
this.height = height;
}

@Override
double area() {
return 0.5 * base * height; // Area formula for triangle
}
}

236470307020 PAGE:
AOOP 4340701

// Rectangle class
class Rectangle extends Shape {
double length, width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
double area() {
return length * width; // Area formula for rectangle
}
}

// Circle class
class Circle extends Shape {
double radius;

Circle(double radius) {
this.radius = radius;
}

236470307020 PAGE:
AOOP 4340701

@Override
double area() {
return Math.PI * radius * radius; // Area formula for circle
}
}

public class Main {


public static void main(String[] args) {
Shape triangle = new Triangle(5, 10);
Shape rectangle = new Rectangle(4, 6);
Shape circle = new Circle(7);

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


System.out.println("Area of Rectangle: " + rectangle.area());
System.out.println("Area of Circle: " + circle.area());
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 6(C)
AIM-: Define method area() in the abstract class Shape and override
area() method tocalculate the area.
CODE-:
// Abstract class with a concrete area() method
abstract class Shape {
// Concrete method to display a generic message
void display() {
System.out.println("This is a shape.");
}

// Method to be overridden by subclasses to calculate the area


double area() {
return 0; // Default implementation (can be overridden)
}
}

// Triangle class
class Triangle extends Shape {
double base, height;

Triangle(double base, double height) {


this.base = base;
this.height = height;

236470307020 PAGE:
AOOP 4340701

@Override
double area() {
return 0.5 * base * height; // Area formula for triangle
}
}

// Rectangle class
class Rectangle extends Shape {
double length, width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
double area() {
return length * width; // Area formula for rectangle
}
}

// Circle class

236470307020 PAGE:
AOOP 4340701

class Circle extends Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
double area() {
return Math.PI * radius * radius; // Area formula for circle
}
}

public class Main {


public static void main(String[] args) {
Shape triangle = new Triangle(5, 10);
Shape rectangle = new Rectangle(4, 6);
Shape circle = new Circle(7);

triangle.display();
System.out.println("Area of Triangle: " + triangle.area());

rectangle.display();
System.out.println("Area of Rectangle: " + rectangle.area());

236470307020 PAGE:
AOOP 4340701

circle.display();
System.out.println("Area of Circle: " + circle.area());
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 6(D)
AIM-: Write a program in Java to demonstrate use of final Class.
CODE-:
// Final class
final class Vehicle {
String brand;

Vehicle(String brand) {
this.brand = brand;
}

void display() {
System.out.println("Brand: " + brand);
}
}

// Attempting to inherit from Vehicle will cause an error


// class Car extends Vehicle { // This will produce a compilation error
// Car(String brand) {
// super(brand);
// }
// }

public class Main {


public static void main(String[] args) {
Vehicle vehicle = new Vehicle("Toyota");

236470307020 PAGE:
AOOP 4340701

vehicle.display();
}
}

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 6(E)
AIM-: Write a program in Java to demonstrate use of package
CODE-:
Step 1: Create a Package
1. Create a directory for the package:
o Let's call the package mypackage.
o Inside this directory, create a file named Greeting.java.
package mypackage;
public class Greeting {
public void sayHello() {
System.out.println("Hello from the package!");
} }
✅ Step 2: Use the Package in Another Class
2. Create another file in the parent directory (outside mypackage):
o Name it Main.java.
import mypackage.Greeting; // Importing the package

public class Main {


public static void main(String[] args) {
Greeting greet = new Greeting(); // Creating an object of the Greeting
class
greet.sayHello(); // Calling the method from the package
}
}
Sample Output:
Hello from the package!

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 7(A)
AIM-: Write a program in Java to develop user defined exception
for'Divide by Zero' error
CODE-:
class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}

public class Main {


public static void divide(int numerator, int denominator) throws
DivideByZeroException {
if (denominator == 0) {
throw new DivideByZeroException("Cannot divide by zero!");
}
System.out.println("Result: " + (numerator / denominator));
}

public static void main(String[] args) {


try {
divide(10, 0); // Test case with divide by zero
} catch (DivideByZeroException e) {
System.out.println(e.getMessage());
}
}

236470307020 PAGE:
AOOP 4340701

}
OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 7(B)
AIM-: Write a program in Java to develop Banking Application in
which user deposits the amount Rs 25000 and then start
withdrawing of Rs 20000, Rs 4000 and it throws exception "Not
Sufficient Fund" when user withdraws Rs. 2000 there after.
CODE-:
// Custom exception for insufficient funds
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

public class BankingApp {

private double balance;

// Constructor to initialize the balance


public BankingApp(double initialBalance) {
this.balance = initialBalance;
}

// Method to deposit money


public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: Rs " + amount);
System.out.println("Current Balance: Rs " + balance);

236470307020 PAGE:
AOOP 4340701

// Method to withdraw money


public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Not Sufficient Funds. Current
Balance: Rs " + balance);
}
balance -= amount;
System.out.println("Withdrawn: Rs " + amount);
System.out.println("Current Balance: Rs " + balance);
}

public static void main(String[] args) {


BankingApp account = new BankingApp(25000); // Initialize with Rs 25000

try {
account.deposit(0); // Deposit Rs 0 to start with the initialized balance
account.withdraw(20000); // First withdrawal of Rs 20000
account.withdraw(4000); // Second withdrawal of Rs 4000
account.withdraw(2000); // Third withdrawal of Rs 2000 (should throw
an exception)
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage()); // Catch and print the exception
message
}
}

236470307020 PAGE:
AOOP 4340701

}
CODE-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 8(A)
AIM-: Write a program that executes two threads. One thread displays “Thread1” every 1000
milliseconds, and the other displays “Thread2” every 2000 milliseconds. Create the threads by
extending the Thread class

CODE-:
// First thread that prints "Thread1" every 1000 milliseconds
class Thread1 extends Thread {
public void run() {
try {
while (true) {
System.out.println("Thread1");
Thread.sleep(1000); // Sleep for 1000 milliseconds
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

// Second thread that prints "Thread2" every 2000 milliseconds


class Thread2 extends Thread {
public void run() {
try {
while (true) {
System.out.println("Thread2");

236470307020 PAGE:
AOOP 4340701

Thread.sleep(2000); // Sleep for 2000 milliseconds


}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public class MultiThreadExample {


public static void main(String[] args) {
// Create two threads
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();

// Start both threads


t1.start();
t2.start();
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 8(B)
AIM-: Write a program that executes two threads. One thread will print the even numbers and
another thread will print odd numbers from 1 to 200.

CODE-:
// Thread to print even numbers
class EvenThread extends Thread {
public void run() {
for (int i = 2; i <= 200; i += 2) {
System.out.println("Even: " + i);
try {
Thread.sleep(100); // Optional sleep to make the output
readable
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

// Thread to print odd numbers


class OddThread extends Thread {
public void run() {
for (int i = 1; i <= 199; i += 2) {
System.out.println("Odd: " + i);
try {

236470307020 PAGE:
AOOP 4340701

Thread.sleep(100); // Optional sleep to make the output


readable
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

public class Main {


public static void main(String[] args) {
// Create both threads
EvenThread evenThread = new EvenThread();
OddThread oddThread = new OddThread();

// Start both threads


evenThread.start();
oddThread.start();
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 9(A)
AIM-: Write a program in Java to perform read and write operations on a Text file
CODE-:
import java.io.*;

public class Main {

// Method to write to a text file


public static void writeToFile(String filename, String content) {
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(filename))) {
writer.write(content); // Write the content to the file
System.out.println("Successfully written to the file: " +
filename);
} catch (IOException e) {
System.out.println("An error occurred while writing to the
file.");
e.printStackTrace();
}
}

// Method to read from a text file


public static void readFromFile(String filename) {
try (BufferedReader reader = new BufferedReader(new
FileReader(filename))) {

236470307020 PAGE:
AOOP 4340701

String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // Print each line from the file
}
} catch (IOException e) {
System.out.println("An error occurred while reading from the
file.");
e.printStackTrace();
}
}

public static void main(String[] args) {


String filename = "example.txt"; // The file name
String content = "Hello, this is a test.\nWelcome to Java file
handling!";

// Write to the file


writeToFile(filename, content);

// Read from the file


System.out.println("\nContent of the file:");
readFromFile(filename);
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 9(B)
AIM-: ) Write a program in Java to demonstrate use of List. 1) Create ArrayList and add weekdays
(in string form) 2) Create LinkedList and add months (in string form) Display

CODE-:
import java.util.*;

public class ListDemo {


public static void main(String[] args) {
// Creating an ArrayList and adding weekdays
List<String> weekdays = new ArrayList<>();
weekdays.add("Monday");
weekdays.add("Tuesday");
weekdays.add("Wednesday");
weekdays.add("Thursday");
weekdays.add("Friday");
weekdays.add("Saturday");
weekdays.add("Sunday");

// Creating a LinkedList and adding months


List<String> months = new LinkedList<>();
months.add("January");
months.add("February");
months.add("March");
months.add("April");

236470307020 PAGE:
AOOP 4340701

months.add("May");
months.add("June");
months.add("July");
months.add("August");
months.add("September");
months.add("October");
months.add("November");
months.add("December");

// Display the weekdays (ArrayList)


System.out.println("Weekdays (ArrayList):");
for (String day : weekdays) {
System.out.println(day);
}

// Display the months (LinkedList)


System.out.println("\nMonths (LinkedList):");
for (String month : months) {
System.out.println(month);
}
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 10(A)
AIM-: Write a program in Java to create a new HashSet, add colors(in string form) and iterate
through all elements using for-each loop to display the collection

CODE-:
import java.util.HashSet;

public class HashSetDemo {


public static void main(String[] args) {
// Create a new HashSet to store color names
HashSet<String> colors = new HashSet<>();

// Add color names to the HashSet


colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Yellow");
colors.add("Orange");
colors.add("Purple");

// Iterate through all elements using a for-each loop and display


the collection
System.out.println("Colors in the HashSet:");
for (String color : colors) {
System.out.println(color);
}

236470307020 PAGE:
AOOP 4340701

}
}
OUTPUT-:

236470307020 PAGE:
AOOP 4340701

PRACTICAL-: 10(B)
AIM-: Write a Java program to create a new HashMap, add 5 students’data (enrolment no and
name). retrieve and display the student’s name from HashMap using enrolment no.

CODE-:
import java.util.HashMap;

public class StudentHashMap {


public static void main(String[] args) {
// Create a new HashMap to store student data (enrollment no
as key and name as value)
HashMap<String, String> students = new HashMap<>();

// Add 5 students' data (enrollment no and name) with Indian


names
students.put("EN001", "Aarav Sharma");
students.put("EN002", "Isha Patel");
students.put("EN003", "Arjun Reddy");
students.put("EN004", "Priya Desai")000;
students.put("EN005", "Kabir Singh");

// Enrolment number to search for


String enrolmentNo = "EN003";

// Retrieve and display the student's name using the enrollment


number

236470307020 PAGE:
AOOP 4340701

if (students.containsKey(enrolmentNo)) {
System.out.println("Student Name for Enrolment No " +
enrolmentNo + ": " + students.get(enrolmentNo));
} else {
System.out.println("Student not found with Enrolment No " +
enrolmentNo);
}
}
}

236470307020 PAGE:
AOOP 4340701

OUTPUT-:

236470307020 PAGE:

You might also like