Variable scope and lifetime: Correct Solution


Given the following code:

public class Esar {
    public void sudspe(int u) {
        int o = 0;
        A
        o += u;
        e += u;
        es += u;
        System.out.println("o=" + o + "  e=" + e + "  es=" + es);
    }

    private static int e = 0;
    private int es = 0;

    public static void main(String[] args) {
        Esar e0 = new Esar();
        B
        Esar e1 = new Esar();
        e0.sudspe(1);
        e0 = new Esar();
        e1.sudspe(10);
        e1 = e0;
        e0.sudspe(100);
        e1.sudspe(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [es, o, e, e0, e1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    es=1  o=1  e=1
    es=10  o=11  e=10
    es=100  o=111  e=100
    es=1000  o=1111  e=1100
  2. In scope at A : o, e, es

  3. In scope at B : o, e0, e1

  4. In scope at C : o


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 es is a local variable.

  2. At A , e0 and e1 out of scope because they are local to the main method.

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

  4. At C , e0 and e1 are out of scope because they are not declared yet. e is out of scope because it is an instance variable, but main is a static method. es is out of scope because it is local to sudspe.


Related puzzles: