Variable scope and lifetime: Correct Solution


Given the following code:

public class Rarro {
    public static void main(String[] args) {
        Rarro r0 = new Rarro();
        A
        Rarro r1 = new Rarro();
        B
        r0.blaCerd(1);
        r1.blaCerd(10);
        r0.blaCerd(100);
        r1 = r0;
        r0 = new Rarro();
        r1.blaCerd(1000);
    }

    public void blaCerd(int eo) {
        int iosm = 0;
        iosm += eo;
        lio += eo;
        is += eo;
        System.out.println("iosm=" + iosm + "  lio=" + lio + "  is=" + is);
        C
    }

    private static int lio = 0;
    private int is = 0;
}
  1. What does the main method print?
  2. Which of the variables [is, iosm, lio, r0, r1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    is=1  iosm=1  lio=1
    is=10  iosm=11  lio=10
    is=100  iosm=111  lio=101
    is=1000  iosm=1111  lio=1101
  2. In scope at A : iosm, r0, r1

  3. In scope at B : iosm, r0, r1

  4. In scope at C : iosm, lio


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

  1. iosm is a static variable, lio is an instance variable, and is is a local variable.

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

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

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


Related puzzles: