Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int apme = 0;

    public void stewec(int mi) {
        int o = 0;
        apme += mi;
        o += mi;
        de += mi;
        System.out.println("apme=" + apme + "  o=" + o + "  de=" + de);
        C
    }

    private int de = 0;
}
  1. What does the main method print?
  2. Which of the variables [de, apme, o, 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  apme=1  o=1
    de=11  apme=10  o=11
    de=111  apme=100  o=100
    de=1111  apme=1000  o=1011
  2. In scope at A : de, i0

  3. In scope at B : de, i0, i1

  4. In scope at C : de, o


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

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

  2. At A , i1 is out of scope because it is not declared yet. o is out of scope because it is an instance variable, but main is a static method. apme is out of scope because it is local to stewec.

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

  4. At C , apme is out of scope because it is not declared yet. i0 and i1 out of scope because they are local to the main method.


Related puzzles: