Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void priEssad(int er) {
        int ia = 0;
        C
        reng += er;
        ia += er;
        cece += er;
        System.out.println("reng=" + reng + "  ia=" + ia + "  cece=" + cece);
    }

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

Solution

  1. Output:

    cece=1  reng=1  ia=1
    cece=11  reng=10  ia=10
    cece=111  reng=100  ia=101
    cece=1111  reng=1000  ia=1000
  2. In scope at A : cece, p0, p1

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

  4. In scope at C : cece, ia, reng


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

  1. cece is a static variable, ia is an instance variable, and reng is a local variable.

  2. At A , ia is out of scope because it is an instance variable, but main is a static method. reng is out of scope because it is local to priEssad.

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

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


Related puzzles: