Variable scope and lifetime: Correct Solution


Given the following code:

public class Engvis {
    public void badmo(int hi) {
        A
        int il = 0;
        il += hi;
        amer += hi;
        ca += hi;
        System.out.println("il=" + il + "  amer=" + amer + "  ca=" + ca);
    }

    private static int ca = 0;
    private int amer = 0;

    public static void main(String[] args) {
        Engvis e0 = new Engvis();
        B
        Engvis e1 = new Engvis();
        e0.badmo(1);
        e1 = e0;
        e1.badmo(10);
        e0.badmo(100);
        e0 = new Engvis();
        e1.badmo(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [ca, il, amer, 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  il=1  amer=1
    ca=10  il=11  amer=11
    ca=100  il=111  amer=111
    ca=1000  il=1111  amer=1111
  2. In scope at A : amer, il, ca

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

  4. In scope at C : amer


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

  1. amer is a static variable, il is an instance variable, and ca is a local variable.

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

  3. At B , il is out of scope because it is an instance variable, but main is a static method. ca is out of scope because it is local to badmo.

  4. At C , e0 and e1 are out of scope because they are not declared yet. il is out of scope because it is an instance variable, but main is a static method. ca is out of scope because it is local to badmo.


Related puzzles: