Post

Created by @nathanedwards
 at October 31st 2023, 4:07:01 pm.

AP Computer Science Exam Question

Variables and Constants

Question:

Consider the following Java code snippet:

public class VariablesExample {
    public static void main(String[] args) {
        final int NUMBER_OF_STUDENTS = 30;
        int numberOfBoys = 20;
        int numberOfGirls = NUMBER_OF_STUDENTS - numberOfBoys;
        
        System.out.println("Number of Boys: " + numberOfBoys);
        System.out.println("Number of Girls: " + numberOfGirls);
    }
}

What will be the output when the above code snippet is executed?

A) Number of Boys: 30 Number of Girls: 20

B) Number of Boys: 20 Number of Girls: 10

C) Number of Boys: 20 Number of Girls: 30

D) Number of Boys: 10 Number of Girls: 20

Explain your answer.

Answer:

The correct answer is B) Number of Boys: 20, Number of Girls: 10.

Explanation:

  1. The final int NUMBER_OF_STUDENTS = 30; declaration sets a constant value of 30 to the variable NUMBER_OF_STUDENTS. The final keyword makes it a constant, which means its value cannot be changed later.
  2. The int numberOfBoys = 20; declaration initializes the variable numberOfBoys with a value of 20.
  3. The expression numberOfGirls = NUMBER_OF_STUDENTS - numberOfBoys; subtracts the value of numberOfBoys (20) from the constant NUMBER_OF_STUDENTS (30) and assigns the result (10) to the variable numberOfGirls.
  4. The System.out.println() statements print the values of numberOfBoys and numberOfGirls to the console, separated by the concatenation operator (+).

Therefore, when the code is executed, it will print:

Number of Boys: 20
Number of Girls: 10

Option B is the correct answer.