Assignment: Module 02 - Part 02
02. Create a class named “Calculator” having two variables “a” and “b” with a value 3 and 5 respectively.Assignment: Module 02 - Part 02
Create an object for the class and display the results of addition, subtraction, multiplication and division operations.
For an example :
Input : a=3 b=5
Expected output :
Addition: 8
Subtraction: -2 or 2
Multiplication: 15
Division: 0.6
Code:
class Calculator {
int a = 3;
int b = 5;
public int addition() {
return a + b;
}
public int subtraction() {
return a - b;
}
public int multiplication() {
return a * b;
}
public double division() {
return (double) a / b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Addition: " + calc.addition());
System.out.println("Subtraction: " + calc.subtraction());
System.out.println("Multiplication: " + calc.multiplication());
System.out.println("Division: " + calc.division());
}
}
Output:Copy code
Addition: 8
Subtraction: -2
Multiplication: 15
Division: 0.6
Note: In the above code, I have defined methods addition(), subtraction(), multiplication() and division() inside the class Calculator which perform the respective operations and return the result. And then I have created an object of the class and used those methods to get the results.