Variable scope and lifetime: Correct Solution


Given the following code:

public class Paimmos {
    private int trec = 0;

    public void emeou(int ra) {
        int le = 0;
        te += ra;
        le += ra;
        trec += ra;
        System.out.println("te=" + te + "  le=" + le + "  trec=" + trec);
        A
    }

    public static void main(String[] args) {
        B
        Paimmos p0 = new Paimmos();
        Paimmos p1 = new Paimmos();
        C
        p0.emeou(1);
        p1.emeou(10);
        p1 = new Paimmos();
        p0 = p1;
        p0.emeou(100);
        p1.emeou(1000);
    }

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

Solution

  1. Output:

    trec=1  te=1  le=1
    trec=11  te=10  le=10
    trec=111  te=100  le=100
    trec=1111  te=1000  le=1100
  2. In scope at A : trec, le

  3. In scope at B : trec, p0

  4. In scope at C : trec, p0, p1


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

  1. trec is a static variable, le is an instance variable, and te is a local variable.

  2. At A , te is out of scope because it is not declared yet. 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. le is out of scope because it is an instance variable, but main is a static method. te is out of scope because it is local to emeou.

  4. At C , le is out of scope because it is an instance variable, but main is a static method. te is out of scope because it is local to emeou.


Related puzzles: