Variable scope and lifetime: Correct Solution


Given the following code:

public class Irem {
    private int a = 0;
    private static int ces = 0;

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

    public void mios(int ar) {
        int o = 0;
        C
        a += ar;
        ces += ar;
        o += ar;
        System.out.println("a=" + a + "  ces=" + ces + "  o=" + o);
    }
}
  1. What does the main method print?
  2. Which of the variables [o, a, ces, i0, i1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    o=1  a=1  ces=1
    o=11  a=11  ces=10
    o=111  a=111  ces=100
    o=1111  a=1111  ces=1000
  2. In scope at A : a, i0

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

  4. In scope at C : a, o, ces


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

  1. a is a static variable, o is an instance variable, and ces 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. ces is out of scope because it is local to mios.

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

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


Related puzzles: