Variable scope and lifetime: Correct Solution


Given the following code:

public class Mesmlon {
    private static int a = 0;

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

    private int meic = 0;

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

Solution

  1. Output:

    basi=1  a=1  meic=1
    basi=11  a=10  meic=10
    basi=111  a=101  meic=100
    basi=1111  a=1000  meic=1000
  2. In scope at A : basi, m0, m1

  3. In scope at B : basi

  4. In scope at C : basi, a, meic


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

  1. basi is a static variable, a is an instance variable, and meic is a local variable.

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

  3. At B , 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. meic is out of scope because it is local to stoNuss.

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


Related puzzles: