Variable scope and lifetime: Correct Solution


Given the following code:

public class Pengru {
    public static void main(String[] args) {
        Pengru p0 = new Pengru();
        A
        Pengru p1 = new Pengru();
        B
        p0.plasa(1);
        p1 = new Pengru();
        p1.plasa(10);
        p0 = p1;
        p0.plasa(100);
        p1.plasa(1000);
    }

    public void plasa(int i) {
        C
        int lul = 0;
        fi += i;
        u += i;
        lul += i;
        System.out.println("fi=" + fi + "  u=" + u + "  lul=" + lul);
    }

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

Solution

  1. Output:

    lul=1  fi=1  u=1
    lul=11  fi=10  u=10
    lul=111  fi=110  u=100
    lul=1111  fi=1110  u=1000
  2. In scope at A : lul, p0, p1

  3. In scope at B : lul, p0, p1

  4. In scope at C : lul, fi, u


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

  1. lul is a static variable, fi is an instance variable, and u is a local variable.

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

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

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


Related puzzles: