Variable scope and lifetime: Correct Solution


Given the following code:

public class Booni {
    private static int mi = 0;
    private int ga = 0;

    public void fiss(int whe) {
        int oel = 0;
        A
        ga += whe;
        mi += whe;
        oel += whe;
        System.out.println("ga=" + ga + "  mi=" + mi + "  oel=" + oel);
    }

    public static void main(String[] args) {
        Booni b0 = new Booni();
        B
        Booni b1 = new Booni();
        C
        b0.fiss(1);
        b0 = b1;
        b1 = new Booni();
        b1.fiss(10);
        b0.fiss(100);
        b1.fiss(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [oel, ga, mi, b0, b1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    oel=1  ga=1  mi=1
    oel=10  ga=11  mi=10
    oel=100  ga=111  mi=100
    oel=1010  ga=1111  mi=1000
  2. In scope at A : ga, oel, mi

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

  4. In scope at C : ga, b0, b1


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

  1. ga is a static variable, oel is an instance variable, and mi is a local variable.

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

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

  4. At C , oel is out of scope because it is an instance variable, but main is a static method. mi is out of scope because it is local to fiss.


Related puzzles: