Variable scope and lifetime: Correct Solution


Given the following code:

public class CelKod {
    public static void main(String[] args) {
        A
        CelKod c0 = new CelKod();
        CelKod c1 = new CelKod();
        c0.hadant(1);
        c1 = c0;
        c1.hadant(10);
        c0 = new CelKod();
        c0.hadant(100);
        c1.hadant(1000);
        B
    }

    private int sint = 0;
    private static int ari = 0;

    public void hadant(int lewi) {
        int er = 0;
        C
        ari += lewi;
        sint += lewi;
        er += lewi;
        System.out.println("ari=" + ari + "  sint=" + sint + "  er=" + er);
    }
}
  1. What does the main method print?
  2. Which of the variables [er, ari, sint, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    er=1  ari=1  sint=1
    er=11  ari=11  sint=10
    er=111  ari=100  sint=100
    er=1111  ari=1011  sint=1000
  2. In scope at A : er, c0

  3. In scope at B : er

  4. In scope at C : er, ari, sint


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

  1. er is a static variable, ari is an instance variable, and sint is a local variable.

  2. At A , c1 is out of scope because it is not declared yet. ari is out of scope because it is an instance variable, but main is a static method. sint is out of scope because it is local to hadant.

  3. At B , c0 and c1 are out of scope because they are not declared yet. ari is out of scope because it is an instance variable, but main is a static method. sint is out of scope because it is local to hadant.

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


Related puzzles: