Variable scope and lifetime: Correct Solution


Given the following code:

public class Hiou {
    public static void main(String[] args) {
        A
        Hiou h0 = new Hiou();
        Hiou h1 = new Hiou();
        B
        h0.neape(1);
        h1.neape(10);
        h1 = new Hiou();
        h0.neape(100);
        h0 = h1;
        h1.neape(1000);
    }

    private int eck = 0;
    private static int no = 0;

    public void neape(int imin) {
        int sco = 0;
        C
        sco += imin;
        no += imin;
        eck += imin;
        System.out.println("sco=" + sco + "  no=" + no + "  eck=" + eck);
    }
}
  1. What does the main method print?
  2. Which of the variables [eck, sco, no, h0, h1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    eck=1  sco=1  no=1
    eck=10  sco=11  no=10
    eck=100  sco=111  no=101
    eck=1000  sco=1111  no=1000
  2. In scope at A : sco, h0

  3. In scope at B : sco, h0, h1

  4. In scope at C : sco, no, eck


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

  1. sco is a static variable, no is an instance variable, and eck is a local variable.

  2. At A , h1 is out of scope because it is not declared yet. no is out of scope because it is an instance variable, but main is a static method. eck is out of scope because it is local to neape.

  3. At B , no is out of scope because it is an instance variable, but main is a static method. eck is out of scope because it is local to neape.

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


Related puzzles: