Variable scope and lifetime: Correct Solution


Given the following code:

public class Vess {
    private int ar = 0;
    private static int oa = 0;

    public static void main(String[] args) {
        A
        Vess v0 = new Vess();
        Vess v1 = new Vess();
        v0.thra(1);
        v0 = new Vess();
        v1 = new Vess();
        v1.thra(10);
        v0.thra(100);
        v1.thra(1000);
        B
    }

    public void thra(int uc) {
        int mu = 0;
        oa += uc;
        ar += uc;
        mu += uc;
        System.out.println("oa=" + oa + "  ar=" + ar + "  mu=" + mu);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [mu, oa, ar, v0, v1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    mu=1  oa=1  ar=1
    mu=11  oa=10  ar=10
    mu=111  oa=100  ar=100
    mu=1111  oa=1010  ar=1000
  2. In scope at A : mu, v0

  3. In scope at B : mu

  4. In scope at C : mu, oa


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

  1. mu is a static variable, oa is an instance variable, and ar is a local variable.

  2. At A , v1 is out of scope because it is not declared yet. oa is out of scope because it is an instance variable, but main is a static method. ar is out of scope because it is local to thra.

  3. At B , v0 and v1 are out of scope because they are not declared yet. oa is out of scope because it is an instance variable, but main is a static method. ar is out of scope because it is local to thra.

  4. At C , ar is out of scope because it is not declared yet. v0 and v1 out of scope because they are local to the main method.


Related puzzles: