You are on page 1of 34

Kalyani Government Engineering College

Kalyani, West Bengal

Department of Information Technology


OBJECT ORIENTED PROGRAMMING LAB
PCA-II

Name: Abhoy Biswas _


Roll Number :10200321037 Semister :5th Year: Third _
Registration Number: 211020100210061 (2021-22)

Subject Name: OOPS Lab _________Subject Code: PCC-CS593(5516)


INDEX PROBLEM PAGE OUTPUT ON PAGE
1 Create a class Room which will store the 3-4 4
length, width and height of the room in
three private variables, constructor to
initialize the variables, method to calculate
the surface area, method to calculate the
volume of the room. Create another Main
class which will use the earlier class,
create instances of rooms, set the values
of the variables and would calculate the
surface area and volume of the room
object.
2 Create a class Student with the 5-6 7
variables to represent the name of the
student and marks of the five subjects
store into an array, constructor to
initialize the variables. Write method to
compute total marks, average marks,
method to calculate letter grade, toString
method to return object as a string.
Create Main class to demonstrate the
functioning of the above.
3 . Create a class Account with the 7 7
variables to represent the account
holder's name, account number, account
type (S for savings and C for Current),
balance amount, use constructor to
initialize the variables. Write method to
deposit money, withdrawal of
money(balance shouldn't be below
₹1000), toString method to return object
as a string. Use static variable to keep
track the number of transactions. Create
Main class to demonstrate the
functioning of the above.
4 WAP in java to demonstrate the use of 10 11
method overloading:
Overloaded Method: area(), area(int) for
square, area(int,int) for rectangle,
area(int,int,int) for triangle, area(double)
for circle, area(int,int,int,int) for straight
line (i.e. calculate length of straight in
this case)
5 Demonstrate the concept for the 13-14 12
following operation.
a. Stopping Overriding with Final
b. Stopping Inheritance with Final
c. Creating Constant with Final
6 Write a Java program to implement 15
single inheritance.
7 Write a Java program to implement 16 17
multilevel inheritance.
8 Write a Java program to implement 18 17
hierarchical inheritance.
9 Write a Java program to implement 19 17
static binding.

1
10 Write a Java program to implement 20 17
dynamic binding.
11 . Write a Java program to implement 21 171
abstract class.
12 . Demonstrate the use of super keyword. 23 24
13 Implement Dynamic method dispatch 25 24
using Abstract class.
14 Create an abstract class Shape with 27-29 27
methods calc_area and calc_volume.
Derive
three classes Sphere (radius), Cone
(radius, height) and Cylinder (radius,
height), Box (length, breadth, height)
from it. Calculate area and volume of all.
(Use Method overriding).
15 Implement a class having private 29 29
variables and methods. Demonstrate
how to use those variables and methods
by objects.
16 Implement use of static variables and 30
methods in a class
17 Perform method overloading with basic 30
example.
18 Perform constructor overloading with 31 31
basic example.
19 Implement class shape take members 32 32
length breadth height & calculate area ()
perimeter () volume () etc. Create
another supportive class to create
objects. Input will be taken from user.
20 Write a Java program to accepts an 33 33
integer and count the factors of the
number.

2
1.Create a class Room which will store the length, width and height of the room in three private
variables, constructor to initialize the variables, method to calculate the surface area, method to
calculate the volume of the room. Create another Main class which will use the earlier class,
create instances of rooms, set the values of the variables and would calculate the surface area
and volume of the room object.

Ans : import java.util.Scanner;

class Room {

private double L;
private double W;
private double H;

public Room(double L, double W, double H) {


this.L = L;
this.W = W;
this.H = H;

public double calculateSurfaceArea() {


return 2 * (L * W + L * H + W * H);

public double calculateVolume() {


return L * W * H;

}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the dimensions for Room 1:");

System.out.print("L: ");
double L1 = scanner.nextDouble();

3
System.out.print("W: ");
double W1 = scanner.nextDouble();
System.out.print("H: ");

double H1 = scanner.nextDouble();
Room room1 = new Room(L1, W1, H1);

System.out.println("Enter the dimensions for Room 2:");

System.out.print("L: ");
double L2 = scanner.nextDouble();
System.out.print("W: ");
double W2 = scanner.nextDouble();

System.out.print("H: ");
double H2 = scanner.nextDouble();
Room room2 = new Room(L2, W2, H2);

scanner.close();

double surfaceArea1 = room1.calculateSurfaceArea();


double volume1 = room1.calculateVolume();

double surfaceArea2 = room2.calculateSurfaceArea();


double volume2 = room2.calculateVolume();

System.out.println("Room 1 Surface Area: " + surfaceArea1 + " sq units");


System.out.println("Room 1 Volume: " + volume1 + " cubic units");
System.out.println("Room 2 Surface Area: " + surfaceArea2 + " sq units");
System.out.println("Room 2 Volume: " + volume2 + " cubic units");

}
}

4
2.Create a class Student with the variables to represent the name of the student and marks of
the five subjects store into an array, constructor to initialize the variables. Write method to
compute total marks, average marks, method to calculate letter grade, toString method to return
object as a string. Create Main class to demonstrate the functioning of the above.
Ans
import java.util.Scanner;
class Student {
private String name;
private int[] marks = new int[5];

public Student(String name, int[] marks) {


this.name = name;
this.marks = marks;
}
public int computeTotalMarks() {
int total = 0;
for (int mark : marks) {
total += mark;
}
return total;
}
public double computeAverageMarks() {
int total = computeTotalMarks();
return (double) total / marks.length;
}
public String calculateLetterGrade() {
double average = computeAverageMarks();
if (average >= 90) {
return "A+";
} else if (average >= 80) {
return "A";
} else if (average >= 70) {
return "B";
} else if (average >= 60) {
return "C";
} else if (average >= 50) {

5
return "D";
} else {
return "F";
}
}

@Override
public String toString() {
return "Student Name: " + name +
"\nTotal Marks: " + computeTotalMarks() +
"\nAverage Marks: " + computeAverageMarks() +
"\nLetter Grade: " + calculateLetterGrade();
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the student's name: ");


String name = scanner.nextLine();

int[] marks = new int[5];


for (int i = 0; i < 5; i++) {
System.out.print("Enter mark for Subject " + (i + 1) + ": ");
marks[i] = scanner.nextInt();
}

Student student = new Student(name, marks);


scanner.close();
System.out.println("Student Details:");
System.out.println(student);
}

6
Out put of 2.

Output of 3

7
3. Create a class Account with the variables to represent the account holder's name, account
number, account type (S for savings and C for Current), balance amount, use constructor to
initialize the variables. Write method to deposit money, withdrawal of money(balance shouldn't be
below ₹1000), toString method to return object as a string. Use static variable to keep track the
number of transactions. Create Main class to demonstrate the functioning of the above.
Ans import java.util.Scanner;
class Account {
private String accountHolderName;
private String accountNumber;
private char accountType;
private double balance;
private static int numTransactions = 0;

public Account(String accountHolderName, String accountNumber, char accountType, double


balance) {
this.accountHolderName = accountHolderName;
this.accountNumber = accountNumber;
this.accountType = accountType;
this.balance = balance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
numTransactions++;
} else {
System.out.println("Invalid deposit amount. Please enter a positive amount.");
}
}

public void withdraw(double amount) {


if (amount > 0) {
if (balance - amount >= 1000) {
balance -= amount;
numTransactions++;
} else {
System.out.println("Insufficient balance. Minimum balance of ₹1000 must be
maintained.");
}
} else {
System.out.println("Invalid withdrawal amount. Please enter a positive amount.");
}
}

public static int getNumTransactions() {


return numTransactions;
}

@Override
public String toString() {
return "Account Holder Name: " + accountHolderName +
"\nAccount Number: " + accountNumber +
"\nAccount Type: " + accountType +
"\nBalance: ₹" + balance;
}
}

8
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter account holder's name: ");


String name = scanner.nextLine();

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


String accountNumber = scanner.nextLine();

System.out.print("Enter account type (S for Savings, C for Current): ");


char accountType = scanner.nextLine().charAt(0);

System.out.print("Enter initial balance: ₹");


double balance = scanner.nextDouble();

Account account = new Account(name, accountNumber, accountType, balance);


int choice;
do {
System.out.println("\nOptions:");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. View Account Details");
System.out.println("4. Number of Transactions");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter the deposit amount: ₹");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter the withdrawal amount: ₹");
double withdrawalAmount = scanner.nextDouble();
account.withdraw(withdrawalAmount);
break;
case 3:
System.out.println("\nAccount Details:");
System.out.println(account);
break;
case 4:
System.out.println("Number of Transactions: " + Account.getNumTransactions());
break;
case 0:
System.out.println("Exiting program.");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
} while (choice != 0);

scanner.close();
}
}

9
4.WAP in java to demonstrate the use of method overloading:Overloaded Method: area(),
area(int) for square, area(int,int) for rectangle, area(int,int,int) for triangle, area(double) for circle,
area(int,int,int,int) for straight line (i.e. calculate length of straight in this case)
Ans import java.util.Scanner;
public class MethodOverloadingDemo {
public double area() {
return 0; }
public double area(int side) {
return side * side; // Area of a square
}
public double area(int length, int width) {
return length * width; // Area of a rectangle }
public double area(int base, int height, int side) {
return 0.5 * base * height; // Area of a triangle
}
public double area(double radius) {
return Math.PI * radius * radius; // Area of a circle
}
public double area(int x1, int y1, int x2, int y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); // Length of a straight line
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
MethodOverloadingDemo demo = new MethodOverloadingDemo();
System.out.println("Choose an option:");
System.out.println("1. Area of a Square");
System.out.println("2. Area of a Rectangle");
System.out.println("3. Area of a Triangle");
System.out.println("4. Area of a Circle");
System.out.println("5. Length of a Straight Line");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the side length of the square: ");
int side = scanner.nextInt();
System.out.println("Area of the square: " + demo.area(side));

10
break;
case 2:
System.out.print("Enter the length of the rectangle: ");
int length = scanner.nextInt();
System.out.print("Enter the width of the rectangle: ");
int width = scanner.nextInt();
System.out.println("Area of the rectangle: " + demo.area(length, width));
break;
case 3:
System.out.print("Enter the base of the triangle: ");
int base = scanner.nextInt();
System.out.print("Enter the height of the triangle: ");
int height = scanner.nextInt();
System.out.println("Area of the triangle: " + demo.area(base, height, 0));
break;
case 4:
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
System.out.println("Area of the circle: " + demo.area(radius));
break;
case 5:
System.out.print("Enter the coordinates of the first point (x1, y1): ");
int x1 = scanner.nextInt();
int y1 = scanner.nextInt();
System.out.print("Enter the coordinates of the second point (x2, y2): ");
int x2 = scanner.nextInt();
int y2 = scanner.nextInt();
System.out.println("Length of the straight line: " + demo.area(x1, y1, x2, y2));
break;
default:
System.out.println("Invalid choice.");
Break: }
scanner.close();
}
}

11
12
5.Demonstrate the concept for the following operation.
a. Stopping Overriding with Final
b. Stopping Inheritance with Final
c. Creating Constant with Final

a. Stopping Overriding with Final

class Parent {
public final void display() {
System.out.println("This method cannot be overridden.");
}
}

class Child extends Parent {


// This will result in a compilation error
// because you cannot override a final method.
// public void display() {
// System.out.println("Child class");
// }
}

public class Main {


public static void main(String[] args) {
Parent parent = new Parent();
parent.display();
}
}

13
b. Stopping Inheritance with Final

final class FinalClass {


public void display() {
System.out.println("This is a final class.");
}
}

c. Creating Constant with Final


kk
public class ConstantsDemo { j
public static final double PI = 3.14159265359;

public static final int MAX_VALUE = 100;

public static void main(String[] args) {

System.out.println("Value of PI: " + PI);

System.out.println("Max Value: " + MAX_VALUE);

14
6. Write a Java program to implement single inheritance.
// Define the superclass (parent class)
class Animal {
void eat() {
System.out.println("The animal is eating.");
}

void sleep() {
System.out.println("The animal is sleeping.");
}
}

// Define the subclass (child class) that extends the superclass


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

public class SingleInheritanceDemo {


public static void main(String[] args) {
// Create an instance of the Dog class
Dog myDog = new Dog();

// Call methods from the superclass


myDog.eat();
myDog.sleep();

// Call methods from the subclass


myDog.bark();
}
}

15
7. Write a Java program to implement multilevel inheritance.
// Define the first (base) class
class Animal {
void eat() {
System.out.println("The animal is eating.");
}
}

// Define the second class that extends the first class


class Dog extends Animal {
void bark() {
System.out.println("The dog is barking.");
}
}
// Define the third class that extends the second class
class Bulldog extends Dog {
void display() {
System.out.println("The Bulldog is a type of dog.");
}
}
public class MultilevelInheritanceDemo {
public static void main(String[] args) {
// Create an instance of the Bulldog class
Bulldog myBulldog = new Bulldog();

// Call methods from the first class


myBulldog.eat();

// Call methods from the second class


myBulldog.bark();

// Call methods from the third class


myBulldog.display();
}
}

16
7. Output Window of multilevel inheritance

8. Output Window of hierarchical inheritance

9,10.Output Window of to implementing static binding.+ dynamic binding

11.Output Window of implementing abstract class.

17
8.Write a Java program to implement hierarchical inheritance.
// Define the base class
class Animal {
void eat() {
System.out.println("The animal is eating.");
}
}
// Define the first subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog is barking.");
}
}
class Cat extends Animal {
void meow() {
System.out.println("The cat is meowing.");
}
}
public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
// Create an instance of the Dog class
Dog myDog = new Dog();

// Create an instance of the Cat class


Cat myCat = new Cat();

// Call methods from the base class


myDog.eat();
myCat.eat();

// Call methods from the respective subclasses


myDog.bark();
myCat.meow();
}
}

18
9.Write a Java program to implement static binding.
class Animal {
void sound() {
System.out.println("This is an animal.");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("The dog barks.");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("The cat meows.");
}
}

public class StaticBindingDemo {


public static void main(String[] args) {
Animal animal1 = new Animal();
Animal animal2 = new Dog();
Animal animal3 = new Cat();

animal1.sound(); // Calls the sound() method of Animal


animal2.sound(); // Calls the sound() method of Dog
animal3.sound(); // Calls the sound() method of Cat
}
}

19
10.Write a Java program to implement dynamic binding.
class Animal {
void sound() {
System.out.println("This is an animal.");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("The dog barks.");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("The cat meows.");
}
}

public class DynamicBindingDemo {


public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();

animal1.sound(); // Calls the sound() method of Dog


animal2.sound(); // Calls the sound() method of Cat
}
}

20
11.Write a Java program to implement abstract class.
import java.util.Scanner;

// Define an abstract class


abstract class Shape {
abstract void draw(); // Abstract method (no implementation)
abstract double area(); // Abstract method (no implementation)
}

// Define a concrete subclass of Shape


class Circle extends Shape {
private double radius;

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

@Override
void draw() {
System.out.println("Drawing a circle");
}

@Override
double area() {
return Math.PI * radius * radius;
}
}

// Define another concrete subclass of Shape


class Rectangle extends Shape {
private double length;
private double width;

Rectangle(double length, double width) {


this.length = length;

21
this.width = width;
}

@Override
void draw() {
System.out.println("Drawing a rectangle");
}

@Override
double area() {
return length * width;
}
}

public class AbstractClassDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the radius of the circle: ");


double circleRadius = scanner.nextDouble();
Circle circle = new Circle(circleRadius);

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


double rectangleLength = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double rectangleWidth = scanner.nextDouble();
Rectangle rectangle = new Rectangle(rectangleLength, rectangleWidth);
scanner.close();
circle.draw();
System.out.println("Circle Area: " + circle.area());
rectangle.draw();
System.out.println("Rectangle Area: " + rectangle.area());
}
}

22
12.Demonstrate the use of super keyword.
class Animal {
String name;

Animal(String name) {
this.name = name;
}
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
String breed;
Dog(String name, String breed) {
super(name); // Call superclass constructor
this.breed = breed;
}
@Override
void sound() {
super.sound(); // Call superclass method
System.out.println("The dog barks.");
}
void display() {
System.out.println("Name: " + name);
System.out.println("Breed: " + breed);
}
}
public class SuperKeywordDemo {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy", "Golden Retriever");

myDog.display();
myDog.sound();
}
}

23
12..Demonstration the use of super keyword.

13.Implemention of Dynamic method dispatch using Abstract class.

24
13.Implement Dynamic method dispatch using Abstract class.
abstract class Animal {
abstract void makeSound(); // Abstract method to be overridden by subclasses
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("The dog barks.");
}
}

class Cat extends Animal {


@Override
void makeSound() {
System.out.println("The cat meows.");
}
}

public class DynamicMethodDispatchDemo {


public static void main(String[] args) {
Animal myAnimal;

myAnimal = new Dog();


myAnimal.makeSound(); // Calls Dog's makeSound method

myAnimal = new Cat();


myAnimal.makeSound(); // Calls Cat's makeSound method
}
}

25
14.Create an abstract class Shape with methods calc_area and calc_volume. Derive
three classes Sphere (radius), Cone (radius, height) and Cylinder (radius,
height), Box (length, breadth, height) from it. Calculate area and volume of all.
(Use Method overriding).
import java.util.Scanner;

abstract class Shape {


abstract double calc_area();
abstract double calc_volume();
}

class Sphere extends Shape {


private double radius;

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

@Override
double calc_area() {
return 4 * Math.PI * Math.pow(radius, 2);
}

@Override
double calc_volume() {
return (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
}
}

class Cone extends Shape {


private double radius;
private double height;

Cone(double radius, double height) {


this.radius = radius;
this.height = height;
}

@Override
double calc_area() {
double slantHeight = Math.sqrt(Math.pow(radius, 2) + Math.pow(height, 2));
return Math.PI * radius * (radius + slantHeight);
}

@Override
double calc_volume() {
return (1.0 / 3.0) * Math.PI * Math.pow(radius, 2) * height;
}
}

class Cylinder extends Shape {


private double radius;
private double height;

26
Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}

@Override
double calc_area() {
return 2 * Math.PI * radius * (radius + height);
}

@Override
double calc_volume() {
return Math.PI * Math.pow(radius, 2) * height;
}
}

class Box extends Shape {


private double length;
private double breadth;
private double height;

Box(double length, double breadth, double height) {


this.length = length;
this.breadth = breadth;
this.height = height;
}

@Override
double calc_area() {
return 2 * (length * breadth + breadth * height + height * length);
}

@Override
double calc_volume() {
return length * breadth * height;
}
}

public class ShapeDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Select a shape:");
System.out.println("1. Sphere");
System.out.println("2. Cone");
System.out.println("3. Cylinder");
System.out.println("4. Box");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();

double radius, height, length, breadth;

switch (choice) {
case 1:
System.out.print("Enter the radius of the sphere: ");
radius = scanner.nextDouble();

27
Sphere sphere = new Sphere(radius);
System.out.println("Sphere Area: " + sphere.calc_area());
System.out.println("Sphere Volume: " + sphere.calc_volume());
break;

case 2:
System.out.print("Enter the radius of the cone: ");
radius = scanner.nextDouble();
System.out.print("Enter the height of the cone: ");
height = scanner.nextDouble();
Cone cone = new Cone(radius, height);
System.out.println("Cone Area: " + cone.calc_area());
System.out.println("Cone Volume: " + cone.calc_volume());
break;

case 3:
System.out.print("Enter the radius of the cylinder: ");
radius = scanner.nextDouble();
System.out.print("Enter the height of the cylinder: ");
height = scanner.nextDouble();
Cylinder cylinder = new Cylinder(radius, height);
System.out.println("Cylinder Area: " + cylinder.calc_area());
System.out.println("Cylinder Volume: " + cylinder.calc_volume());
break;

case 4:
System.out.print("Enter the length of the box: ");
length = scanner.nextDouble();
System.out.print("Enter the breadth of the box: ");
breadth = scanner.nextDouble();
System.out.print("Enter the height of the box: ");
height = scanner.nextDouble();
Box box = new Box(length, breadth, height);
System.out.println("Box Area: " + box.calc_area());
System.out.println("Box Volume: " + box.calc_volume());
break;

default:
System.out.println("Invalid choice.");
}

scanner.close();
}
}

28
15.Implement a class having private variables and methods. Demonstrate how to use those
variables and methods by objects.
class PrivateDemo {
private int privateVar; // Private instance variable

// Private instance method


private void privateMethod() {
System.out.println("This is a private method.");
}

public void setPrivateVar(int value) {


privateVar = value;
}

public int getPrivateVar() {


return privateVar;
}

// Public method to access the private method


public void accessPrivateMethod() {
privateMethod();
}
}

public class PrivateVariablesAndMethodsDemo {


public static void main(String[] args) {
PrivateDemo obj = new PrivateDemo();

// Setting the private variable using a public method


obj.setPrivateVar(42);

// Getting the private variable using a public method


int value = obj.getPrivateVar();
System.out.println("PrivateVar: " + value);

// Accessing the private method using a public method


obj.accessPrivateMethod();
}
}

29
16.Implement use of static variables and methods in a class.
class MyClass {
// Static variable shared by all instances of the class
static int staticVar = 0;
int instanceVar;

MyClass(int instanceVar) {
this.instanceVar = instanceVar;
}

// Static method
static void staticMethod() {
System.out.println("This is a static method.");
}

void instanceMethod() {
System.out.println("This is an instance method.");
}
}

public class StaticVariablesAndMethodsDemo {


public static void main(String[] args) {
// Create instances of MyClass
MyClass obj1 = new MyClass(1);
MyClass obj2 = new MyClass(2);

// Access instance variables


System.out.println("obj1.instanceVar: " + obj1.instanceVar);
System.out.println("obj2.instanceVar: " + obj2.instanceVar);

// Access and modify the static variable


System.out.println("MyClass.staticVar: " + MyClass.staticVar);
MyClass.staticVar = 42;
System.out.println("MyClass.staticVar (modified): " + MyClass.staticVar);

// Call static method


MyClass.staticMethod();

// Call instance method


obj1.instanceMethod();
obj2.instanceMethod();
}
}

30
17. Perform method overloading with basic example.Give output also

public class Calculator {


public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public String add(String a, String b) {


return a + b;
}

public static void main(String[] args) {


Calculator calculator = new Calculator();

int result1 = calculator.add(5, 10);


System.out.println("Result (int): " + result1);

double result2 = calculator.add(3.5, 2.5);


System.out.println("Result (double): " + result2);

String result3 = calculator.add("Hello, ", "World!");


System.out.println("Result (String): " + result3);
}
}

18. Implement use of static variables and methods in a class.


class MathOperations {
// Static variable
static int totalOperations = 0;

// Static method to add two numbers


static int add(int a, int b) {
totalOperations++;
return a + b;
}

// Static method to subtract two numbers


static int subtract(int a, int b) {
totalOperations++;
return a - b;
}
}

public class Main {


public static void main(String[] args) {
int result1 = MathOperations.add(10, 5);
System.out.println("Addition Result: " + result1);

31
int result2 = MathOperations.subtract(10, 5);
System.out.println("Subtraction Result: " + result2);

int result3 = MathOperations.add(20, 15);


System.out.println("Addition Result: " + result3);

System.out.println("Total Operations: " + MathOperations.totalOperations);


}
}

19. Perform constructor overloading with basic example.


Perform method overloading with basic example.Give output also

public class Calculator {


public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public String add(String a, String b) {


return a + b;
}

public static void main(String[] args) {


Calculator calculator = new Calculator();

int result1 = calculator.add(5, 10);


System.out.println("Result (int): " + result1);

double result2 = calculator.add(3.5, 2.5);


System.out.println("Result (double): " + result2);

String result3 = calculator.add("Hello, ", "World!");


System.out.println("Result (String): " + result3);
}
}

32
20.Write a Java program to accepts an integer and count the factors of the number. import
java.util.Scanner;

public class FactorCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = scanner.nextInt();

int count = countFactors(number);

System.out.println("The number of factors of " + number + " is: " + count);

scanner.close();
}

public static int countFactors(int number) {


int count = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
count++;
}
}
return count;
}
}

33

You might also like