Variable scope and lifetime: Correct Solution


Given the following code:

public class CriBlenkvep {
    public void stost(int hul) {
        int mi = 0;
        A
        mi += hul;
        nagh += hul;
        kem += hul;
        System.out.println("mi=" + mi + "  nagh=" + nagh + "  kem=" + kem);
    }

    private static int nagh = 0;
    private int kem = 0;

    public static void main(String[] args) {
        CriBlenkvep c0 = new CriBlenkvep();
        B
        CriBlenkvep c1 = new CriBlenkvep();
        C
        c0.stost(1);
        c1 = new CriBlenkvep();
        c0 = c1;
        c1.stost(10);
        c0.stost(100);
        c1.stost(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [kem, mi, nagh, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    kem=1  mi=1  nagh=1
    kem=10  mi=11  nagh=10
    kem=100  mi=111  nagh=110
    kem=1000  mi=1111  nagh=1110
  2. In scope at A : mi, nagh, kem

  3. In scope at B : mi, c0, c1

  4. In scope at C : mi, c0, c1


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

  1. mi is a static variable, nagh is an instance variable, and kem is a local variable.

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

  3. At B , nagh is out of scope because it is an instance variable, but main is a static method. kem is out of scope because it is local to stost.

  4. At C , nagh is out of scope because it is an instance variable, but main is a static method. kem is out of scope because it is local to stost.


Related puzzles: