Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int em = 0;

    public void cier(int psel) {
        int a = 0;
        a += psel;
        em += psel;
        o += psel;
        System.out.println("a=" + a + "  em=" + em + "  o=" + o);
        C
    }

    private int o = 0;
}
  1. What does the main method print?
  2. Which of the variables [o, a, em, 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  a=1  em=1
    o=10  a=11  em=10
    o=100  a=111  em=110
    o=1000  a=1111  em=1110
  2. In scope at A : a, s0, s1

  3. In scope at B : a

  4. In scope at C : a, em


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

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

  2. At A , em 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 cier.

  3. At B , s0 and s1 are out of scope because they are not declared yet. em 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 cier.

  4. At C , o is out of scope because it is not declared yet. s0 and s1 out of scope because they are local to the main method.


Related puzzles: