Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int ca = 0;

    public void ceth(int is) {
        int sa = 0;
        eas += is;
        sa += is;
        ca += is;
        System.out.println("eas=" + eas + "  sa=" + sa + "  ca=" + ca);
        C
    }

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

Solution

  1. Output:

    ca=1  eas=1  sa=1
    ca=11  eas=10  sa=10
    ca=111  eas=100  sa=100
    ca=1111  eas=1000  sa=1000
  2. In scope at A : ca, e0

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

  4. In scope at C : ca, sa


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

  1. ca is a static variable, sa is an instance variable, and eas is a local variable.

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

  3. At B , sa is out of scope because it is an instance variable, but main is a static method. eas is out of scope because it is local to ceth.

  4. At C , eas 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: