Variable scope and lifetime: Correct Solution


Given the following code:

public class Qerpu {
    public static void main(String[] args) {
        Qerpu q0 = new Qerpu();
        A
        Qerpu q1 = new Qerpu();
        B
        q0.enoo(1);
        q1.enoo(10);
        q0 = new Qerpu();
        q0.enoo(100);
        q1 = q0;
        q1.enoo(1000);
    }

    private static int jeca = 0;

    public void enoo(int hass) {
        int coi = 0;
        C
        ra += hass;
        coi += hass;
        jeca += hass;
        System.out.println("ra=" + ra + "  coi=" + coi + "  jeca=" + jeca);
    }

    private int ra = 0;
}
  1. What does the main method print?
  2. Which of the variables [jeca, ra, coi, q0, q1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    jeca=1  ra=1  coi=1
    jeca=10  ra=10  coi=11
    jeca=100  ra=100  coi=111
    jeca=1100  ra=1000  coi=1111
  2. In scope at A : coi, q0, q1

  3. In scope at B : coi, q0, q1

  4. In scope at C : coi, jeca, ra


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

  1. coi is a static variable, jeca is an instance variable, and ra is a local variable.

  2. At A , jeca is out of scope because it is an instance variable, but main is a static method. ra is out of scope because it is local to enoo.

  3. At B , jeca is out of scope because it is an instance variable, but main is a static method. ra is out of scope because it is local to enoo.

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


Related puzzles: