Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int auc = 0;

    public void phouss(int desa) {
        int a = 0;
        auc += desa;
        a += desa;
        ve += desa;
        System.out.println("auc=" + auc + "  a=" + a + "  ve=" + ve);
        C
    }

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

Solution

  1. Output:

    ve=1  auc=1  a=1
    ve=10  auc=10  a=11
    ve=101  auc=100  a=111
    ve=1101  auc=1000  a=1111
  2. In scope at A : a, m0

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

  4. In scope at C : a, ve


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

  1. a is a static variable, ve is an instance variable, and auc is a local variable.

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

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

  4. At C , auc is out of scope because it is not declared yet. m0 and m1 out of scope because they are local to the main method.


Related puzzles: