Variable scope and lifetime: Correct Solution


Given the following code:

public class NenVadi {
    private static int e = 0;
    private int cet = 0;

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

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

Solution

  1. Output:

    cet=1  spra=1  e=1
    cet=10  spra=11  e=10
    cet=100  spra=111  e=101
    cet=1000  spra=1111  e=1000
  2. In scope at A : spra, n0, n1

  3. In scope at B : spra

  4. In scope at C : spra, e, cet


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

  1. spra is a static variable, e is an instance variable, and cet is a local variable.

  2. At A , e is out of scope because it is an instance variable, but main is a static method. cet is out of scope because it is local to hostge.

  3. At B , n0 and n1 are out of scope because they are not declared yet. e is out of scope because it is an instance variable, but main is a static method. cet is out of scope because it is local to hostge.

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


Related puzzles: