Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void naclen(int ee) {
        C
        int a = 0;
        rade += ee;
        or += ee;
        a += ee;
        System.out.println("rade=" + rade + "  or=" + or + "  a=" + a);
    }

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

Solution

  1. Output:

    a=1  rade=1  or=1
    a=11  rade=10  or=10
    a=111  rade=101  or=100
    a=1111  rade=1000  or=1000
  2. In scope at A : a, c0, c1

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

  4. In scope at C : a, rade, or


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

  1. a is a static variable, rade is an instance variable, and or is a local variable.

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

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

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


Related puzzles: