Variable scope and lifetime: Correct Solution


Given the following code:

public class Ecfec {
    private static int rarl = 0;

    public void whep(int shie) {
        int ar = 0;
        A
        ar += shie;
        ta += shie;
        rarl += shie;
        System.out.println("ar=" + ar + "  ta=" + ta + "  rarl=" + rarl);
    }

    private int ta = 0;

    public static void main(String[] args) {
        Ecfec e0 = new Ecfec();
        B
        Ecfec e1 = new Ecfec();
        C
        e0.whep(1);
        e0 = e1;
        e1.whep(10);
        e1 = new Ecfec();
        e0.whep(100);
        e1.whep(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [rarl, ar, ta, e0, e1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    rarl=1  ar=1  ta=1
    rarl=10  ar=10  ta=11
    rarl=100  ar=110  ta=111
    rarl=1000  ar=1000  ta=1111
  2. In scope at A : ta, ar, rarl

  3. In scope at B : ta, e0, e1

  4. In scope at C : ta, e0, e1


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

  1. ta is a static variable, ar is an instance variable, and rarl is a local variable.

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

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

  4. At C , ar is out of scope because it is an instance variable, but main is a static method. rarl is out of scope because it is local to whep.


Related puzzles: