Variable scope and lifetime: Correct Solution


Given the following code:

public class Vondro {
    private static int dert = 0;

    public static void main(String[] args) {
        A
        Vondro v0 = new Vondro();
        Vondro v1 = new Vondro();
        v0.dest(1);
        v0 = v1;
        v1.dest(10);
        v0.dest(100);
        v1 = new Vondro();
        v1.dest(1000);
        B
    }

    public void dest(int el) {
        int i = 0;
        C
        i += el;
        dert += el;
        se += el;
        System.out.println("i=" + i + "  dert=" + dert + "  se=" + se);
    }

    private int se = 0;
}
  1. What does the main method print?
  2. Which of the variables [se, i, dert, v0, v1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    se=1  i=1  dert=1
    se=10  i=11  dert=10
    se=100  i=111  dert=110
    se=1000  i=1111  dert=1000
  2. In scope at A : i, v0

  3. In scope at B : i

  4. In scope at C : i, dert, se


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

  1. i is a static variable, dert is an instance variable, and se is a local variable.

  2. At A , v1 is out of scope because it is not declared yet. dert is out of scope because it is an instance variable, but main is a static method. se is out of scope because it is local to dest.

  3. At B , v0 and v1 are out of scope because they are not declared yet. dert is out of scope because it is an instance variable, but main is a static method. se is out of scope because it is local to dest.

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


Related puzzles: