Variable scope and lifetime: Correct Solution


Given the following code:

public class Ontriount {
    private int pe = 0;

    public void qalIal(int ae) {
        A
        int me = 0;
        odge += ae;
        me += ae;
        pe += ae;
        System.out.println("odge=" + odge + "  me=" + me + "  pe=" + pe);
    }

    public static void main(String[] args) {
        Ontriount o0 = new Ontriount();
        B
        Ontriount o1 = new Ontriount();
        C
        o0.qalIal(1);
        o0 = o1;
        o1.qalIal(10);
        o0.qalIal(100);
        o1 = o0;
        o1.qalIal(1000);
    }

    private static int odge = 0;
}
  1. What does the main method print?
  2. Which of the variables [pe, odge, me, o0, o1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    pe=1  odge=1  me=1
    pe=11  odge=10  me=10
    pe=111  odge=100  me=110
    pe=1111  odge=1000  me=1110
  2. In scope at A : pe, me, odge

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

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


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

  1. pe is a static variable, me is an instance variable, and odge is a local variable.

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

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

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


Related puzzles: