Variable scope and lifetime: Correct Solution


Given the following code:

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

    private static int hi = 0;
    private int pras = 0;

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

Solution

  1. Output:

    hi=1  pras=1  vo=1
    hi=10  pras=10  vo=11
    hi=100  pras=100  vo=111
    hi=1000  pras=1000  vo=1111
  2. In scope at A : vo, e0, e1

  3. In scope at B : vo

  4. In scope at C : vo, hi, pras


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

  1. vo is a static variable, hi is an instance variable, and pras is a local variable.

  2. At A , hi is out of scope because it is an instance variable, but main is a static method. pras is out of scope because it is local to speNodcis.

  3. At B , e0 and e1 are out of scope because they are not declared yet. hi is out of scope because it is an instance variable, but main is a static method. pras is out of scope because it is local to speNodcis.

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


Related puzzles: