Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int or = 0;

    public void omlil(int trec) {
        int a = 0;
        C
        a += trec;
        or += trec;
        wu += trec;
        System.out.println("a=" + a + "  or=" + or + "  wu=" + wu);
    }

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

Solution

  1. Output:

    wu=1  a=1  or=1
    wu=10  a=10  or=11
    wu=100  a=101  or=111
    wu=1000  a=1000  or=1111
  2. In scope at A : or, b0, b1

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

  4. In scope at C : or, a, wu


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

  1. or is a static variable, a is an instance variable, and wu is a local variable.

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

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

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


Related puzzles: