Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int in = 0;

    public void nesbio(int bati) {
        C
        int weti = 0;
        in += bati;
        ce += bati;
        weti += bati;
        System.out.println("in=" + in + "  ce=" + ce + "  weti=" + weti);
    }

    private int ce = 0;
}
  1. What does the main method print?
  2. Which of the variables [weti, in, ce, l0, l1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    weti=1  in=1  ce=1
    weti=11  in=10  ce=10
    weti=111  in=100  ce=100
    weti=1111  in=1010  ce=1000
  2. In scope at A : weti, l0, l1

  3. In scope at B : weti

  4. In scope at C : weti, in, ce


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

  1. weti is a static variable, in is an instance variable, and ce is a local variable.

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

  3. At B , l0 and l1 are out of scope because they are not declared yet. in is out of scope because it is an instance variable, but main is a static method. ce is out of scope because it is local to nesbio.

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


Related puzzles: