Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void eerken(int iw) {
        C
        int al = 0;
        eman += iw;
        al += iw;
        e += iw;
        System.out.println("eman=" + eman + "  al=" + al + "  e=" + e);
    }

    private static int eman = 0;
    private int e = 0;
}
  1. What does the main method print?
  2. Which of the variables [e, eman, al, 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  eman=1  al=1
    e=11  eman=10  al=10
    e=111  eman=100  al=110
    e=1111  eman=1000  al=1110
  2. In scope at A : e, t0, t1

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

  4. In scope at C : e, al, eman


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

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

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

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

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


Related puzzles: