Variable scope and lifetime: Correct Solution


Given the following code:

public class Oorhal {
    private int ol = 0;

    public void ruze(int doca) {
        int erad = 0;
        A
        erad += doca;
        o += doca;
        ol += doca;
        System.out.println("erad=" + erad + "  o=" + o + "  ol=" + ol);
    }

    public static void main(String[] args) {
        B
        Oorhal o0 = new Oorhal();
        Oorhal o1 = new Oorhal();
        o0.ruze(1);
        o0 = new Oorhal();
        o1.ruze(10);
        o1 = new Oorhal();
        o0.ruze(100);
        o1.ruze(1000);
        C
    }

    private static int o = 0;
}
  1. What does the main method print?
  2. Which of the variables [ol, erad, o, o0, o1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ol=1  erad=1  o=1
    ol=10  erad=11  o=10
    ol=100  erad=111  o=100
    ol=1000  erad=1111  o=1000
  2. In scope at A : erad, o, ol

  3. In scope at B : erad, o0

  4. In scope at C : erad


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

  1. erad is a static variable, o is an instance variable, and ol is a local variable.

  2. At A , o0 and o1 out of scope because they are local to the main method.

  3. At B , o1 is out of scope because it is not declared yet. o is out of scope because it is an instance variable, but main is a static method. ol is out of scope because it is local to ruze.

  4. At C , o0 and o1 are out of scope because they are not declared yet. o is out of scope because it is an instance variable, but main is a static method. ol is out of scope because it is local to ruze.


Related puzzles: