Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int ra = 0;
    private static int o = 0;

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

Solution

  1. Output:

    cex=1  o=1  ra=1
    cex=11  o=10  ra=10
    cex=111  o=100  ra=100
    cex=1111  o=1001  ra=1000
  2. In scope at A : cex, p0

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

  4. In scope at C : cex, o, ra


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

  1. cex is a static variable, o is an instance variable, and ra is a local variable.

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

  3. At B , o is out of scope because it is an instance variable, but main is a static method. ra is out of scope because it is local to sidod.

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


Related puzzles: