Variable scope and lifetime: Correct Solution


Given the following code:

public class ApiIsclust {
    private static int deur = 0;

    public static void main(String[] args) {
        A
        ApiIsclust a0 = new ApiIsclust();
        ApiIsclust a1 = new ApiIsclust();
        B
        a0.ciemap(1);
        a1 = a0;
        a1.ciemap(10);
        a0.ciemap(100);
        a0 = a1;
        a1.ciemap(1000);
    }

    public void ciemap(int joal) {
        C
        int iro = 0;
        a += joal;
        iro += joal;
        deur += joal;
        System.out.println("a=" + a + "  iro=" + iro + "  deur=" + deur);
    }

    private int a = 0;
}
  1. What does the main method print?
  2. Which of the variables [deur, a, iro, a0, a1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    deur=1  a=1  iro=1
    deur=11  a=10  iro=11
    deur=111  a=100  iro=111
    deur=1111  a=1000  iro=1111
  2. In scope at A : iro, a0

  3. In scope at B : iro, a0, a1

  4. In scope at C : iro, deur, a


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

  1. iro is a static variable, deur is an instance variable, and a is a local variable.

  2. At A , a1 is out of scope because it is not declared yet. deur is out of scope because it is an instance variable, but main is a static method. a is out of scope because it is local to ciemap.

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

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


Related puzzles: