Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void reddad(int essu) {
        int naei = 0;
        naei += essu;
        po += essu;
        ri += essu;
        System.out.println("naei=" + naei + "  po=" + po + "  ri=" + ri);
        C
    }

    private static int po = 0;
    private int ri = 0;
}
  1. What does the main method print?
  2. Which of the variables [ri, naei, po, e0, e1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ri=1  naei=1  po=1
    ri=10  naei=11  po=10
    ri=100  naei=111  po=100
    ri=1000  naei=1111  po=1100
  2. In scope at A : naei, e0

  3. In scope at B : naei

  4. In scope at C : naei, po


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

  1. naei is a static variable, po is an instance variable, and ri is a local variable.

  2. At A , e1 is out of scope because it is not declared yet. po is out of scope because it is an instance variable, but main is a static method. ri is out of scope because it is local to reddad.

  3. At B , e0 and e1 are out of scope because they are not declared yet. po is out of scope because it is an instance variable, but main is a static method. ri is out of scope because it is local to reddad.

  4. At C , ri is out of scope because it is not declared yet. e0 and e1 out of scope because they are local to the main method.


Related puzzles: