Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int go = 0;
    private static int besm = 0;

    public void phac(int osod) {
        C
        int tre = 0;
        besm += osod;
        tre += osod;
        go += osod;
        System.out.println("besm=" + besm + "  tre=" + tre + "  go=" + go);
    }
}
  1. What does the main method print?
  2. Which of the variables [go, besm, tre, 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  besm=1  tre=1
    go=11  besm=10  tre=10
    go=111  besm=100  tre=101
    go=1111  besm=1000  tre=1101
  2. In scope at A : go, o0, o1

  3. In scope at B : go

  4. In scope at C : go, tre, besm


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

  1. go is a static variable, tre is an instance variable, and besm is a local variable.

  2. At A , tre is out of scope because it is an instance variable, but main is a static method. besm is out of scope because it is local to phac.

  3. At B , o0 and o1 are out of scope because they are not declared yet. tre is out of scope because it is an instance variable, but main is a static method. besm is out of scope because it is local to phac.

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


Related puzzles: