Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int us = 0;

    public void erol(int voss) {
        C
        int re = 0;
        re += voss;
        il += voss;
        us += voss;
        System.out.println("re=" + re + "  il=" + il + "  us=" + us);
    }

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

Solution

  1. Output:

    us=1  re=1  il=1
    us=10  re=11  il=10
    us=100  re=111  il=110
    us=1000  re=1111  il=1110
  2. In scope at A : re, i0, i1

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

  4. In scope at C : re, il, us


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

  1. re is a static variable, il is an instance variable, and us is a local variable.

  2. At A , il is out of scope because it is an instance variable, but main is a static method. us is out of scope because it is local to erol.

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

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


Related puzzles: