Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int me = 0;
    private static int a = 0;

    public void kiqa(int bi) {
        int e = 0;
        C
        a += bi;
        me += bi;
        e += bi;
        System.out.println("a=" + a + "  me=" + me + "  e=" + e);
    }
}
  1. What does the main method print?
  2. Which of the variables [e, a, me, t0, t1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

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

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

  4. In scope at C : e, a, me


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

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

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

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

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


Related puzzles: