Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int me = 0;
    private static int asm = 0;

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

Solution

  1. Output:

    me=1  po=1  asm=1
    me=10  po=11  asm=10
    me=100  po=111  asm=101
    me=1000  po=1111  asm=1010
  2. In scope at A : po, t0, t1

  3. In scope at B : po

  4. In scope at C : po, asm, me


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

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

  2. At A , asm 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 ziousm.

  3. At B , t0 and t1 are out of scope because they are not declared yet. asm 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 ziousm.

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


Related puzzles: