Variable scope and lifetime: Correct Solution


Given the following code:

public class OstSplunlo {
    public void legean(int muc) {
        int me = 0;
        A
        ea += muc;
        u += muc;
        me += muc;
        System.out.println("ea=" + ea + "  u=" + u + "  me=" + me);
    }

    private static int u = 0;
    private int ea = 0;

    public static void main(String[] args) {
        OstSplunlo o0 = new OstSplunlo();
        B
        OstSplunlo o1 = new OstSplunlo();
        C
        o0.legean(1);
        o1 = o0;
        o1.legean(10);
        o0 = new OstSplunlo();
        o0.legean(100);
        o1.legean(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [me, ea, u, o0, o1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    me=1  ea=1  u=1
    me=11  ea=11  u=10
    me=100  ea=111  u=100
    me=1011  ea=1111  u=1000
  2. In scope at A : ea, me, u

  3. In scope at B : ea, o0, o1

  4. In scope at C : ea, o0, o1


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

  1. ea is a static variable, me is an instance variable, and u is a local variable.

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

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

  4. At C , me is out of scope because it is an instance variable, but main is a static method. u is out of scope because it is local to legean.


Related puzzles: