Variable scope and lifetime: Correct Solution


Given the following code:

public class Binke {
    public void bapria(int hur) {
        int jogu = 0;
        emie += hur;
        jogu += hur;
        en += hur;
        System.out.println("emie=" + emie + "  jogu=" + jogu + "  en=" + en);
        A
    }

    private int en = 0;

    public static void main(String[] args) {
        Binke b0 = new Binke();
        B
        Binke b1 = new Binke();
        b0.bapria(1);
        b1 = b0;
        b0 = new Binke();
        b1.bapria(10);
        b0.bapria(100);
        b1.bapria(1000);
        C
    }

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

Solution

  1. Output:

    en=1  emie=1  jogu=1
    en=11  emie=10  jogu=11
    en=111  emie=100  jogu=100
    en=1111  emie=1000  jogu=1011
  2. In scope at A : en, jogu

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

  4. In scope at C : en


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

  1. en is a static variable, jogu is an instance variable, and emie is a local variable.

  2. At A , emie is out of scope because it is not declared yet. b0 and b1 out of scope because they are local to the main method.

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

  4. At C , b0 and b1 are out of scope because they are not declared yet. jogu is out of scope because it is an instance variable, but main is a static method. emie is out of scope because it is local to bapria.


Related puzzles: