Post

Created by @nathanedwards
 at November 1st 2023, 6:29:03 am.

AP Computer Science Exam Question

Consider the following Java code:

public class VariableScope {
    
    public static void main(String[] args) {
        int a = 5;
        int b = 10;
        
        if (a > 3) {
            int c = a + b;
            System.out.println(c);
        }
        
        int d = a + b;
        System.out.println(d);
        
        for (int i = 0; i < 3; i++) {
            int e = i * 2;
            System.out.println(e);
        }
        
        System.out.println(e);
    }
}

Question:

What will be the output of the above code? Explain the scope and lifetime of each variable used in the code.

Answer:

The output of the above code will be:

15
15
0
2
4
Exception in thread "main" java: cannot find symbol
  symbol:   variable e
  location: class VariableScope

Explanation of the scope and lifetime of each variable used in the code:

  • a and b are declared and initialized within the main method, and their scope is limited to the main method. Their lifetime begins when the code execution enters the main method and ends when that method returns.

  • c is declared within the if block and initialized with the sum of a and b. Its scope is limited to that if block, and its lifetime is as long as the if block is being executed. Once the if block ends, the variable c cannot be accessed anymore.

  • d is declared within the main method, right after the if block. Its scope is limited to the main method, and its lifetime begins when it is declared and ends when the method returns. d is assigned the sum of a and b, and its value is printed after the if block execution.

  • i is declared within the for loop initialization statement. Its scope is limited to that for loop, and its lifetime is as long as the loop is being executed. Once the loop ends, the variable i cannot be accessed anymore.

  • e is also declared within the for loop, within the iteration body. Its scope is limited to that iteration body, and its lifetime is as long as that iteration is being executed. Once an iteration ends, the variable e cannot be accessed anymore. In the last line System.out.println(e), a cannot find symbol error is thrown because e is not accessible outside the for loop.