Variable scope and lifetime: Correct Solution


Given the following code:

public class Doank {
    private static int stic = 0;
    private int zon = 0;

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

    public void thesad(int ce) {
        C
        int ii = 0;
        stic += ce;
        ii += ce;
        zon += ce;
        System.out.println("stic=" + stic + "  ii=" + ii + "  zon=" + zon);
    }
}
  1. What does the main method print?
  2. Which of the variables [zon, stic, ii, d0, d1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    zon=1  stic=1  ii=1
    zon=11  stic=10  ii=10
    zon=111  stic=100  ii=101
    zon=1111  stic=1000  ii=1101
  2. In scope at A : zon, d0, d1

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

  4. In scope at C : zon, ii, stic


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

  1. zon is a static variable, ii is an instance variable, and stic is a local variable.

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

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

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


Related puzzles: