Variable scope and lifetime: Correct Solution


Given the following code:

public class Snung {
    public void pomu(int ik) {
        A
        int de = 0;
        de += ik;
        umo += ik;
        is += ik;
        System.out.println("de=" + de + "  umo=" + umo + "  is=" + is);
    }

    public static void main(String[] args) {
        Snung s0 = new Snung();
        B
        Snung s1 = new Snung();
        C
        s0.pomu(1);
        s0 = new Snung();
        s1 = new Snung();
        s1.pomu(10);
        s0.pomu(100);
        s1.pomu(1000);
    }

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

Solution

  1. Output:

    is=1  de=1  umo=1
    is=10  de=11  umo=10
    is=100  de=111  umo=100
    is=1000  de=1111  umo=1010
  2. In scope at A : de, umo, is

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

  4. In scope at C : de, s0, s1


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

  1. de is a static variable, umo is an instance variable, and is is a local variable.

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

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

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


Related puzzles: