Variable scope and lifetime: Correct Solution


Given the following code:

public class Prun {
    private static int ti = 0;

    public void feoButrel(int en) {
        int fiui = 0;
        A
        fiui += en;
        ti += en;
        siar += en;
        System.out.println("fiui=" + fiui + "  ti=" + ti + "  siar=" + siar);
    }

    private int siar = 0;

    public static void main(String[] args) {
        B
        Prun p0 = new Prun();
        Prun p1 = new Prun();
        p0.feoButrel(1);
        p1.feoButrel(10);
        p0.feoButrel(100);
        p1 = p0;
        p0 = new Prun();
        p1.feoButrel(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [siar, fiui, ti, p0, p1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    siar=1  fiui=1  ti=1
    siar=10  fiui=11  ti=10
    siar=100  fiui=111  ti=101
    siar=1000  fiui=1111  ti=1101
  2. In scope at A : fiui, ti, siar

  3. In scope at B : fiui, p0

  4. In scope at C : fiui


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

  1. fiui is a static variable, ti is an instance variable, and siar is a local variable.

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

  3. At B , p1 is out of scope because it is not declared yet. ti is out of scope because it is an instance variable, but main is a static method. siar is out of scope because it is local to feoButrel.

  4. At C , p0 and p1 are out of scope because they are not declared yet. ti is out of scope because it is an instance variable, but main is a static method. siar is out of scope because it is local to feoButrel.


Related puzzles: