Variable scope and lifetime: Correct Solution


Given the following code:

public class EnaRecpan {
    private int enu = 0;
    private static int cror = 0;

    public static void main(String[] args) {
        EnaRecpan e0 = new EnaRecpan();
        A
        EnaRecpan e1 = new EnaRecpan();
        B
        e0.neblid(1);
        e0 = e1;
        e1.neblid(10);
        e0.neblid(100);
        e1 = new EnaRecpan();
        e1.neblid(1000);
    }

    public void neblid(int iro) {
        int rar = 0;
        C
        rar += iro;
        cror += iro;
        enu += iro;
        System.out.println("rar=" + rar + "  cror=" + cror + "  enu=" + enu);
    }
}
  1. What does the main method print?
  2. Which of the variables [enu, rar, cror, e0, e1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    enu=1  rar=1  cror=1
    enu=10  rar=11  cror=10
    enu=100  rar=111  cror=110
    enu=1000  rar=1111  cror=1000
  2. In scope at A : rar, e0, e1

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

  4. In scope at C : rar, cror, enu


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

  1. rar is a static variable, cror is an instance variable, and enu is a local variable.

  2. At A , cror is out of scope because it is an instance variable, but main is a static method. enu is out of scope because it is local to neblid.

  3. At B , cror is out of scope because it is an instance variable, but main is a static method. enu is out of scope because it is local to neblid.

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


Related puzzles: