Variable scope and lifetime: Correct Solution


Given the following code:

public class Coek {
    public static void main(String[] args) {
        A
        Coek c0 = new Coek();
        Coek c1 = new Coek();
        B
        c0.meis(1);
        c1.meis(10);
        c1 = new Coek();
        c0.meis(100);
        c0 = c1;
        c1.meis(1000);
    }

    private static int coa = 0;

    public void meis(int oll) {
        C
        int uco = 0;
        co += oll;
        coa += oll;
        uco += oll;
        System.out.println("co=" + co + "  coa=" + coa + "  uco=" + uco);
    }

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

Solution

  1. Output:

    uco=1  co=1  coa=1
    uco=10  co=11  coa=10
    uco=101  co=111  coa=100
    uco=1000  co=1111  coa=1000
  2. In scope at A : co, c0

  3. In scope at B : co, c0, c1

  4. In scope at C : co, uco, coa


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

  1. co is a static variable, uco is an instance variable, and coa is a local variable.

  2. At A , c1 is out of scope because it is not declared yet. uco is out of scope because it is an instance variable, but main is a static method. coa is out of scope because it is local to meis.

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

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


Related puzzles: