Variable scope and lifetime: Correct Solution


Given the following code:

public class RilHonse {
    public void dicUnt(int o) {
        A
        int u = 0;
        miom += o;
        u += o;
        ir += o;
        System.out.println("miom=" + miom + "  u=" + u + "  ir=" + ir);
    }

    private static int ir = 0;
    private int miom = 0;

    public static void main(String[] args) {
        B
        RilHonse r0 = new RilHonse();
        RilHonse r1 = new RilHonse();
        C
        r0.dicUnt(1);
        r1 = new RilHonse();
        r1.dicUnt(10);
        r0 = r1;
        r0.dicUnt(100);
        r1.dicUnt(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [ir, miom, u, r0, r1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ir=1  miom=1  u=1
    ir=10  miom=10  u=11
    ir=110  miom=100  u=111
    ir=1110  miom=1000  u=1111
  2. In scope at A : u, ir, miom

  3. In scope at B : u, r0

  4. In scope at C : u, r0, r1


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

  1. u is a static variable, ir is an instance variable, and miom is a local variable.

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

  3. At B , r1 is out of scope because it is not declared yet. ir is out of scope because it is an instance variable, but main is a static method. miom is out of scope because it is local to dicUnt.

  4. At C , ir is out of scope because it is an instance variable, but main is a static method. miom is out of scope because it is local to dicUnt.


Related puzzles: