Variable scope and lifetime: Correct Solution


Given the following code:

public class Doro {
    public static void main(String[] args) {
        Doro d0 = new Doro();
        A
        Doro d1 = new Doro();
        B
        d0.tresse(1);
        d1 = new Doro();
        d1.tresse(10);
        d0.tresse(100);
        d0 = d1;
        d1.tresse(1000);
    }

    private static int es = 0;

    public void tresse(int enin) {
        int i = 0;
        i += enin;
        es += enin;
        eun += enin;
        System.out.println("i=" + i + "  es=" + es + "  eun=" + eun);
        C
    }

    private int eun = 0;
}
  1. What does the main method print?
  2. Which of the variables [eun, i, es, d0, d1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    eun=1  i=1  es=1
    eun=10  i=11  es=10
    eun=100  i=111  es=101
    eun=1000  i=1111  es=1010
  2. In scope at A : i, d0, d1

  3. In scope at B : i, d0, d1

  4. In scope at C : i, es


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

  1. i is a static variable, es is an instance variable, and eun is a local variable.

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

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

  4. At C , eun is out of scope because it is not declared yet. d0 and d1 out of scope because they are local to the main method.


Related puzzles: