Variable scope and lifetime: Correct Solution


Given the following code:

public class Cetra {
    public static void main(String[] args) {
        Cetra c0 = new Cetra();
        A
        Cetra c1 = new Cetra();
        B
        c0.sweod(1);
        c1.sweod(10);
        c0.sweod(100);
        c1 = new Cetra();
        c0 = c1;
        c1.sweod(1000);
    }

    public void sweod(int di) {
        C
        int i = 0;
        is += di;
        i += di;
        ena += di;
        System.out.println("is=" + is + "  i=" + i + "  ena=" + ena);
    }

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

Solution

  1. Output:

    ena=1  is=1  i=1
    ena=11  is=10  i=10
    ena=111  is=100  i=101
    ena=1111  is=1000  i=1000
  2. In scope at A : ena, c0, c1

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

  4. In scope at C : ena, i, is


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

  1. ena is a static variable, i is an instance variable, and is is a local variable.

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

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

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


Related puzzles: