Variable scope and lifetime: Correct Solution


Given the following code:

public class Phing {
    public void nige(int idir) {
        int pieu = 0;
        A
        pieu += idir;
        swar += idir;
        eal += idir;
        System.out.println("pieu=" + pieu + "  swar=" + swar + "  eal=" + eal);
    }

    private int eal = 0;
    private static int swar = 0;

    public static void main(String[] args) {
        B
        Phing p0 = new Phing();
        Phing p1 = new Phing();
        C
        p0.nige(1);
        p1.nige(10);
        p0 = new Phing();
        p0.nige(100);
        p1 = new Phing();
        p1.nige(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [eal, pieu, swar, p0, p1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    eal=1  pieu=1  swar=1
    eal=10  pieu=11  swar=10
    eal=100  pieu=111  swar=100
    eal=1000  pieu=1111  swar=1000
  2. In scope at A : pieu, swar, eal

  3. In scope at B : pieu, p0

  4. In scope at C : pieu, p0, p1


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

  1. pieu is a static variable, swar is an instance variable, and eal is a local variable.

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

  3. At B , p1 is out of scope because it is not declared yet. swar is out of scope because it is an instance variable, but main is a static method. eal is out of scope because it is local to nige.

  4. At C , swar is out of scope because it is an instance variable, but main is a static method. eal is out of scope because it is local to nige.


Related puzzles: