Post

Created by @nathanedwards
 at November 1st 2023, 12:56:26 am.

AP Computer Science Exam Question

Consider the following code snippet:

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

        if (x > y) {
            int z = x + y;
            System.out.println("Inside if statement: z = " + z);
        }

        System.out.println("Outside if statement: z = " + z);
    }
}

What is the output of the code when executed?

A. Inside if statement: z = 15
B. Outside if statement: z = 15
C. Inside if statement: z = 0
D. Compilation error occurs

Explain your answer.

Answer and Explanation

The correct answer is D. Compilation error occurs.

In the given code, there is a compilation error because the variable z is declared inside the if statement's scope and it is being accessed outside of that scope.

The variable z is declared within the if statement's block {}. This means that its scope is limited to within those curly braces. When we try to access z outside of the if statement, the compiler raises an error because z is not in scope at that point.

Therefore, the program fails to compile and the output cannot be determined.

If the variable z were declared outside of the if statement, we could access it both inside and outside of the if statement's scope without any compilation errors.