Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int da = 0;
    private int goci = 0;

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

Solution

  1. Output:

    wul=1  da=1  goci=1
    wul=11  da=10  goci=10
    wul=111  da=100  goci=100
    wul=1111  da=1100  goci=1000
  2. In scope at A : wul, m0

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

  4. In scope at C : wul, da, goci


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

  1. wul is a static variable, da is an instance variable, and goci is a local variable.

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

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

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


Related puzzles: