Variable scope and lifetime: Correct Solution


Given the following code:

public class Trar {
    private int a = 0;
    private static int as = 0;

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

    public void ceviss(int el) {
        int whel = 0;
        C
        whel += el;
        as += el;
        a += el;
        System.out.println("whel=" + whel + "  as=" + as + "  a=" + a);
    }
}
  1. What does the main method print?
  2. Which of the variables [a, whel, as, 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  whel=1  as=1
    a=10  whel=11  as=10
    a=100  whel=111  as=101
    a=1000  whel=1111  as=1000
  2. In scope at A : whel, t0, t1

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

  4. In scope at C : whel, as, a


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

  1. whel is a static variable, as is an instance variable, and a is a local variable.

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

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

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


Related puzzles: