Variable scope and lifetime: Correct Solution


Given the following code:

public class Eshcesh {
    private int irar = 0;

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

    private static int e = 0;

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

Solution

  1. Output:

    irar=1  es=1  e=1
    irar=10  es=11  e=10
    irar=100  es=111  e=110
    irar=1000  es=1111  e=1000
  2. In scope at A : es, e0, e1

  3. In scope at B : es

  4. In scope at C : es, e, irar


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

  1. es is a static variable, e is an instance variable, and irar is a local variable.

  2. At A , e is out of scope because it is an instance variable, but main is a static method. irar is out of scope because it is local to antbo.

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

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


Related puzzles: