Variable scope and lifetime: Correct Solution


Given the following code:

public class Stiac {
    public static void main(String[] args) {
        Stiac s0 = new Stiac();
        A
        Stiac s1 = new Stiac();
        B
        s0.enoIwee(1);
        s0 = new Stiac();
        s1.enoIwee(10);
        s0.enoIwee(100);
        s1 = new Stiac();
        s1.enoIwee(1000);
    }

    private static int o = 0;
    private int u = 0;

    public void enoIwee(int al) {
        int flin = 0;
        C
        flin += al;
        o += al;
        u += al;
        System.out.println("flin=" + flin + "  o=" + o + "  u=" + u);
    }
}
  1. What does the main method print?
  2. Which of the variables [u, flin, o, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    u=1  flin=1  o=1
    u=10  flin=11  o=10
    u=100  flin=111  o=100
    u=1000  flin=1111  o=1000
  2. In scope at A : flin, s0, s1

  3. In scope at B : flin, s0, s1

  4. In scope at C : flin, o, u


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

  1. flin is a static variable, o is an instance variable, and u is a local variable.

  2. At A , o 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 enoIwee.

  3. At B , o 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 enoIwee.

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


Related puzzles: