Variable scope and lifetime: Correct Solution


Given the following code:

public class Ruchor {
    private static int ac = 0;
    private int oic = 0;

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

    public void cedpen(int ko) {
        int wa = 0;
        C
        wa += ko;
        oic += ko;
        ac += ko;
        System.out.println("wa=" + wa + "  oic=" + oic + "  ac=" + ac);
    }
}
  1. What does the main method print?
  2. Which of the variables [ac, wa, oic, r0, r1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ac=1  wa=1  oic=1
    ac=10  wa=10  oic=11
    ac=100  wa=110  oic=111
    ac=1000  wa=1000  oic=1111
  2. In scope at A : oic, r0

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

  4. In scope at C : oic, wa, ac


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

  1. oic is a static variable, wa is an instance variable, and ac is a local variable.

  2. At A , r1 is out of scope because it is not declared yet. wa is out of scope because it is an instance variable, but main is a static method. ac is out of scope because it is local to cedpen.

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

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


Related puzzles: