Variable scope and lifetime: Correct Solution


Given the following code:

public class OngChongcid {
    private int go = 0;

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

    private static int oss = 0;

    public void osmi(int os) {
        C
        int he = 0;
        he += os;
        oss += os;
        go += os;
        System.out.println("he=" + he + "  oss=" + oss + "  go=" + go);
    }
}
  1. What does the main method print?
  2. Which of the variables [go, he, oss, o0, o1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    go=1  he=1  oss=1
    go=10  he=11  oss=10
    go=100  he=111  oss=110
    go=1000  he=1111  oss=1110
  2. In scope at A : he, o0

  3. In scope at B : he, o0, o1

  4. In scope at C : he, oss, go


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

  1. he is a static variable, oss is an instance variable, and go is a local variable.

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

  3. At B , oss is out of scope because it is an instance variable, but main is a static method. go is out of scope because it is local to osmi.

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


Related puzzles: