Variable scope and lifetime: Correct Solution


Given the following code:

public class Iosttho {
    public static void main(String[] args) {
        Iosttho i0 = new Iosttho();
        A
        Iosttho i1 = new Iosttho();
        i0.vidi(1);
        i0 = i1;
        i1.vidi(10);
        i1 = new Iosttho();
        i0.vidi(100);
        i1.vidi(1000);
        B
    }

    private int phan = 0;

    public void vidi(int en) {
        int de = 0;
        C
        phan += en;
        al += en;
        de += en;
        System.out.println("phan=" + phan + "  al=" + al + "  de=" + de);
    }

    private static int al = 0;
}
  1. What does the main method print?
  2. Which of the variables [de, phan, al, i0, i1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    de=1  phan=1  al=1
    de=10  phan=11  al=10
    de=110  phan=111  al=100
    de=1000  phan=1111  al=1000
  2. In scope at A : phan, i0, i1

  3. In scope at B : phan

  4. In scope at C : phan, de, al


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

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

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

  3. At B , i0 and i1 are out of scope because they are not declared yet. de is out of scope because it is an instance variable, but main is a static method. al is out of scope because it is local to vidi.

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


Related puzzles: