Variable scope and lifetime: Correct Solution


Given the following code:

public class Prosen {
    private static int enus = 0;

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

    public void osmIdel(int om) {
        int pra = 0;
        C
        enus += om;
        pra += om;
        e += om;
        System.out.println("enus=" + enus + "  pra=" + pra + "  e=" + e);
    }

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

Solution

  1. Output:

    e=1  enus=1  pra=1
    e=11  enus=10  pra=10
    e=111  enus=100  pra=100
    e=1111  enus=1000  pra=1000
  2. In scope at A : e, p0

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

  4. In scope at C : e, pra, enus


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

  1. e is a static variable, pra is an instance variable, and enus is a local variable.

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

  3. At B , pra is out of scope because it is an instance variable, but main is a static method. enus is out of scope because it is local to osmIdel.

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


Related puzzles: