Variable scope and lifetime: Correct Solution


Given the following code:

public class Mewcur {
    private static int a = 0;

    public void oshri(int ca) {
        A
        int pid = 0;
        a += ca;
        iass += ca;
        pid += ca;
        System.out.println("a=" + a + "  iass=" + iass + "  pid=" + pid);
    }

    private int iass = 0;

    public static void main(String[] args) {
        Mewcur m0 = new Mewcur();
        B
        Mewcur m1 = new Mewcur();
        m0.oshri(1);
        m0 = m1;
        m1.oshri(10);
        m0.oshri(100);
        m1 = new Mewcur();
        m1.oshri(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [pid, a, iass, m0, m1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    pid=1  a=1  iass=1
    pid=11  a=10  iass=10
    pid=111  a=110  iass=100
    pid=1111  a=1000  iass=1000
  2. In scope at A : pid, a, iass

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

  4. In scope at C : pid


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

  1. pid is a static variable, a is an instance variable, and iass is a local variable.

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

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

  4. At C , m0 and m1 are out of scope because they are not declared yet. a is out of scope because it is an instance variable, but main is a static method. iass is out of scope because it is local to oshri.


Related puzzles: