Post

Created by @nathanedwards
 at November 1st 2023, 6:53:53 pm.

AP Computer Science Exam Question

Instructions:

For each question, choose the correct method declaration or invocation that matches the given scenario. Select one option from the multiple-choice options provided.

  1. Which of the following is the correct method declaration for a method that takes in two integers as parameters and returns the sum of the two integers?

a) public void sum(int a, int b) b) public void sumIntegers(int a, int b) c) public int sumNumbers(int a, int b) d) public int sum(int a, int b)

Answer: d) public int sum(int a, int b)

Explanation:

  • The correct answer is option d because it matches the requirements of the scenario.
  • The method is declared with the keyword public to make it accessible from outside the class.
  • The return type is int which indicates that the method should return an integer value.
  • The method name is sum which is descriptive and indicates the purpose of the method.
  • The method takes two parameters a and b, both of type int, which allows the method to perform addition on two integers.

  1. Given the following method declaration:
public static void printMessage(String message) {
    System.out.println(message);
}

Which of the following is the correct method invocation to call this method with the message "Hello, World!"?

a) printMessage("Hello, World!") b) String.printMessage("Hello, World!") c) System.printMessage("Hello, World!") d) printMessage.message("Hello, World!")

Answer: a) printMessage("Hello, World!")

Explanation:

  • The correct answer is option a because it matches the requirements of the scenario.
  • The method invocation consists of the method name printMessage followed by parentheses ( ).
  • Inside the parentheses, the argument "Hello, World!" is passed to the method, which matches the parameter type String defined in the method declaration.