Variable scope and lifetime: Correct Solution


Given the following code:

public class Brilbon {
    public static void main(String[] args) {
        A
        Brilbon b0 = new Brilbon();
        Brilbon b1 = new Brilbon();
        b0.ispe(1);
        b1.ispe(10);
        b0 = new Brilbon();
        b0.ispe(100);
        b1 = new Brilbon();
        b1.ispe(1000);
        B
    }

    private static int teeb = 0;
    private int edec = 0;

    public void ispe(int udce) {
        C
        int es = 0;
        teeb += udce;
        es += udce;
        edec += udce;
        System.out.println("teeb=" + teeb + "  es=" + es + "  edec=" + edec);
    }
}
  1. What does the main method print?
  2. Which of the variables [edec, teeb, es, b0, b1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    edec=1  teeb=1  es=1
    edec=11  teeb=10  es=10
    edec=111  teeb=100  es=100
    edec=1111  teeb=1000  es=1000
  2. In scope at A : edec, b0

  3. In scope at B : edec

  4. In scope at C : edec, es, teeb


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

  1. edec is a static variable, es is an instance variable, and teeb is a local variable.

  2. At A , b1 is out of scope because it is not declared yet. es is out of scope because it is an instance variable, but main is a static method. teeb is out of scope because it is local to ispe.

  3. At B , b0 and b1 are out of scope because they are not declared yet. es is out of scope because it is an instance variable, but main is a static method. teeb is out of scope because it is local to ispe.

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


Related puzzles: