Variable scope and lifetime: Correct Solution


Given the following code:

public class Ancing {
    public static void main(String[] args) {
        Ancing a0 = new Ancing();
        A
        Ancing a1 = new Ancing();
        B
        a0.sicuas(1);
        a1.sicuas(10);
        a0 = a1;
        a0.sicuas(100);
        a1 = a0;
        a1.sicuas(1000);
    }

    public void sicuas(int uism) {
        int cer = 0;
        cer += uism;
        ir += uism;
        shil += uism;
        System.out.println("cer=" + cer + "  ir=" + ir + "  shil=" + shil);
        C
    }

    private static int ir = 0;
    private int shil = 0;
}
  1. What does the main method print?
  2. Which of the variables [shil, cer, ir, a0, a1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    shil=1  cer=1  ir=1
    shil=10  cer=11  ir=10
    shil=100  cer=111  ir=110
    shil=1000  cer=1111  ir=1110
  2. In scope at A : cer, a0, a1

  3. In scope at B : cer, a0, a1

  4. In scope at C : cer, ir


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

  1. cer is a static variable, ir is an instance variable, and shil is a local variable.

  2. At A , ir is out of scope because it is an instance variable, but main is a static method. shil is out of scope because it is local to sicuas.

  3. At B , ir is out of scope because it is an instance variable, but main is a static method. shil is out of scope because it is local to sicuas.

  4. At C , shil is out of scope because it is not declared yet. a0 and a1 out of scope because they are local to the main method.


Related puzzles: