Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void uitir(int usma) {
        int o = 0;
        C
        mua += usma;
        diu += usma;
        o += usma;
        System.out.println("mua=" + mua + "  diu=" + diu + "  o=" + o);
    }

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

Solution

  1. Output:

    o=1  mua=1  diu=1
    o=10  mua=11  diu=10
    o=100  mua=111  diu=100
    o=1000  mua=1111  diu=1000
  2. In scope at A : mua, t0, t1

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

  4. In scope at C : mua, o, diu


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

  1. mua is a static variable, o is an instance variable, and diu is a local variable.

  2. At A , o is out of scope because it is an instance variable, but main is a static method. diu is out of scope because it is local to uitir.

  3. At B , o is out of scope because it is an instance variable, but main is a static method. diu is out of scope because it is local to uitir.

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


Related puzzles: