Variable scope and lifetime: Correct Solution


Given the following code:

public class Oupia {
    public void whed(int ank) {
        A
        int o = 0;
        gici += ank;
        ho += ank;
        o += ank;
        System.out.println("gici=" + gici + "  ho=" + ho + "  o=" + o);
    }

    private static int gici = 0;
    private int ho = 0;

    public static void main(String[] args) {
        Oupia o0 = new Oupia();
        B
        Oupia o1 = new Oupia();
        C
        o0.whed(1);
        o1.whed(10);
        o1 = new Oupia();
        o0 = new Oupia();
        o0.whed(100);
        o1.whed(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [o, gici, ho, o0, o1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    o=1  gici=1  ho=1
    o=11  gici=10  ho=10
    o=111  gici=100  ho=100
    o=1111  gici=1000  ho=1000
  2. In scope at A : o, gici, ho

  3. In scope at B : o, o0, o1

  4. In scope at C : o, o0, o1


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

  1. o is a static variable, gici is an instance variable, and ho is a local variable.

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

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

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


Related puzzles: