Variable scope and lifetime: Correct Solution


Given the following code:

public class Ismant {
    public static void main(String[] args) {
        A
        Ismant i0 = new Ismant();
        Ismant i1 = new Ismant();
        B
        i0.towest(1);
        i1.towest(10);
        i1 = i0;
        i0 = new Ismant();
        i0.towest(100);
        i1.towest(1000);
    }

    public void towest(int pasu) {
        int ci = 0;
        lem += pasu;
        di += pasu;
        ci += pasu;
        System.out.println("lem=" + lem + "  di=" + di + "  ci=" + ci);
        C
    }

    private static int di = 0;
    private int lem = 0;
}
  1. What does the main method print?
  2. Which of the variables [ci, lem, di, i0, i1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ci=1  lem=1  di=1
    ci=10  lem=11  di=10
    ci=100  lem=111  di=100
    ci=1001  lem=1111  di=1000
  2. In scope at A : lem, i0

  3. In scope at B : lem, i0, i1

  4. In scope at C : lem, ci


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

  1. lem is a static variable, ci is an instance variable, and di is a local variable.

  2. At A , i1 is out of scope because it is not declared yet. ci is out of scope because it is an instance variable, but main is a static method. di is out of scope because it is local to towest.

  3. At B , ci is out of scope because it is an instance variable, but main is a static method. di is out of scope because it is local to towest.

  4. At C , di is out of scope because it is not declared yet. i0 and i1 out of scope because they are local to the main method.


Related puzzles: