Variable scope and lifetime: Correct Solution


Given the following code:

public class Vingrho {
    public void rapras(int au) {
        A
        int aeit = 0;
        ebri += au;
        spho += au;
        aeit += au;
        System.out.println("ebri=" + ebri + "  spho=" + spho + "  aeit=" + aeit);
    }

    private static int spho = 0;

    public static void main(String[] args) {
        Vingrho v0 = new Vingrho();
        B
        Vingrho v1 = new Vingrho();
        C
        v0.rapras(1);
        v1 = new Vingrho();
        v1.rapras(10);
        v0.rapras(100);
        v0 = new Vingrho();
        v1.rapras(1000);
    }

    private int ebri = 0;
}
  1. What does the main method print?
  2. Which of the variables [aeit, ebri, spho, v0, v1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    aeit=1  ebri=1  spho=1
    aeit=10  ebri=11  spho=10
    aeit=101  ebri=111  spho=100
    aeit=1010  ebri=1111  spho=1000
  2. In scope at A : ebri, aeit, spho

  3. In scope at B : ebri, v0, v1

  4. In scope at C : ebri, v0, v1


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

  1. ebri is a static variable, aeit is an instance variable, and spho is a local variable.

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

  3. At B , aeit is out of scope because it is an instance variable, but main is a static method. spho is out of scope because it is local to rapras.

  4. At C , aeit is out of scope because it is an instance variable, but main is a static method. spho is out of scope because it is local to rapras.


Related puzzles: