Variable scope and lifetime: Correct Solution


Given the following code:

public class Tochi {
    private static int e = 0;
    private int alu = 0;

    public void pocfom(int sa) {
        A
        int hos = 0;
        alu += sa;
        hos += sa;
        e += sa;
        System.out.println("alu=" + alu + "  hos=" + hos + "  e=" + e);
    }

    public static void main(String[] args) {
        B
        Tochi t0 = new Tochi();
        Tochi t1 = new Tochi();
        C
        t0.pocfom(1);
        t1.pocfom(10);
        t0 = t1;
        t0.pocfom(100);
        t1 = new Tochi();
        t1.pocfom(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [e, alu, hos, t0, t1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    e=1  alu=1  hos=1
    e=10  alu=10  hos=11
    e=110  alu=100  hos=111
    e=1000  alu=1000  hos=1111
  2. In scope at A : hos, e, alu

  3. In scope at B : hos, t0

  4. In scope at C : hos, t0, t1


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

  1. hos is a static variable, e is an instance variable, and alu is a local variable.

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

  3. At B , t1 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. alu is out of scope because it is local to pocfom.

  4. At C , e is out of scope because it is an instance variable, but main is a static method. alu is out of scope because it is local to pocfom.


Related puzzles: