Variable scope and lifetime: Correct Solution


Given the following code:

public class Chresm {
    public static void main(String[] args) {
        A
        Chresm c0 = new Chresm();
        Chresm c1 = new Chresm();
        B
        c0.steo(1);
        c1 = new Chresm();
        c1.steo(10);
        c0 = new Chresm();
        c0.steo(100);
        c1.steo(1000);
    }

    private int pa = 0;

    public void steo(int prou) {
        int ent = 0;
        C
        an += prou;
        pa += prou;
        ent += prou;
        System.out.println("an=" + an + "  pa=" + pa + "  ent=" + ent);
    }

    private static int an = 0;
}
  1. What does the main method print?
  2. Which of the variables [ent, an, pa, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ent=1  an=1  pa=1
    ent=11  an=10  pa=10
    ent=111  an=100  pa=100
    ent=1111  an=1010  pa=1000
  2. In scope at A : ent, c0

  3. In scope at B : ent, c0, c1

  4. In scope at C : ent, an, pa


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

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

  2. At A , c1 is out of scope because it is not declared yet. an is out of scope because it is an instance variable, but main is a static method. pa is out of scope because it is local to steo.

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

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


Related puzzles: