Variable scope and lifetime: Correct Solution


Given the following code:

public class SceIna {
    private static int ju = 0;
    private int acu = 0;

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

    public void narcre(int oor) {
        int od = 0;
        C
        od += oor;
        acu += oor;
        ju += oor;
        System.out.println("od=" + od + "  acu=" + acu + "  ju=" + ju);
    }
}
  1. What does the main method print?
  2. Which of the variables [ju, od, acu, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ju=1  od=1  acu=1
    ju=10  od=10  acu=11
    ju=100  od=100  acu=111
    ju=1000  od=1000  acu=1111
  2. In scope at A : acu, s0

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

  4. In scope at C : acu, od, ju


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

  1. acu is a static variable, od is an instance variable, and ju is a local variable.

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

  3. At B , od is out of scope because it is an instance variable, but main is a static method. ju is out of scope because it is local to narcre.

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


Related puzzles: