Variable scope and lifetime: Correct Solution


Given the following code:

public class Cepar {
    private int ci = 0;

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

    public void achoim(int co) {
        C
        int no = 0;
        gle += co;
        ci += co;
        no += co;
        System.out.println("gle=" + gle + "  ci=" + ci + "  no=" + no);
    }

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

Solution

  1. Output:

    no=1  gle=1  ci=1
    no=11  gle=11  ci=10
    no=111  gle=111  ci=100
    no=1111  gle=1111  ci=1000
  2. In scope at A : no, c0, c1

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

  4. In scope at C : no, gle, ci


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

  1. no is a static variable, gle is an instance variable, and ci is a local variable.

  2. At A , gle is out of scope because it is an instance variable, but main is a static method. ci is out of scope because it is local to achoim.

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

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


Related puzzles: