Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void psiss(int prid) {
        int i = 0;
        i += prid;
        ua += prid;
        pren += prid;
        System.out.println("i=" + i + "  ua=" + ua + "  pren=" + pren);
        C
    }

    private int ua = 0;
    private static int pren = 0;
}
  1. What does the main method print?
  2. Which of the variables [pren, i, ua, n0, n1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    pren=1  i=1  ua=1
    pren=10  i=10  ua=11
    pren=100  i=101  ua=111
    pren=1000  i=1000  ua=1111
  2. In scope at A : ua, n0

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

  4. In scope at C : ua, i


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

  1. ua is a static variable, i is an instance variable, and pren is a local variable.

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

  3. At B , i is out of scope because it is an instance variable, but main is a static method. pren is out of scope because it is local to psiss.

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