Variable scope and lifetime: Correct Solution


Given the following code:

public class Cifled {
    public void eong(int le) {
        A
        int cies = 0;
        e += le;
        cies += le;
        ro += le;
        System.out.println("e=" + e + "  cies=" + cies + "  ro=" + ro);
    }

    private int e = 0;

    public static void main(String[] args) {
        Cifled c0 = new Cifled();
        B
        Cifled c1 = new Cifled();
        c0.eong(1);
        c1.eong(10);
        c0 = new Cifled();
        c0.eong(100);
        c1 = new Cifled();
        c1.eong(1000);
        C
    }

    private static int ro = 0;
}
  1. What does the main method print?
  2. Which of the variables [ro, e, cies, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ro=1  e=1  cies=1
    ro=10  e=10  cies=11
    ro=100  e=100  cies=111
    ro=1000  e=1000  cies=1111
  2. In scope at A : cies, ro, e

  3. In scope at B : cies, c0, c1

  4. In scope at C : cies


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

  1. cies is a static variable, ro is an instance variable, and e is a local variable.

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

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

  4. At C , c0 and c1 are out of scope because they are not declared yet. ro is out of scope because it is an instance variable, but main is a static method. e is out of scope because it is local to eong.


Related puzzles: