Variable scope and lifetime: Correct Solution


Given the following code:

public class Duhel {
    private static int sa = 0;

    public static void main(String[] args) {
        Duhel d0 = new Duhel();
        A
        Duhel d1 = new Duhel();
        B
        d0.bres(1);
        d1.bres(10);
        d1 = new Duhel();
        d0 = new Duhel();
        d0.bres(100);
        d1.bres(1000);
    }

    public void bres(int huan) {
        int oc = 0;
        C
        oc += huan;
        sa += huan;
        co += huan;
        System.out.println("oc=" + oc + "  sa=" + sa + "  co=" + co);
    }

    private int co = 0;
}
  1. What does the main method print?
  2. Which of the variables [co, oc, sa, d0, d1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    co=1  oc=1  sa=1
    co=10  oc=11  sa=10
    co=100  oc=111  sa=100
    co=1000  oc=1111  sa=1000
  2. In scope at A : oc, d0, d1

  3. In scope at B : oc, d0, d1

  4. In scope at C : oc, sa, co


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

  1. oc is a static variable, sa is an instance variable, and co is a local variable.

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

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

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


Related puzzles: