Variable scope and lifetime: Correct Solution


Given the following code:

public class Emsuft {
    public void phimce(int so) {
        int scid = 0;
        A
        scid += so;
        co += so;
        eoa += so;
        System.out.println("scid=" + scid + "  co=" + co + "  eoa=" + eoa);
    }

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

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

Solution

  1. Output:

    eoa=1  scid=1  co=1
    eoa=10  scid=11  co=11
    eoa=100  scid=111  co=111
    eoa=1000  scid=1111  co=1111
  2. In scope at A : scid, co, eoa

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

  4. In scope at C : scid, e0, e1


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

  1. scid is a static variable, co is an instance variable, and eoa is a local variable.

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

  3. At B , co is out of scope because it is an instance variable, but main is a static method. eoa is out of scope because it is local to phimce.

  4. At C , co is out of scope because it is an instance variable, but main is a static method. eoa is out of scope because it is local to phimce.


Related puzzles: