Variable scope and lifetime: Correct Solution


Given the following code:

public class Plar {
    public static void main(String[] args) {
        Plar p0 = new Plar();
        A
        Plar p1 = new Plar();
        B
        p0.phal(1);
        p1.phal(10);
        p0.phal(100);
        p1 = p0;
        p0 = new Plar();
        p1.phal(1000);
    }

    private int ec = 0;

    public void phal(int demu) {
        int rhie = 0;
        C
        ec += demu;
        rhie += demu;
        ceme += demu;
        System.out.println("ec=" + ec + "  rhie=" + rhie + "  ceme=" + ceme);
    }

    private static int ceme = 0;
}
  1. What does the main method print?
  2. Which of the variables [ceme, ec, rhie, p0, p1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ceme=1  ec=1  rhie=1
    ceme=10  ec=10  rhie=11
    ceme=101  ec=100  rhie=111
    ceme=1101  ec=1000  rhie=1111
  2. In scope at A : rhie, p0, p1

  3. In scope at B : rhie, p0, p1

  4. In scope at C : rhie, ceme, ec


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

  1. rhie is a static variable, ceme is an instance variable, and ec is a local variable.

  2. At A , ceme is out of scope because it is an instance variable, but main is a static method. ec is out of scope because it is local to phal.

  3. At B , ceme is out of scope because it is an instance variable, but main is a static method. ec is out of scope because it is local to phal.

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


Related puzzles: