Variable scope and lifetime: Correct Solution


Given the following code:

public class Peph {
    private static int u = 0;

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

    public void eniChasap(int il) {
        int eesh = 0;
        C
        pa += il;
        u += il;
        eesh += il;
        System.out.println("pa=" + pa + "  u=" + u + "  eesh=" + eesh);
    }

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

Solution

  1. Output:

    eesh=1  pa=1  u=1
    eesh=10  pa=11  u=10
    eesh=101  pa=111  u=100
    eesh=1101  pa=1111  u=1000
  2. In scope at A : pa, p0, p1

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

  4. In scope at C : pa, eesh, u


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

  1. pa is a static variable, eesh is an instance variable, and u is a local variable.

  2. At A , eesh is out of scope because it is an instance variable, but main is a static method. u is out of scope because it is local to eniChasap.

  3. At B , eesh is out of scope because it is an instance variable, but main is a static method. u is out of scope because it is local to eniChasap.

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


Related puzzles: