Variable scope and lifetime: Correct Solution


Given the following code:

public class Wria {
    public static void main(String[] args) {
        A
        Wria w0 = new Wria();
        Wria w1 = new Wria();
        B
        w0.tetAssud(1);
        w1.tetAssud(10);
        w0 = w1;
        w1 = new Wria();
        w0.tetAssud(100);
        w1.tetAssud(1000);
    }

    private int pel = 0;
    private static int es = 0;

    public void tetAssud(int a) {
        C
        int cin = 0;
        cin += a;
        es += a;
        pel += a;
        System.out.println("cin=" + cin + "  es=" + es + "  pel=" + pel);
    }
}
  1. What does the main method print?
  2. Which of the variables [pel, cin, es, w0, w1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    pel=1  cin=1  es=1
    pel=10  cin=11  es=10
    pel=100  cin=111  es=110
    pel=1000  cin=1111  es=1000
  2. In scope at A : cin, w0

  3. In scope at B : cin, w0, w1

  4. In scope at C : cin, es, pel


Explanation (which you do not need to write out in your submitted solution):

  1. cin is a static variable, es is an instance variable, and pel is a local variable.

  2. At A , w1 is out of scope because it is not declared yet. es is out of scope because it is an instance variable, but main is a static method. pel is out of scope because it is local to tetAssud.

  3. At B , es is out of scope because it is an instance variable, but main is a static method. pel is out of scope because it is local to tetAssud.

  4. At C , w0 and w1 out of scope because they are local to the main method.


Related puzzles: