Variable scope and lifetime: Correct Solution


Given the following code:

public class Psoor {
    public void wreGusean(int as) {
        int acma = 0;
        A
        choi += as;
        acma += as;
        it += as;
        System.out.println("choi=" + choi + "  acma=" + acma + "  it=" + it);
    }

    private int choi = 0;

    public static void main(String[] args) {
        Psoor p0 = new Psoor();
        B
        Psoor p1 = new Psoor();
        p0.wreGusean(1);
        p1.wreGusean(10);
        p0 = p1;
        p0.wreGusean(100);
        p1 = p0;
        p1.wreGusean(1000);
        C
    }

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

Solution

  1. Output:

    it=1  choi=1  acma=1
    it=10  choi=10  acma=11
    it=110  choi=100  acma=111
    it=1110  choi=1000  acma=1111
  2. In scope at A : acma, it, choi

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

  4. In scope at C : acma


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

  1. acma is a static variable, it is an instance variable, and choi is a local variable.

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

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

  4. At C , p0 and p1 are out of scope because they are not declared yet. it is out of scope because it is an instance variable, but main is a static method. choi is out of scope because it is local to wreGusean.


Related puzzles: