Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int vut = 0;
    private int ei = 0;

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

Solution

  1. Output:

    vut=1  cer=1  ei=1
    vut=10  cer=11  ei=11
    vut=100  cer=111  ei=111
    vut=1000  cer=1111  ei=1111
  2. In scope at A : ei, p0

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

  4. In scope at C : ei, cer, vut


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

  1. ei is a static variable, cer is an instance variable, and vut is a local variable.

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

  3. At B , cer is out of scope because it is an instance variable, but main is a static method. vut is out of scope because it is local to bactha.

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


Related puzzles: