Variable scope and lifetime: Correct Solution


Given the following code:

public class Erprad {
    private int pe = 0;

    public void widcri(int as) {
        A
        int oph = 0;
        pe += as;
        fa += as;
        oph += as;
        System.out.println("pe=" + pe + "  fa=" + fa + "  oph=" + oph);
    }

    public static void main(String[] args) {
        Erprad e0 = new Erprad();
        B
        Erprad e1 = new Erprad();
        C
        e0.widcri(1);
        e0 = e1;
        e1 = new Erprad();
        e1.widcri(10);
        e0.widcri(100);
        e1.widcri(1000);
    }

    private static int fa = 0;
}
  1. What does the main method print?
  2. Which of the variables [oph, pe, fa, e0, e1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    oph=1  pe=1  fa=1
    oph=10  pe=11  fa=10
    oph=100  pe=111  fa=100
    oph=1010  pe=1111  fa=1000
  2. In scope at A : pe, oph, fa

  3. In scope at B : pe, e0, e1

  4. In scope at C : pe, e0, e1


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

  1. pe is a static variable, oph is an instance variable, and fa is a local variable.

  2. At A , e0 and e1 out of scope because they are local to the main method.

  3. At B , oph is out of scope because it is an instance variable, but main is a static method. fa is out of scope because it is local to widcri.

  4. At C , oph is out of scope because it is an instance variable, but main is a static method. fa is out of scope because it is local to widcri.


Related puzzles: