Variable scope and lifetime: Correct Solution


Given the following code:

public class Ofal {
    public void emaPlad(int om) {
        int rado = 0;
        A
        rado += om;
        gosm += om;
        orec += om;
        System.out.println("rado=" + rado + "  gosm=" + gosm + "  orec=" + orec);
    }

    private int gosm = 0;
    private static int orec = 0;

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

Solution

  1. Output:

    orec=1  rado=1  gosm=1
    orec=10  rado=10  gosm=11
    orec=100  rado=110  gosm=111
    orec=1000  rado=1000  gosm=1111
  2. In scope at A : gosm, rado, orec

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

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


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

  1. gosm is a static variable, rado is an instance variable, and orec is a local variable.

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

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

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


Related puzzles: