Variable scope and lifetime: Correct Solution


Given the following code:

public class HulOss {
    private int eles = 0;

    public void aeng(int et) {
        A
        int id = 0;
        id += et;
        eles += et;
        es += et;
        System.out.println("id=" + id + "  eles=" + eles + "  es=" + es);
    }

    public static void main(String[] args) {
        B
        HulOss h0 = new HulOss();
        HulOss h1 = new HulOss();
        h0.aeng(1);
        h1.aeng(10);
        h0.aeng(100);
        h0 = new HulOss();
        h1 = h0;
        h1.aeng(1000);
        C
    }

    private static int es = 0;
}
  1. What does the main method print?
  2. Which of the variables [es, id, eles, h0, h1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    es=1  id=1  eles=1
    es=10  id=10  eles=11
    es=100  id=101  eles=111
    es=1000  id=1000  eles=1111
  2. In scope at A : eles, id, es

  3. In scope at B : eles, h0

  4. In scope at C : eles


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

  1. eles is a static variable, id is an instance variable, and es is a local variable.

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

  3. At B , h1 is out of scope because it is not declared yet. id is out of scope because it is an instance variable, but main is a static method. es is out of scope because it is local to aeng.

  4. At C , h0 and h1 are out of scope because they are not declared yet. id is out of scope because it is an instance variable, but main is a static method. es is out of scope because it is local to aeng.


Related puzzles: