Variable scope and lifetime: Correct Solution


Given the following code:

public class EsiSoobu {
    private static int uroc = 0;
    private int qir = 0;

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

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

Solution

  1. Output:

    fous=1  uroc=1  qir=1
    fous=11  uroc=10  qir=10
    fous=111  uroc=100  qir=100
    fous=1111  uroc=1000  qir=1000
  2. In scope at A : fous, e0, e1

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

  4. In scope at C : fous, uroc, qir


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

  1. fous is a static variable, uroc is an instance variable, and qir is a local variable.

  2. At A , uroc is out of scope because it is an instance variable, but main is a static method. qir is out of scope because it is local to nasull.

  3. At B , uroc is out of scope because it is an instance variable, but main is a static method. qir is out of scope because it is local to nasull.

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


Related puzzles: