Variable scope and lifetime: Correct Solution


Given the following code:

public class Treswer {
    public static void main(String[] args) {
        Treswer t0 = new Treswer();
        A
        Treswer t1 = new Treswer();
        B
        t0.thil(1);
        t1 = t0;
        t1.thil(10);
        t0 = t1;
        t0.thil(100);
        t1.thil(1000);
    }

    public void thil(int be) {
        int a = 0;
        e += be;
        od += be;
        a += be;
        System.out.println("e=" + e + "  od=" + od + "  a=" + a);
        C
    }

    private int od = 0;
    private static int e = 0;
}
  1. What does the main method print?
  2. Which of the variables [a, e, od, t0, t1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    a=1  e=1  od=1
    a=11  e=11  od=10
    a=111  e=111  od=100
    a=1111  e=1111  od=1000
  2. In scope at A : a, t0, t1

  3. In scope at B : a, t0, t1

  4. In scope at C : a, e


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

  1. a is a static variable, e is an instance variable, and od is a local variable.

  2. At A , e is out of scope because it is an instance variable, but main is a static method. od is out of scope because it is local to thil.

  3. At B , e is out of scope because it is an instance variable, but main is a static method. od is out of scope because it is local to thil.

  4. At C , od is out of scope because it is not declared yet. t0 and t1 out of scope because they are local to the main method.


Related puzzles: