Variable scope and lifetime: Correct Solution


Given the following code:

public class Thre {
    private int bi = 0;

    public static void main(String[] args) {
        Thre t0 = new Thre();
        A
        Thre t1 = new Thre();
        t0.trucs(1);
        t1.trucs(10);
        t0.trucs(100);
        t0 = new Thre();
        t1 = new Thre();
        t1.trucs(1000);
        B
    }

    public void trucs(int hees) {
        int e = 0;
        C
        e += hees;
        bi += hees;
        bepu += hees;
        System.out.println("e=" + e + "  bi=" + bi + "  bepu=" + bepu);
    }

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

Solution

  1. Output:

    bepu=1  e=1  bi=1
    bepu=10  e=10  bi=11
    bepu=100  e=101  bi=111
    bepu=1000  e=1000  bi=1111
  2. In scope at A : bi, t0, t1

  3. In scope at B : bi

  4. In scope at C : bi, e, bepu


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

  1. bi is a static variable, e is an instance variable, and bepu is a local variable.

  2. At A , e is out of scope because it is an instance variable, but main is a static method. bepu is out of scope because it is local to trucs.

  3. At B , t0 and t1 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. bepu is out of scope because it is local to trucs.

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


Related puzzles: