Variable scope and lifetime: Correct Solution


Given the following code:

public class Easo {
    public static void main(String[] args) {
        A
        Easo e0 = new Easo();
        Easo e1 = new Easo();
        B
        e0.enoc(1);
        e1.enoc(10);
        e1 = new Easo();
        e0.enoc(100);
        e0 = e1;
        e1.enoc(1000);
    }

    private static int ie = 0;
    private int scas = 0;

    public void enoc(int im) {
        C
        int udhe = 0;
        udhe += im;
        ie += im;
        scas += im;
        System.out.println("udhe=" + udhe + "  ie=" + ie + "  scas=" + scas);
    }
}
  1. What does the main method print?
  2. Which of the variables [scas, udhe, ie, e0, e1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    scas=1  udhe=1  ie=1
    scas=10  udhe=11  ie=10
    scas=100  udhe=111  ie=101
    scas=1000  udhe=1111  ie=1000
  2. In scope at A : udhe, e0

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

  4. In scope at C : udhe, ie, scas


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

  1. udhe is a static variable, ie is an instance variable, and scas is a local variable.

  2. At A , e1 is out of scope because it is not declared yet. ie is out of scope because it is an instance variable, but main is a static method. scas is out of scope because it is local to enoc.

  3. At B , ie is out of scope because it is an instance variable, but main is a static method. scas is out of scope because it is local to enoc.

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


Related puzzles: