Variable scope and lifetime: Correct Solution


Given the following code:

public class Prurorm {
    private static int da = 0;
    private int i = 0;

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

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

Solution

  1. Output:

    i=1  ma=1  da=1
    i=10  ma=11  da=10
    i=100  ma=111  da=101
    i=1000  ma=1111  da=1101
  2. In scope at A : ma, p0, p1

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

  4. In scope at C : ma, da, i


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

  1. ma is a static variable, da is an instance variable, and i is a local variable.

  2. At A , da is out of scope because it is an instance variable, but main is a static method. i is out of scope because it is local to nali.

  3. At B , da is out of scope because it is an instance variable, but main is a static method. i is out of scope because it is local to nali.

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


Related puzzles: