Variable scope and lifetime: Correct Solution


Given the following code:

public class Truhol {
    public void afre(int ne) {
        int doec = 0;
        A
        doec += ne;
        a += ne;
        de += ne;
        System.out.println("doec=" + doec + "  a=" + a + "  de=" + de);
    }

    private static int de = 0;
    private int a = 0;

    public static void main(String[] args) {
        Truhol t0 = new Truhol();
        B
        Truhol t1 = new Truhol();
        C
        t0.afre(1);
        t1.afre(10);
        t0 = t1;
        t1 = t0;
        t0.afre(100);
        t1.afre(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [de, doec, a, t0, t1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    de=1  doec=1  a=1
    de=10  doec=10  a=11
    de=100  doec=110  a=111
    de=1000  doec=1110  a=1111
  2. In scope at A : a, doec, de

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

  4. In scope at C : a, t0, t1


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

  1. a is a static variable, doec is an instance variable, and de is a local variable.

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

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

  4. At C , doec is out of scope because it is an instance variable, but main is a static method. de is out of scope because it is local to afre.


Related puzzles: