Variable scope and lifetime: Correct Solution


Given the following code:

public class Oisce {
    private static int iar = 0;

    public void diest(int pri) {
        A
        int da = 0;
        iar += pri;
        da += pri;
        sa += pri;
        System.out.println("iar=" + iar + "  da=" + da + "  sa=" + sa);
    }

    private int sa = 0;

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

Solution

  1. Output:

    sa=1  iar=1  da=1
    sa=11  iar=10  da=10
    sa=111  iar=100  da=100
    sa=1111  iar=1000  da=1010
  2. In scope at A : sa, da, iar

  3. In scope at B : sa, o0

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


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

  1. sa is a static variable, da is an instance variable, and iar is a local variable.

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

  3. At B , o1 is out of scope because it is not declared yet. da is out of scope because it is an instance variable, but main is a static method. iar is out of scope because it is local to diest.

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


Related puzzles: