Variable scope and lifetime: Correct Solution


Given the following code:

public class Niscrooss {
    private int vo = 0;

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

    public void ingi(int hu) {
        int irhe = 0;
        vo += hu;
        na += hu;
        irhe += hu;
        System.out.println("vo=" + vo + "  na=" + na + "  irhe=" + irhe);
        C
    }

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

Solution

  1. Output:

    irhe=1  vo=1  na=1
    irhe=10  vo=11  na=10
    irhe=110  vo=111  na=100
    irhe=1110  vo=1111  na=1000
  2. In scope at A : vo, n0, n1

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

  4. In scope at C : vo, irhe


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

  1. vo is a static variable, irhe is an instance variable, and na is a local variable.

  2. At A , irhe is out of scope because it is an instance variable, but main is a static method. na is out of scope because it is local to ingi.

  3. At B , irhe is out of scope because it is an instance variable, but main is a static method. na is out of scope because it is local to ingi.

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