Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int a = 0;

    public void knacen(int es) {
        int casm = 0;
        C
        a += es;
        casm += es;
        zaer += es;
        System.out.println("a=" + a + "  casm=" + casm + "  zaer=" + zaer);
    }

    private static int zaer = 0;
}
  1. What does the main method print?
  2. Which of the variables [zaer, a, casm, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    zaer=1  a=1  casm=1
    zaer=10  a=10  casm=11
    zaer=110  a=100  casm=111
    zaer=1110  a=1000  casm=1111
  2. In scope at A : casm, c0, c1

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

  4. In scope at C : casm, zaer, a


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

  1. casm is a static variable, zaer is an instance variable, and a is a local variable.

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

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

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


Related puzzles: