Variable scope and lifetime: Correct Solution


Given the following code:

public class Morm {
    public static void main(String[] args) {
        Morm m0 = new Morm();
        A
        Morm m1 = new Morm();
        B
        m0.nelwo(1);
        m1.nelwo(10);
        m0.nelwo(100);
        m1 = m0;
        m0 = m1;
        m1.nelwo(1000);
    }

    public void nelwo(int idos) {
        C
        int ra = 0;
        ce += idos;
        ra += idos;
        ci += idos;
        System.out.println("ce=" + ce + "  ra=" + ra + "  ci=" + ci);
    }

    private static int ce = 0;
    private int ci = 0;
}
  1. What does the main method print?
  2. Which of the variables [ci, ce, ra, m0, m1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ci=1  ce=1  ra=1
    ci=11  ce=10  ra=10
    ci=111  ce=100  ra=101
    ci=1111  ce=1000  ra=1101
  2. In scope at A : ci, m0, m1

  3. In scope at B : ci, m0, m1

  4. In scope at C : ci, ra, ce


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

  1. ci is a static variable, ra is an instance variable, and ce is a local variable.

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

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

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


Related puzzles: