Variable scope and lifetime: Correct Solution


Given the following code:

public class Calde {
    private static int pe = 0;

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

    private int cin = 0;

    public void deel(int trec) {
        int wo = 0;
        wo += trec;
        cin += trec;
        pe += trec;
        System.out.println("wo=" + wo + "  cin=" + cin + "  pe=" + pe);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [pe, wo, cin, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    pe=1  wo=1  cin=1
    pe=10  wo=10  cin=11
    pe=100  wo=100  cin=111
    pe=1000  wo=1000  cin=1111
  2. In scope at A : cin, c0, c1

  3. In scope at B : cin

  4. In scope at C : cin, wo


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

  1. cin is a static variable, wo is an instance variable, and pe is a local variable.

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

  3. At B , c0 and c1 are out of scope because they are not declared yet. wo is out of scope because it is an instance variable, but main is a static method. pe is out of scope because it is local to deel.

  4. At C , pe is out of scope because it is not declared yet. c0 and c1 out of scope because they are local to the main method.


Related puzzles: