Variable scope and lifetime: Correct Solution


Given the following code:

public class RouArphan {
    private static int vi = 0;

    public void hiaie(int tre) {
        A
        int i = 0;
        vi += tre;
        i += tre;
        uem += tre;
        System.out.println("vi=" + vi + "  i=" + i + "  uem=" + uem);
    }

    public static void main(String[] args) {
        RouArphan r0 = new RouArphan();
        B
        RouArphan r1 = new RouArphan();
        C
        r0.hiaie(1);
        r0 = new RouArphan();
        r1.hiaie(10);
        r1 = new RouArphan();
        r0.hiaie(100);
        r1.hiaie(1000);
    }

    private int uem = 0;
}
  1. What does the main method print?
  2. Which of the variables [uem, vi, i, r0, r1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    uem=1  vi=1  i=1
    uem=11  vi=10  i=10
    uem=111  vi=100  i=100
    uem=1111  vi=1000  i=1000
  2. In scope at A : uem, i, vi

  3. In scope at B : uem, r0, r1

  4. In scope at C : uem, r0, r1


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

  1. uem is a static variable, i is an instance variable, and vi is a local variable.

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

  3. At B , i is out of scope because it is an instance variable, but main is a static method. vi is out of scope because it is local to hiaie.

  4. At C , i is out of scope because it is an instance variable, but main is a static method. vi is out of scope because it is local to hiaie.


Related puzzles: