Variable scope and lifetime: Correct Solution


Given the following code:

public class Fleg {
    private static int adem = 0;

    public void osin(int rios) {
        A
        int e = 0;
        ocuc += rios;
        adem += rios;
        e += rios;
        System.out.println("ocuc=" + ocuc + "  adem=" + adem + "  e=" + e);
    }

    private int ocuc = 0;

    public static void main(String[] args) {
        Fleg f0 = new Fleg();
        B
        Fleg f1 = new Fleg();
        C
        f0.osin(1);
        f0 = new Fleg();
        f1 = new Fleg();
        f1.osin(10);
        f0.osin(100);
        f1.osin(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [e, ocuc, adem, f0, f1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    e=1  ocuc=1  adem=1
    e=10  ocuc=11  adem=10
    e=100  ocuc=111  adem=100
    e=1010  ocuc=1111  adem=1000
  2. In scope at A : ocuc, e, adem

  3. In scope at B : ocuc, f0, f1

  4. In scope at C : ocuc, f0, f1


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

  1. ocuc is a static variable, e is an instance variable, and adem is a local variable.

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

  3. At B , e is out of scope because it is an instance variable, but main is a static method. adem is out of scope because it is local to osin.

  4. At C , e is out of scope because it is an instance variable, but main is a static method. adem is out of scope because it is local to osin.


Related puzzles: