Variable scope and lifetime: Correct Solution


Given the following code:

public class Oismud {
    private static int ious = 0;

    public static void main(String[] args) {
        A
        Oismud o0 = new Oismud();
        Oismud o1 = new Oismud();
        o0.fasur(1);
        o1 = new Oismud();
        o1.fasur(10);
        o0 = o1;
        o0.fasur(100);
        o1.fasur(1000);
        B
    }

    public void fasur(int es) {
        int e = 0;
        phai += es;
        ious += es;
        e += es;
        System.out.println("phai=" + phai + "  ious=" + ious + "  e=" + e);
        C
    }

    private int phai = 0;
}
  1. What does the main method print?
  2. Which of the variables [e, phai, ious, o0, o1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    e=1  phai=1  ious=1
    e=10  phai=11  ious=10
    e=110  phai=111  ious=100
    e=1110  phai=1111  ious=1000
  2. In scope at A : phai, o0

  3. In scope at B : phai

  4. In scope at C : phai, e


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

  1. phai is a static variable, e is an instance variable, and ious is a local variable.

  2. At A , o1 is out of scope because it is not declared yet. e is out of scope because it is an instance variable, but main is a static method. ious is out of scope because it is local to fasur.

  3. At B , o0 and o1 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. ious is out of scope because it is local to fasur.

  4. At C , ious is out of scope because it is not declared yet. o0 and o1 out of scope because they are local to the main method.


Related puzzles: