Variable scope and lifetime: Correct Solution


Given the following code:

public class Mosm {
    public static void main(String[] args) {
        A
        Mosm m0 = new Mosm();
        Mosm m1 = new Mosm();
        B
        m0.sheu(1);
        m0 = new Mosm();
        m1 = m0;
        m1.sheu(10);
        m0.sheu(100);
        m1.sheu(1000);
    }

    public void sheu(int hil) {
        int dre = 0;
        me += hil;
        dre += hil;
        phe += hil;
        System.out.println("me=" + me + "  dre=" + dre + "  phe=" + phe);
        C
    }

    private static int me = 0;
    private int phe = 0;
}
  1. What does the main method print?
  2. Which of the variables [phe, me, dre, m0, m1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    phe=1  me=1  dre=1
    phe=11  me=10  dre=10
    phe=111  me=100  dre=110
    phe=1111  me=1000  dre=1110
  2. In scope at A : phe, m0

  3. In scope at B : phe, m0, m1

  4. In scope at C : phe, dre


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

  1. phe is a static variable, dre is an instance variable, and me is a local variable.

  2. At A , m1 is out of scope because it is not declared yet. dre is out of scope because it is an instance variable, but main is a static method. me is out of scope because it is local to sheu.

  3. At B , dre is out of scope because it is an instance variable, but main is a static method. me is out of scope because it is local to sheu.

  4. At C , me is out of scope because it is not declared yet. m0 and m1 out of scope because they are local to the main method.


Related puzzles: