Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int ci = 0;
    private static int es = 0;

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

Solution

  1. Output:

    ci=1  e=1  es=1
    ci=10  e=11  es=10
    ci=100  e=111  es=101
    ci=1000  e=1111  es=1000
  2. In scope at A : e, p0

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

  4. In scope at C : e, es


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

  1. e is a static variable, es is an instance variable, and ci is a local variable.

  2. At A , p1 is out of scope because it is not declared yet. es is out of scope because it is an instance variable, but main is a static method. ci is out of scope because it is local to hopor.

  3. At B , es is out of scope because it is an instance variable, but main is a static method. ci is out of scope because it is local to hopor.

  4. At C , ci is out of scope because it is not declared yet. p0 and p1 out of scope because they are local to the main method.


Related puzzles: