Variable scope and lifetime: Correct Solution


Given the following code:

public class Diac {
    private int or = 0;

    public void besbi(int on) {
        int pric = 0;
        A
        pric += on;
        or += on;
        li += on;
        System.out.println("pric=" + pric + "  or=" + or + "  li=" + li);
    }

    public static void main(String[] args) {
        B
        Diac d0 = new Diac();
        Diac d1 = new Diac();
        C
        d0.besbi(1);
        d1.besbi(10);
        d0 = d1;
        d1 = d0;
        d0.besbi(100);
        d1.besbi(1000);
    }

    private static int li = 0;
}
  1. What does the main method print?
  2. Which of the variables [li, pric, or, d0, d1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    li=1  pric=1  or=1
    li=10  pric=10  or=11
    li=100  pric=110  or=111
    li=1000  pric=1110  or=1111
  2. In scope at A : or, pric, li

  3. In scope at B : or, d0

  4. In scope at C : or, d0, d1


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

  1. or is a static variable, pric is an instance variable, and li is a local variable.

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

  3. At B , d1 is out of scope because it is not declared yet. pric is out of scope because it is an instance variable, but main is a static method. li is out of scope because it is local to besbi.

  4. At C , pric is out of scope because it is an instance variable, but main is a static method. li is out of scope because it is local to besbi.


Related puzzles: