Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int iat = 0;
    private int efe = 0;

    public void prilis(int ci) {
        int ce = 0;
        C
        efe += ci;
        iat += ci;
        ce += ci;
        System.out.println("efe=" + efe + "  iat=" + iat + "  ce=" + ce);
    }
}
  1. What does the main method print?
  2. Which of the variables [ce, efe, iat, p0, p1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ce=1  efe=1  iat=1
    ce=10  efe=11  iat=10
    ce=101  efe=111  iat=100
    ce=1000  efe=1111  iat=1000
  2. In scope at A : efe, p0

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

  4. In scope at C : efe, ce, iat


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

  1. efe is a static variable, ce is an instance variable, and iat is a local variable.

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

  3. At B , ce is out of scope because it is an instance variable, but main is a static method. iat is out of scope because it is local to prilis.

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


Related puzzles: