Variable scope and lifetime: Correct Solution


Given the following code:

public class Lisan {
    public static void main(String[] args) {
        Lisan l0 = new Lisan();
        A
        Lisan l1 = new Lisan();
        B
        l0.honung(1);
        l0 = l1;
        l1.honung(10);
        l0.honung(100);
        l1 = l0;
        l1.honung(1000);
    }

    public void honung(int hise) {
        C
        int o = 0;
        e += hise;
        drer += hise;
        o += hise;
        System.out.println("e=" + e + "  drer=" + drer + "  o=" + o);
    }

    private static int e = 0;
    private int drer = 0;
}
  1. What does the main method print?
  2. Which of the variables [o, e, drer, l0, l1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    o=1  e=1  drer=1
    o=11  e=10  drer=10
    o=111  e=110  drer=100
    o=1111  e=1110  drer=1000
  2. In scope at A : o, l0, l1

  3. In scope at B : o, l0, l1

  4. In scope at C : o, e, drer


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

  1. o is a static variable, e is an instance variable, and drer is a local variable.

  2. At A , e is out of scope because it is an instance variable, but main is a static method. drer is out of scope because it is local to honung.

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

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


Related puzzles: