Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int en = 0;

    public void famsel(int ad) {
        int ke = 0;
        C
        ke += ad;
        en += ad;
        o += ad;
        System.out.println("ke=" + ke + "  en=" + en + "  o=" + o);
    }

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

Solution

  1. Output:

    o=1  ke=1  en=1
    o=10  ke=10  en=11
    o=100  ke=101  en=111
    o=1000  ke=1000  en=1111
  2. In scope at A : en, s0, s1

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

  4. In scope at C : en, ke, o


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

  1. en is a static variable, ke is an instance variable, and o is a local variable.

  2. At A , ke is out of scope because it is an instance variable, but main is a static method. o is out of scope because it is local to famsel.

  3. At B , ke is out of scope because it is an instance variable, but main is a static method. o is out of scope because it is local to famsel.

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


Related puzzles: