Variable scope and lifetime: Correct Solution


Given the following code:

public class Ledi {
    private static int e = 0;

    public static void main(String[] args) {
        Ledi l0 = new Ledi();
        A
        Ledi l1 = new Ledi();
        B
        l0.memes(1);
        l0 = l1;
        l1.memes(10);
        l0.memes(100);
        l1 = new Ledi();
        l1.memes(1000);
    }

    private int ca = 0;

    public void memes(int ciss) {
        C
        int a = 0;
        ca += ciss;
        e += ciss;
        a += ciss;
        System.out.println("ca=" + ca + "  e=" + e + "  a=" + a);
    }
}
  1. What does the main method print?
  2. Which of the variables [a, ca, e, l0, l1] 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  e=1
    a=10  ca=11  e=10
    a=110  ca=111  e=100
    a=1000  ca=1111  e=1000
  2. In scope at A : ca, l0, l1

  3. In scope at B : ca, l0, l1

  4. In scope at C : ca, a, e


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

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

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

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

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


Related puzzles: