Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void estrar(int asac) {
        int si = 0;
        C
        fel += asac;
        e += asac;
        si += asac;
        System.out.println("fel=" + fel + "  e=" + e + "  si=" + si);
    }

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

Solution

  1. Output:

    si=1  fel=1  e=1
    si=10  fel=11  e=10
    si=101  fel=111  e=100
    si=1101  fel=1111  e=1000
  2. In scope at A : fel, p0

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

  4. In scope at C : fel, si, e


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

  1. fel is a static variable, si is an instance variable, and e is a local variable.

  2. At A , p1 is out of scope because it is not declared yet. si is out of scope because it is an instance variable, but main is a static method. e is out of scope because it is local to estrar.

  3. At B , si is out of scope because it is an instance variable, but main is a static method. e is out of scope because it is local to estrar.

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


Related puzzles: