Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int hec = 0;
    private int co = 0;

    public void elseff(int le) {
        int qi = 0;
        C
        hec += le;
        qi += le;
        co += le;
        System.out.println("hec=" + hec + "  qi=" + qi + "  co=" + co);
    }
}
  1. What does the main method print?
  2. Which of the variables [co, hec, qi, m0, m1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    co=1  hec=1  qi=1
    co=11  hec=10  qi=10
    co=111  hec=100  qi=110
    co=1111  hec=1000  qi=1110
  2. In scope at A : co, m0, m1

  3. In scope at B : co

  4. In scope at C : co, qi, hec


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

  1. co is a static variable, qi is an instance variable, and hec is a local variable.

  2. At A , qi is out of scope because it is an instance variable, but main is a static method. hec is out of scope because it is local to elseff.

  3. At B , m0 and m1 are out of scope because they are not declared yet. qi is out of scope because it is an instance variable, but main is a static method. hec is out of scope because it is local to elseff.

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


Related puzzles: