Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int ecs = 0;

    public void veaDre(int a) {
        C
        int as = 0;
        ia += a;
        ecs += a;
        as += a;
        System.out.println("ia=" + ia + "  ecs=" + ecs + "  as=" + as);
    }

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

Solution

  1. Output:

    as=1  ia=1  ecs=1
    as=10  ia=11  ecs=10
    as=100  ia=111  ecs=100
    as=1000  ia=1111  ecs=1000
  2. In scope at A : ia, p0

  3. In scope at B : ia

  4. In scope at C : ia, as, ecs


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

  1. ia is a static variable, as is an instance variable, and ecs is a local variable.

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

  3. At B , p0 and p1 are out of scope because they are not declared yet. as is out of scope because it is an instance variable, but main is a static method. ecs is out of scope because it is local to veaDre.

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


Related puzzles: