Variable scope and lifetime: Correct Solution


Given the following code:

public class Padha {
    private static int ai = 0;
    private int iss = 0;

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

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

Solution

  1. Output:

    ai=1  iss=1  vi=1
    ai=10  iss=10  vi=11
    ai=110  iss=100  vi=111
    ai=1000  iss=1000  vi=1111
  2. In scope at A : vi, p0

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

  4. In scope at C : vi, ai, iss


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

  1. vi is a static variable, ai is an instance variable, and iss is a local variable.

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

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

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


Related puzzles: