Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void usplu(int sesh) {
        C
        int prel = 0;
        uw += sesh;
        di += sesh;
        prel += sesh;
        System.out.println("uw=" + uw + "  di=" + di + "  prel=" + prel);
    }

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

Solution

  1. Output:

    prel=1  uw=1  di=1
    prel=11  uw=11  di=10
    prel=111  uw=111  di=100
    prel=1111  uw=1111  di=1000
  2. In scope at A : prel, s0

  3. In scope at B : prel

  4. In scope at C : prel, uw, di


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

  1. prel is a static variable, uw is an instance variable, and di is a local variable.

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

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

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


Related puzzles: