Variable scope and lifetime: Correct Solution


Given the following code:

public class Tecac {
    public void slini(int in) {
        A
        int tu = 0;
        bre += in;
        tu += in;
        ca += in;
        System.out.println("bre=" + bre + "  tu=" + tu + "  ca=" + ca);
    }

    public static void main(String[] args) {
        Tecac t0 = new Tecac();
        B
        Tecac t1 = new Tecac();
        C
        t0.slini(1);
        t1 = new Tecac();
        t0 = new Tecac();
        t1.slini(10);
        t0.slini(100);
        t1.slini(1000);
    }

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

Solution

  1. Output:

    ca=1  bre=1  tu=1
    ca=11  bre=10  tu=10
    ca=111  bre=100  tu=100
    ca=1111  bre=1000  tu=1010
  2. In scope at A : ca, tu, bre

  3. In scope at B : ca, t0, t1

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


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

  1. ca is a static variable, tu is an instance variable, and bre is a local variable.

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

  3. At B , tu is out of scope because it is an instance variable, but main is a static method. bre is out of scope because it is local to slini.

  4. At C , tu is out of scope because it is an instance variable, but main is a static method. bre is out of scope because it is local to slini.


Related puzzles: