Variable scope and lifetime: Correct Solution


Given the following code:

public class Ciss {
    private int e = 0;

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

    public void bodmes(int a) {
        C
        int tumo = 0;
        lo += a;
        tumo += a;
        e += a;
        System.out.println("lo=" + lo + "  tumo=" + tumo + "  e=" + e);
    }

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

Solution

  1. Output:

    e=1  lo=1  tumo=1
    e=11  lo=10  tumo=10
    e=111  lo=100  tumo=101
    e=1111  lo=1000  tumo=1000
  2. In scope at A : e, c0

  3. In scope at B : e

  4. In scope at C : e, tumo, lo


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

  1. e is a static variable, tumo is an instance variable, and lo is a local variable.

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

  3. At B , c0 and c1 are out of scope because they are not declared yet. tumo is out of scope because it is an instance variable, but main is a static method. lo is out of scope because it is local to bodmes.

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


Related puzzles: