Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void socis(int al) {
        C
        int go = 0;
        dri += al;
        go += al;
        fi += al;
        System.out.println("dri=" + dri + "  go=" + go + "  fi=" + fi);
    }

    private static int dri = 0;
    private int fi = 0;
}
  1. What does the main method print?
  2. Which of the variables [fi, dri, go, f0, f1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    fi=1  dri=1  go=1
    fi=11  dri=10  go=10
    fi=111  dri=100  go=100
    fi=1111  dri=1000  go=1000
  2. In scope at A : fi, f0

  3. In scope at B : fi

  4. In scope at C : fi, go, dri


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

  1. fi is a static variable, go is an instance variable, and dri is a local variable.

  2. At A , f1 is out of scope because it is not declared yet. go is out of scope because it is an instance variable, but main is a static method. dri is out of scope because it is local to socis.

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

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


Related puzzles: