Variable scope and lifetime: Correct Solution


Given the following code:

public class Knisbroa {
    public static void main(String[] args) {
        Knisbroa k0 = new Knisbroa();
        A
        Knisbroa k1 = new Knisbroa();
        B
        k0.sphon(1);
        k1.sphon(10);
        k0 = new Knisbroa();
        k1 = k0;
        k0.sphon(100);
        k1.sphon(1000);
    }

    private static int cang = 0;
    private int som = 0;

    public void sphon(int cet) {
        int pha = 0;
        C
        cang += cet;
        pha += cet;
        som += cet;
        System.out.println("cang=" + cang + "  pha=" + pha + "  som=" + som);
    }
}
  1. What does the main method print?
  2. Which of the variables [som, cang, pha, k0, k1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    som=1  cang=1  pha=1
    som=11  cang=10  pha=10
    som=111  cang=100  pha=100
    som=1111  cang=1000  pha=1100
  2. In scope at A : som, k0, k1

  3. In scope at B : som, k0, k1

  4. In scope at C : som, pha, cang


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

  1. som is a static variable, pha is an instance variable, and cang is a local variable.

  2. At A , pha is out of scope because it is an instance variable, but main is a static method. cang is out of scope because it is local to sphon.

  3. At B , pha is out of scope because it is an instance variable, but main is a static method. cang is out of scope because it is local to sphon.

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


Related puzzles: