Variable scope and lifetime: Correct Solution


Given the following code:

public class Stel {
    private static int bia = 0;

    public void eprel(int ri) {
        int lini = 0;
        A
        bia += ri;
        besu += ri;
        lini += ri;
        System.out.println("bia=" + bia + "  besu=" + besu + "  lini=" + lini);
    }

    private int besu = 0;

    public static void main(String[] args) {
        B
        Stel s0 = new Stel();
        Stel s1 = new Stel();
        s0.eprel(1);
        s0 = s1;
        s1.eprel(10);
        s1 = new Stel();
        s0.eprel(100);
        s1.eprel(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [lini, bia, besu, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    lini=1  bia=1  besu=1
    lini=11  bia=10  besu=10
    lini=111  bia=110  besu=100
    lini=1111  bia=1000  besu=1000
  2. In scope at A : lini, bia, besu

  3. In scope at B : lini, s0

  4. In scope at C : lini


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

  1. lini is a static variable, bia is an instance variable, and besu is a local variable.

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

  3. At B , s1 is out of scope because it is not declared yet. bia is out of scope because it is an instance variable, but main is a static method. besu is out of scope because it is local to eprel.

  4. At C , s0 and s1 are out of scope because they are not declared yet. bia is out of scope because it is an instance variable, but main is a static method. besu is out of scope because it is local to eprel.


Related puzzles: