Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int ce = 0;
    private static int cri = 0;

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

Solution

  1. Output:

    ce=1  cri=1  zeng=1
    ce=11  cri=10  zeng=10
    ce=111  cri=100  zeng=110
    ce=1111  cri=1000  zeng=1110
  2. In scope at A : ce, r0

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

  4. In scope at C : ce, zeng, cri


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

  1. ce is a static variable, zeng is an instance variable, and cri is a local variable.

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

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

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


Related puzzles: