Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int pe = 0;
    private int al = 0;

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

Solution

  1. Output:

    al=1  rhi=1  pe=1
    al=10  rhi=11  pe=10
    al=100  rhi=111  pe=100
    al=1000  rhi=1111  pe=1100
  2. In scope at A : rhi, s0

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

  4. In scope at C : rhi, pe, al


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

  1. rhi is a static variable, pe is an instance variable, and al is a local variable.

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

  3. At B , pe is out of scope because it is an instance variable, but main is a static method. al is out of scope because it is local to casTangu.

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


Related puzzles: