Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void ress(int rae) {
        int si = 0;
        si += rae;
        se += rae;
        swe += rae;
        System.out.println("si=" + si + "  se=" + se + "  swe=" + swe);
        C
    }

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

Solution

  1. Output:

    swe=1  si=1  se=1
    swe=10  si=11  se=10
    swe=100  si=111  se=101
    swe=1000  si=1111  se=1101
  2. In scope at A : si, s0

  3. In scope at B : si

  4. In scope at C : si, se


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

  1. si is a static variable, se is an instance variable, and swe is a local variable.

  2. At A , s1 is out of scope because it is not declared yet. se is out of scope because it is an instance variable, but main is a static method. swe is out of scope because it is local to ress.

  3. At B , s0 and s1 are out of scope because they are not declared yet. se is out of scope because it is an instance variable, but main is a static method. swe is out of scope because it is local to ress.

  4. At C , swe 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: