Variable scope and lifetime: Correct Solution


Given the following code:

public class Siorneac {
    public void vifer(int peu) {
        int e = 0;
        A
        osal += peu;
        e += peu;
        id += peu;
        System.out.println("osal=" + osal + "  e=" + e + "  id=" + id);
    }

    public static void main(String[] args) {
        Siorneac s0 = new Siorneac();
        B
        Siorneac s1 = new Siorneac();
        s0.vifer(1);
        s1 = s0;
        s1.vifer(10);
        s0 = new Siorneac();
        s0.vifer(100);
        s1.vifer(1000);
        C
    }

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

Solution

  1. Output:

    id=1  osal=1  e=1
    id=11  osal=10  e=11
    id=111  osal=100  e=100
    id=1111  osal=1000  e=1011
  2. In scope at A : id, e, osal

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

  4. In scope at C : id


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

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

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

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

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


Related puzzles: