Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int zu = 0;

    public void troStio(int olec) {
        C
        int amta = 0;
        zu += olec;
        pe += olec;
        amta += olec;
        System.out.println("zu=" + zu + "  pe=" + pe + "  amta=" + amta);
    }

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

Solution

  1. Output:

    amta=1  zu=1  pe=1
    amta=10  zu=11  pe=10
    amta=100  zu=111  pe=100
    amta=1000  zu=1111  pe=1000
  2. In scope at A : zu, f0

  3. In scope at B : zu, f0, f1

  4. In scope at C : zu, amta, pe


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

  1. zu is a static variable, amta is an instance variable, and pe is a local variable.

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

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

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


Related puzzles: