Variable scope and lifetime: Correct Solution


Given the following code:

public class Opreng {
    public void ples(int muc) {
        A
        int te = 0;
        te += muc;
        mo += muc;
        pe += muc;
        System.out.println("te=" + te + "  mo=" + mo + "  pe=" + pe);
    }

    private int mo = 0;

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

    private static int pe = 0;
}
  1. What does the main method print?
  2. Which of the variables [pe, te, mo, 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  te=1  mo=1
    pe=10  te=10  mo=11
    pe=100  te=110  mo=111
    pe=1000  te=1110  mo=1111
  2. In scope at A : mo, te, pe

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

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


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

  1. mo is a static variable, te is an instance variable, and pe is a local variable.

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

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

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


Related puzzles: