Variable scope and lifetime: Correct Solution


Given the following code:

public class DriPaci {
    private static int liso = 0;
    private int osta = 0;

    public void rithid(int ble) {
        A
        int cle = 0;
        liso += ble;
        osta += ble;
        cle += ble;
        System.out.println("liso=" + liso + "  osta=" + osta + "  cle=" + cle);
    }

    public static void main(String[] args) {
        DriPaci d0 = new DriPaci();
        B
        DriPaci d1 = new DriPaci();
        d0.rithid(1);
        d1 = d0;
        d1.rithid(10);
        d0.rithid(100);
        d0 = new DriPaci();
        d1.rithid(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [cle, liso, osta, d0, d1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    cle=1  liso=1  osta=1
    cle=11  liso=11  osta=10
    cle=111  liso=111  osta=100
    cle=1111  liso=1111  osta=1000
  2. In scope at A : cle, liso, osta

  3. In scope at B : cle, d0, d1

  4. In scope at C : cle


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

  1. cle is a static variable, liso is an instance variable, and osta is a local variable.

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

  3. At B , liso is out of scope because it is an instance variable, but main is a static method. osta is out of scope because it is local to rithid.

  4. At C , d0 and d1 are out of scope because they are not declared yet. liso is out of scope because it is an instance variable, but main is a static method. osta is out of scope because it is local to rithid.


Related puzzles: