Post

Created by @nathanedwards
 at October 31st 2023, 5:17:15 pm.

AP Computer Science Exam Question

// Given the following code snippet:

public class VariableScope {
    public static void main(String[] args) {
        int x = 5;
        int y = 10;
        int z = 15;

        if (x < 10) {
            int y = 20;
            z = 25;
            System.out.println("Inside if block: x = " + x + ", y = " + y + ", z = " + z);
        }

        System.out.println("Outside if block: x = " + x + ", y = " + y + ", z = " + z);
    }
}

What is the output of the above code?

A. Inside if block: x = 5, y = 20, z = 25 Outside if block: x = 5, y = 10, z = 25

B. Inside if block: x = 5, y = 10, z = 25 Outside if block: x = 5, y = 10, z = 25

C. Inside if block: x = 5, y = 20, z = 15 Outside if block: x = 5, y = 10, z = 25

D. Inside if block: x = 5, y = 20, z = 25 Outside if block: x = 5, y = 10, z = 15

Choose the correct option (A, B, C, or D) and provide the reason behind your choice.


Answer

The correct option is C. Inside if block: x = 5, y = 20, z = 15 Outside if block: x = 5, y = 10, z = 25

Explanation:

  • The variable x is declared and initialized with the value 5 in the main method.
  • The variable y is declared and initialized with the value 10 in the main method.
  • The variable z is declared and initialized with the value 15 in the main method.
  • Inside the if block, another variable y is declared and initialized with the value 20. This y variable is local to the if block and has a different scope than the y variable declared in the main method.
  • Inside the if block, the value of z is changed to 25.
  • The System.out.println statement inside the if block will print the values of x, y, and z based on their current values, which are 5, 20, and 25, respectively.
  • Outside the if block, the System.out.println statement will print the values of x, y, and z based on their current values, which are unchanged from their initial values (5, 10, and 15, respectively).
  • Therefore, the output will be:
    Inside if block: x = 5, y = 20, z = 15
    Outside if block: x = 5, y = 10, z = 25