Variable scope and lifetime: Correct Solution


Given the following code:

public class Mousa {
    public void zirEle(int piac) {
        int tant = 0;
        A
        oran += piac;
        ien += piac;
        tant += piac;
        System.out.println("oran=" + oran + "  ien=" + ien + "  tant=" + tant);
    }

    public static void main(String[] args) {
        Mousa m0 = new Mousa();
        B
        Mousa m1 = new Mousa();
        C
        m0.zirEle(1);
        m1.zirEle(10);
        m0.zirEle(100);
        m0 = new Mousa();
        m1 = m0;
        m1.zirEle(1000);
    }

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

Solution

  1. Output:

    tant=1  oran=1  ien=1
    tant=10  oran=11  ien=10
    tant=101  oran=111  ien=100
    tant=1000  oran=1111  ien=1000
  2. In scope at A : oran, tant, ien

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

  4. In scope at C : oran, m0, m1


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

  1. oran is a static variable, tant is an instance variable, and ien is a local variable.

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

  3. At B , tant is out of scope because it is an instance variable, but main is a static method. ien is out of scope because it is local to zirEle.

  4. At C , tant is out of scope because it is an instance variable, but main is a static method. ien is out of scope because it is local to zirEle.


Related puzzles: