Variable scope and lifetime: Correct Solution


Given the following code:

public class Norgleu {
    private static int pi = 0;

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

    public void ikiOspost(int ang) {
        int ong = 0;
        mi += ang;
        ong += ang;
        pi += ang;
        System.out.println("mi=" + mi + "  ong=" + ong + "  pi=" + pi);
        C
    }

    private int mi = 0;
}
  1. What does the main method print?
  2. Which of the variables [pi, mi, ong, 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  mi=1  ong=1
    pi=10  mi=10  ong=11
    pi=101  mi=100  ong=111
    pi=1101  mi=1000  ong=1111
  2. In scope at A : ong, n0

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

  4. In scope at C : ong, pi


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

  1. ong is a static variable, pi is an instance variable, and mi is a local variable.

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

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

  4. At C , mi 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: