Variable scope and lifetime: Correct Solution


Given the following code:

public class Vavuch {
    public void icatt(int uas) {
        int elir = 0;
        i += uas;
        elir += uas;
        piol += uas;
        System.out.println("i=" + i + "  elir=" + elir + "  piol=" + piol);
        A
    }

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

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

Solution

  1. Output:

    piol=1  i=1  elir=1
    piol=11  i=10  elir=10
    piol=111  i=100  elir=100
    piol=1111  i=1000  elir=1001
  2. In scope at A : piol, elir

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

  4. In scope at C : piol


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

  1. piol is a static variable, elir is an instance variable, and i is a local variable.

  2. At A , i is out of scope because it is not declared yet. v0 and v1 out of scope because they are local to the main method.

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

  4. At C , v0 and v1 are out of scope because they are not declared yet. elir is out of scope because it is an instance variable, but main is a static method. i is out of scope because it is local to icatt.


Related puzzles: