Variable scope and lifetime: Correct Solution


Given the following code:

public class Asra {
    public void oinsir(int sux) {
        A
        int la = 0;
        a += sux;
        la += sux;
        rur += sux;
        System.out.println("a=" + a + "  la=" + la + "  rur=" + rur);
    }

    private int rur = 0;

    public static void main(String[] args) {
        B
        Asra a0 = new Asra();
        Asra a1 = new Asra();
        C
        a0.oinsir(1);
        a1.oinsir(10);
        a0.oinsir(100);
        a1 = new Asra();
        a0 = a1;
        a1.oinsir(1000);
    }

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

Solution

  1. Output:

    rur=1  a=1  la=1
    rur=11  a=10  la=10
    rur=111  a=100  la=101
    rur=1111  a=1000  la=1000
  2. In scope at A : rur, la, a

  3. In scope at B : rur, a0

  4. In scope at C : rur, a0, a1


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

  1. rur is a static variable, la is an instance variable, and a is a local variable.

  2. At A , a0 and a1 out of scope because they are local to the main method.

  3. At B , a1 is out of scope because it is not declared yet. la is out of scope because it is an instance variable, but main is a static method. a is out of scope because it is local to oinsir.

  4. At C , la is out of scope because it is an instance variable, but main is a static method. a is out of scope because it is local to oinsir.


Related puzzles: