Post

Created by @nathanedwards
 at November 3rd 2023, 5:58:58 pm.

AP Computer Science Exam Question

You are given the following code snippet:

public class Calculator {
    private int result;

    public Calculator() {
        result = 0;
    }

    public int add(int num1, int num2) {
        return num1 + num2;
    }

    public int multiply(int num1, int num2) {
        return num1 * num2;
    }

    public int subtract(int num1, int num2) {
        return num1 - num2;
    }

    public void printResult() {
        System.out.println("Result: " + result);
    }

    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        int sum = calculator.add(5, 3);
        int product = calculator.multiply(sum, 2);
        calculator.printResult();
    }
}
  1. Explain the purpose of the Calculator class in the given code snippet.

  2. What is the purpose of the constructor public Calculator() in the Calculator class?

  3. Explain the purpose of the add, multiply, and subtract methods in the Calculator class.

  4. What is the significance of the printResult() method in the Calculator class?

  5. Identify the output of the code when executed.

Answer

  1. The purpose of the Calculator class in the given code snippet is to perform basic arithmetic operations such as addition, multiplication, and subtraction.

  2. The constructor public Calculator() in the Calculator class is used to initialize the result variable, which holds the final result of the calculations. By default, it sets the result to 0.

    • The add method takes two integers as input (num1 and num2) and returns their sum by using the + operator.
    • The multiply method takes two integers as input (num1 and num2) and returns their product by using the * operator.
    • The subtract method takes two integers as input (num1 and num2) and returns their difference by using the - operator.
  3. The printResult() method is significant because it prints the current value of the result variable to the console. It allows the user to see the final result of the calculations performed by the Calculator.

  4. The output of the code when executed will be:

Result: 16

Explanation:

  • The main method creates an instance of the Calculator class using the new keyword.
  • It then calls the add method on the calculator instance, passing 5 and 3 as arguments. The add method returns 8.
  • The returned value of 8 is stored in the sum variable.
  • The multiply method is then called on the calculator instance, passing the sum (8) and 2 as arguments. The multiply method returns 16.
  • Finally, the printResult method is called, which prints Result: 16 to the console.