Variable scope and lifetime: Correct Solution


Given the following code:

public class Poud {
    private static int ad = 0;

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

    private int vinu = 0;

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

Solution

  1. Output:

    ad=1  chel=1  vinu=1
    ad=10  chel=10  vinu=11
    ad=100  chel=101  vinu=111
    ad=1000  chel=1000  vinu=1111
  2. In scope at A : vinu, p0, p1

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

  4. In scope at C : vinu, chel, ad


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

  1. vinu is a static variable, chel is an instance variable, and ad is a local variable.

  2. At A , chel is out of scope because it is an instance variable, but main is a static method. ad is out of scope because it is local to praVef.

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

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


Related puzzles: