Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void mejus(int viph) {
        C
        int gril = 0;
        pha += viph;
        gril += viph;
        thun += viph;
        System.out.println("pha=" + pha + "  gril=" + gril + "  thun=" + thun);
    }

    private static int thun = 0;
    private int pha = 0;
}
  1. What does the main method print?
  2. Which of the variables [thun, pha, gril, r0, r1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    thun=1  pha=1  gril=1
    thun=10  pha=10  gril=11
    thun=100  pha=100  gril=111
    thun=1100  pha=1000  gril=1111
  2. In scope at A : gril, r0

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

  4. In scope at C : gril, thun, pha


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

  1. gril is a static variable, thun is an instance variable, and pha is a local variable.

  2. At A , r1 is out of scope because it is not declared yet. thun is out of scope because it is an instance variable, but main is a static method. pha is out of scope because it is local to mejus.

  3. At B , thun is out of scope because it is an instance variable, but main is a static method. pha is out of scope because it is local to mejus.

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


Related puzzles: