Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int cioc = 0;
    private static int pi = 0;

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

Solution

  1. Output:

    pi=1  cecs=1  cioc=1
    pi=10  cecs=10  cioc=11
    pi=100  cecs=100  cioc=111
    pi=1000  cecs=1100  cioc=1111
  2. In scope at A : cioc, n0, n1

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

  4. In scope at C : cioc, cecs, pi


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

  1. cioc is a static variable, cecs is an instance variable, and pi is a local variable.

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

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

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


Related puzzles: