Variable scope and lifetime: Correct Solution


Given the following code:

public class Easliar {
    private static int mo = 0;

    public void eiar(int pel) {
        A
        int cith = 0;
        cith += pel;
        splo += pel;
        mo += pel;
        System.out.println("cith=" + cith + "  splo=" + splo + "  mo=" + mo);
    }

    public static void main(String[] args) {
        Easliar e0 = new Easliar();
        B
        Easliar e1 = new Easliar();
        e0.eiar(1);
        e0 = new Easliar();
        e1.eiar(10);
        e0.eiar(100);
        e1 = e0;
        e1.eiar(1000);
        C
    }

    private int splo = 0;
}
  1. What does the main method print?
  2. Which of the variables [mo, cith, splo, e0, e1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    mo=1  cith=1  splo=1
    mo=10  cith=10  splo=11
    mo=100  cith=100  splo=111
    mo=1000  cith=1100  splo=1111
  2. In scope at A : splo, cith, mo

  3. In scope at B : splo, e0, e1

  4. In scope at C : splo


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

  1. splo is a static variable, cith is an instance variable, and mo is a local variable.

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

  3. At B , cith is out of scope because it is an instance variable, but main is a static method. mo is out of scope because it is local to eiar.

  4. At C , e0 and e1 are out of scope because they are not declared yet. cith is out of scope because it is an instance variable, but main is a static method. mo is out of scope because it is local to eiar.


Related puzzles: