Variable scope and lifetime: Correct Solution


Given the following code:

public class Rhinkphrod {
    private static int ue = 0;
    private int ci = 0;

    public void mismvi(int e) {
        A
        int en = 0;
        en += e;
        ci += e;
        ue += e;
        System.out.println("en=" + en + "  ci=" + ci + "  ue=" + ue);
    }

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

Solution

  1. Output:

    ue=1  en=1  ci=1
    ue=10  en=10  ci=11
    ue=100  en=100  ci=111
    ue=1000  en=1000  ci=1111
  2. In scope at A : ci, en, ue

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

  4. In scope at C : ci, r0, r1


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

  1. ci is a static variable, en is an instance variable, and ue is a local variable.

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

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

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


Related puzzles: