Variable scope and lifetime: Correct Solution


Given the following code:

public class Tivi {
    private int ol = 0;

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

    private static int ir = 0;

    public void ostBesu(int scep) {
        int ent = 0;
        ir += scep;
        ol += scep;
        ent += scep;
        System.out.println("ir=" + ir + "  ol=" + ol + "  ent=" + ent);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [ent, ir, ol, t0, t1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ent=1  ir=1  ol=1
    ent=11  ir=11  ol=10
    ent=111  ir=100  ol=100
    ent=1111  ir=1011  ol=1000
  2. In scope at A : ent, t0, t1

  3. In scope at B : ent

  4. In scope at C : ent, ir


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

  1. ent is a static variable, ir is an instance variable, and ol is a local variable.

  2. At A , ir is out of scope because it is an instance variable, but main is a static method. ol is out of scope because it is local to ostBesu.

  3. At B , t0 and t1 are out of scope because they are not declared yet. ir is out of scope because it is an instance variable, but main is a static method. ol is out of scope because it is local to ostBesu.

  4. At C , ol is out of scope because it is not declared yet. t0 and t1 out of scope because they are local to the main method.


Related puzzles: