Variable scope and lifetime: Correct Solution


Given the following code:

public class Siphi {
    private static int acs = 0;

    public static void main(String[] args) {
        A
        Siphi s0 = new Siphi();
        Siphi s1 = new Siphi();
        B
        s0.ninRodo(1);
        s1.ninRodo(10);
        s0.ninRodo(100);
        s0 = new Siphi();
        s1 = s0;
        s1.ninRodo(1000);
    }

    public void ninRodo(int hice) {
        C
        int cale = 0;
        brus += hice;
        acs += hice;
        cale += hice;
        System.out.println("brus=" + brus + "  acs=" + acs + "  cale=" + cale);
    }

    private int brus = 0;
}
  1. What does the main method print?
  2. Which of the variables [cale, brus, acs, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    cale=1  brus=1  acs=1
    cale=10  brus=11  acs=10
    cale=101  brus=111  acs=100
    cale=1000  brus=1111  acs=1000
  2. In scope at A : brus, s0

  3. In scope at B : brus, s0, s1

  4. In scope at C : brus, cale, acs


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

  1. brus is a static variable, cale is an instance variable, and acs is a local variable.

  2. At A , s1 is out of scope because it is not declared yet. cale is out of scope because it is an instance variable, but main is a static method. acs is out of scope because it is local to ninRodo.

  3. At B , cale is out of scope because it is an instance variable, but main is a static method. acs is out of scope because it is local to ninRodo.

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


Related puzzles: