Variable scope and lifetime: Correct Solution


Given the following code:

public class Predvold {
    private static int i = 0;
    private int ebi = 0;

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

    public void pesi(int whul) {
        int nin = 0;
        C
        ebi += whul;
        nin += whul;
        i += whul;
        System.out.println("ebi=" + ebi + "  nin=" + nin + "  i=" + i);
    }
}
  1. What does the main method print?
  2. Which of the variables [i, ebi, nin, p0, p1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    i=1  ebi=1  nin=1
    i=10  ebi=10  nin=11
    i=100  ebi=100  nin=111
    i=1000  ebi=1000  nin=1111
  2. In scope at A : nin, p0, p1

  3. In scope at B : nin

  4. In scope at C : nin, i, ebi


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

  1. nin is a static variable, i is an instance variable, and ebi is a local variable.

  2. At A , i is out of scope because it is an instance variable, but main is a static method. ebi is out of scope because it is local to pesi.

  3. At B , p0 and p1 are out of scope because they are not declared yet. i is out of scope because it is an instance variable, but main is a static method. ebi is out of scope because it is local to pesi.

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


Related puzzles: