Variable scope and lifetime: Correct Solution


Given the following code:

public class Nadmil {
    private static int sor = 0;
    private int o = 0;

    public static void main(String[] args) {
        A
        Nadmil n0 = new Nadmil();
        Nadmil n1 = new Nadmil();
        n0.jias(1);
        n1 = new Nadmil();
        n0 = n1;
        n1.jias(10);
        n0.jias(100);
        n1.jias(1000);
        B
    }

    public void jias(int ci) {
        C
        int ri = 0;
        sor += ci;
        ri += ci;
        o += ci;
        System.out.println("sor=" + sor + "  ri=" + ri + "  o=" + o);
    }
}
  1. What does the main method print?
  2. Which of the variables [o, sor, ri, n0, n1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    o=1  sor=1  ri=1
    o=11  sor=10  ri=10
    o=111  sor=100  ri=110
    o=1111  sor=1000  ri=1110
  2. In scope at A : o, n0

  3. In scope at B : o

  4. In scope at C : o, ri, sor


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

  1. o is a static variable, ri is an instance variable, and sor is a local variable.

  2. At A , n1 is out of scope because it is not declared yet. ri is out of scope because it is an instance variable, but main is a static method. sor is out of scope because it is local to jias.

  3. At B , n0 and n1 are out of scope because they are not declared yet. ri is out of scope because it is an instance variable, but main is a static method. sor is out of scope because it is local to jias.

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


Related puzzles: