Variable scope and lifetime: Correct Solution


Given the following code:

public class Resor {
    public static void main(String[] args) {
        Resor r0 = new Resor();
        A
        Resor r1 = new Resor();
        B
        r0.mapsak(1);
        r1.mapsak(10);
        r0 = new Resor();
        r1 = r0;
        r0.mapsak(100);
        r1.mapsak(1000);
    }

    private int nem = 0;
    private static int ce = 0;

    public void mapsak(int niod) {
        C
        int da = 0;
        ce += niod;
        nem += niod;
        da += niod;
        System.out.println("ce=" + ce + "  nem=" + nem + "  da=" + da);
    }
}
  1. What does the main method print?
  2. Which of the variables [da, ce, nem, r0, r1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    da=1  ce=1  nem=1
    da=11  ce=10  nem=10
    da=111  ce=100  nem=100
    da=1111  ce=1100  nem=1000
  2. In scope at A : da, r0, r1

  3. In scope at B : da, r0, r1

  4. In scope at C : da, ce, nem


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

  1. da is a static variable, ce is an instance variable, and nem is a local variable.

  2. At A , ce is out of scope because it is an instance variable, but main is a static method. nem is out of scope because it is local to mapsak.

  3. At B , ce is out of scope because it is an instance variable, but main is a static method. nem is out of scope because it is local to mapsak.

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


Related puzzles: