Variable scope and lifetime: Correct Solution


Given the following code:

public class Nackcad {
    public static void main(String[] args) {
        A
        Nackcad n0 = new Nackcad();
        Nackcad n1 = new Nackcad();
        B
        n0.asho(1);
        n1.asho(10);
        n0 = new Nackcad();
        n0.asho(100);
        n1 = new Nackcad();
        n1.asho(1000);
    }

    private static int rac = 0;
    private int stea = 0;

    public void asho(int regh) {
        int e = 0;
        e += regh;
        rac += regh;
        stea += regh;
        System.out.println("e=" + e + "  rac=" + rac + "  stea=" + stea);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [stea, e, rac, n0, n1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    stea=1  e=1  rac=1
    stea=10  e=11  rac=10
    stea=100  e=111  rac=100
    stea=1000  e=1111  rac=1000
  2. In scope at A : e, n0

  3. In scope at B : e, n0, n1

  4. In scope at C : e, rac


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

  1. e is a static variable, rac is an instance variable, and stea is a local variable.

  2. At A , n1 is out of scope because it is not declared yet. rac is out of scope because it is an instance variable, but main is a static method. stea is out of scope because it is local to asho.

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

  4. At C , stea is out of scope because it is not declared yet. n0 and n1 out of scope because they are local to the main method.


Related puzzles: