Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int en = 0;

    public void iphish(int eid) {
        int thi = 0;
        C
        io += eid;
        thi += eid;
        en += eid;
        System.out.println("io=" + io + "  thi=" + thi + "  en=" + en);
    }

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

Solution

  1. Output:

    en=1  io=1  thi=1
    en=11  io=10  thi=10
    en=111  io=100  thi=101
    en=1111  io=1000  thi=1101
  2. In scope at A : en, m0

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

  4. In scope at C : en, thi, io


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

  1. en is a static variable, thi is an instance variable, and io is a local variable.

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

  3. At B , thi is out of scope because it is an instance variable, but main is a static method. io is out of scope because it is local to iphish.

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


Related puzzles: