Variable scope and lifetime: Correct Solution


Given the following code:

public class KnoAlses {
    private int ena = 0;
    private static int pe = 0;

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

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

Solution

  1. Output:

    pe=1  ena=1  hiu=1
    pe=10  ena=10  hiu=11
    pe=100  ena=100  hiu=111
    pe=1000  ena=1000  hiu=1111
  2. In scope at A : hiu, k0, k1

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

  4. In scope at C : hiu, pe, ena


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

  1. hiu is a static variable, pe is an instance variable, and ena is a local variable.

  2. At A , pe is out of scope because it is an instance variable, but main is a static method. ena is out of scope because it is local to darpe.

  3. At B , pe is out of scope because it is an instance variable, but main is a static method. ena is out of scope because it is local to darpe.

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


Related puzzles: