Variable scope and lifetime: Correct Solution


Given the following code:

public class Pharblem {
    private int el = 0;

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

    public void bism(int omas) {
        int eum = 0;
        eum += omas;
        em += omas;
        el += omas;
        System.out.println("eum=" + eum + "  em=" + em + "  el=" + el);
        C
    }

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

Solution

  1. Output:

    el=1  eum=1  em=1
    el=10  eum=11  em=10
    el=100  eum=111  em=100
    el=1000  eum=1111  em=1100
  2. In scope at A : eum, p0, p1

  3. In scope at B : eum

  4. In scope at C : eum, em


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

  1. eum is a static variable, em is an instance variable, and el is a local variable.

  2. At A , em is out of scope because it is an instance variable, but main is a static method. el is out of scope because it is local to bism.

  3. At B , p0 and p1 are out of scope because they are not declared yet. em is out of scope because it is an instance variable, but main is a static method. el is out of scope because it is local to bism.

  4. At C , el is out of scope because it is not declared yet. p0 and p1 out of scope because they are local to the main method.


Related puzzles: