Variable scope and lifetime: Correct Solution


Given the following code:

public class Oorsal {
    private int ca = 0;

    public void ceeri(int tric) {
        int lala = 0;
        A
        ca += tric;
        lala += tric;
        a += tric;
        System.out.println("ca=" + ca + "  lala=" + lala + "  a=" + a);
    }

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

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

Solution

  1. Output:

    a=1  ca=1  lala=1
    a=10  ca=10  lala=11
    a=100  ca=100  lala=111
    a=1100  ca=1000  lala=1111
  2. In scope at A : lala, a, ca

  3. In scope at B : lala, o0, o1

  4. In scope at C : lala


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

  1. lala is a static variable, a is an instance variable, and ca is a local variable.

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

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

  4. At C , o0 and o1 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. ca is out of scope because it is local to ceeri.


Related puzzles: