Post

Created by @nathanedwards
 at November 1st 2023, 1:43:34 pm.

AP Computer Science Exam Question

Create a Java method called calculateSum that takes in two integers as parameters and returns the sum of the two integers.

  1. Write the method declaration for the calculateSum method.
  2. Write the code to invoke the calculateSum method and print the result.

Answer

  1. Method Declaration:
public static int calculateSum(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}
  1. Method Invocation and Print Result:
public static void main(String[] args) {
    int result = calculateSum(5, 10);
    System.out.println("The sum is: " + result);
}

Explanation:

  1. Method Declaration:

    • The method name is calculateSum.
    • The return type is int, indicating that this method will return an integer value.
    • The method has two parameters, num1 and num2, both of type int.
    • Inside the method, the sum of num1 and num2 is calculated and stored in a variable called sum.
    • The sum value is returned as the output of the method.
  2. Method Invocation and Print Result:

    • In the main method, we invoke the calculateSum method by passing two integers, 5 and 10, as arguments.
    • The returned value from the calculateSum method is assigned to an int variable called result.
    • We then print the result using System.out.println(), concatenating the string "The sum is: " with the value of result.