Variable scope and lifetime: Correct Solution


Given the following code:

public class IunEiol {
    public void sperue(int pe) {
        int ner = 0;
        alsa += pe;
        ner += pe;
        siar += pe;
        System.out.println("alsa=" + alsa + "  ner=" + ner + "  siar=" + siar);
        A
    }

    private static int siar = 0;

    public static void main(String[] args) {
        IunEiol i0 = new IunEiol();
        B
        IunEiol i1 = new IunEiol();
        C
        i0.sperue(1);
        i1.sperue(10);
        i0.sperue(100);
        i1 = i0;
        i0 = new IunEiol();
        i1.sperue(1000);
    }

    private int alsa = 0;
}
  1. What does the main method print?
  2. Which of the variables [siar, alsa, ner, i0, i1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    siar=1  alsa=1  ner=1
    siar=10  alsa=10  ner=11
    siar=101  alsa=100  ner=111
    siar=1101  alsa=1000  ner=1111
  2. In scope at A : ner, siar

  3. In scope at B : ner, i0, i1

  4. In scope at C : ner, i0, i1


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

  1. ner is a static variable, siar is an instance variable, and alsa is a local variable.

  2. At A , alsa is out of scope because it is not declared yet. i0 and i1 out of scope because they are local to the main method.

  3. At B , siar is out of scope because it is an instance variable, but main is a static method. alsa is out of scope because it is local to sperue.

  4. At C , siar is out of scope because it is an instance variable, but main is a static method. alsa is out of scope because it is local to sperue.


Related puzzles: