Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int zo = 0;

    public void caling(int en) {
        int i = 0;
        C
        oong += en;
        i += en;
        zo += en;
        System.out.println("oong=" + oong + "  i=" + i + "  zo=" + zo);
    }

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

Solution

  1. Output:

    zo=1  oong=1  i=1
    zo=10  oong=10  i=11
    zo=101  oong=100  i=111
    zo=1000  oong=1000  i=1111
  2. In scope at A : i, s0

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

  4. In scope at C : i, zo, oong


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

  1. i is a static variable, zo is an instance variable, and oong is a local variable.

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

  3. At B , zo is out of scope because it is an instance variable, but main is a static method. oong is out of scope because it is local to caling.

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


Related puzzles: