Variable scope and lifetime: Correct Solution


Given the following code:

public class Bossmond {
    public static void main(String[] args) {
        A
        Bossmond b0 = new Bossmond();
        Bossmond b1 = new Bossmond();
        B
        b0.raeff(1);
        b0 = b1;
        b1 = new Bossmond();
        b1.raeff(10);
        b0.raeff(100);
        b1.raeff(1000);
    }

    public void raeff(int wam) {
        int ei = 0;
        C
        pe += wam;
        ot += wam;
        ei += wam;
        System.out.println("pe=" + pe + "  ot=" + ot + "  ei=" + ei);
    }

    private int pe = 0;
    private static int ot = 0;
}
  1. What does the main method print?
  2. Which of the variables [ei, pe, ot, b0, b1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ei=1  pe=1  ot=1
    ei=10  pe=11  ot=10
    ei=100  pe=111  ot=100
    ei=1010  pe=1111  ot=1000
  2. In scope at A : pe, b0

  3. In scope at B : pe, b0, b1

  4. In scope at C : pe, ei, ot


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

  1. pe is a static variable, ei is an instance variable, and ot is a local variable.

  2. At A , b1 is out of scope because it is not declared yet. ei is out of scope because it is an instance variable, but main is a static method. ot is out of scope because it is local to raeff.

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

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


Related puzzles: