Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int ha = 0;
    private static int me = 0;

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

Solution

  1. Output:

    ao=1  ha=1  me=1
    ao=10  ha=11  me=10
    ao=100  ha=111  me=100
    ao=1100  ha=1111  me=1000
  2. In scope at A : ha, s0, s1

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

  4. In scope at C : ha, ao, me


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

  1. ha is a static variable, ao is an instance variable, and me is a local variable.

  2. At A , ao is out of scope because it is an instance variable, but main is a static method. me is out of scope because it is local to iatHoctho.

  3. At B , ao is out of scope because it is an instance variable, but main is a static method. me is out of scope because it is local to iatHoctho.

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


Related puzzles: