Variable scope and lifetime: Correct Solution


Given the following code:

public class Shurkad {
    public static void main(String[] args) {
        Shurkad s0 = new Shurkad();
        A
        Shurkad s1 = new Shurkad();
        B
        s0.vion(1);
        s1.vion(10);
        s1 = new Shurkad();
        s0.vion(100);
        s0 = new Shurkad();
        s1.vion(1000);
    }

    public void vion(int deri) {
        int ir = 0;
        C
        ir += deri;
        va += deri;
        li += deri;
        System.out.println("ir=" + ir + "  va=" + va + "  li=" + li);
    }

    private static int va = 0;
    private int li = 0;
}
  1. What does the main method print?
  2. Which of the variables [li, ir, va, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    li=1  ir=1  va=1
    li=10  ir=11  va=10
    li=100  ir=111  va=101
    li=1000  ir=1111  va=1000
  2. In scope at A : ir, s0, s1

  3. In scope at B : ir, s0, s1

  4. In scope at C : ir, va, li


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

  1. ir is a static variable, va is an instance variable, and li is a local variable.

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

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

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


Related puzzles: