Variable scope and lifetime: Correct Solution


Given the following code:

public class Flis {
    private int mur = 0;
    private static int hepi = 0;

    public static void main(String[] args) {
        Flis f0 = new Flis();
        A
        Flis f1 = new Flis();
        f0.dursas(1);
        f1.dursas(10);
        f0.dursas(100);
        f1 = f0;
        f0 = new Flis();
        f1.dursas(1000);
        B
    }

    public void dursas(int cint) {
        C
        int o = 0;
        hepi += cint;
        o += cint;
        mur += cint;
        System.out.println("hepi=" + hepi + "  o=" + o + "  mur=" + mur);
    }
}
  1. What does the main method print?
  2. Which of the variables [mur, hepi, o, f0, f1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    mur=1  hepi=1  o=1
    mur=11  hepi=10  o=10
    mur=111  hepi=100  o=101
    mur=1111  hepi=1000  o=1101
  2. In scope at A : mur, f0, f1

  3. In scope at B : mur

  4. In scope at C : mur, o, hepi


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

  1. mur is a static variable, o is an instance variable, and hepi is a local variable.

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

  3. At B , f0 and f1 are out of scope because they are not declared yet. o is out of scope because it is an instance variable, but main is a static method. hepi is out of scope because it is local to dursas.

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


Related puzzles: