Variable scope and lifetime: Correct Solution


Given the following code:

public class Rucac {
    private static int cof = 0;

    public void diso(int es) {
        A
        int ied = 0;
        osia += es;
        cof += es;
        ied += es;
        System.out.println("osia=" + osia + "  cof=" + cof + "  ied=" + ied);
    }

    private int osia = 0;

    public static void main(String[] args) {
        B
        Rucac r0 = new Rucac();
        Rucac r1 = new Rucac();
        r0.diso(1);
        r1 = r0;
        r1.diso(10);
        r0 = r1;
        r0.diso(100);
        r1.diso(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [ied, osia, cof, r0, r1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ied=1  osia=1  cof=1
    ied=11  osia=11  cof=10
    ied=111  osia=111  cof=100
    ied=1111  osia=1111  cof=1000
  2. In scope at A : osia, ied, cof

  3. In scope at B : osia, r0

  4. In scope at C : osia


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

  1. osia is a static variable, ied is an instance variable, and cof is a local variable.

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

  3. At B , r1 is out of scope because it is not declared yet. ied is out of scope because it is an instance variable, but main is a static method. cof is out of scope because it is local to diso.

  4. At C , r0 and r1 are out of scope because they are not declared yet. ied is out of scope because it is an instance variable, but main is a static method. cof is out of scope because it is local to diso.


Related puzzles: