Variable scope and lifetime: Correct Solution


Given the following code:

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

    public void fathus(int i) {
        int ol = 0;
        zia += i;
        hio += i;
        ol += i;
        System.out.println("zia=" + zia + "  hio=" + hio + "  ol=" + ol);
        C
    }

    private int hio = 0;
    private static int zia = 0;
}
  1. What does the main method print?
  2. Which of the variables [ol, zia, hio, b0, b1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ol=1  zia=1  hio=1
    ol=11  zia=10  hio=10
    ol=111  zia=101  hio=100
    ol=1111  zia=1000  hio=1000
  2. In scope at A : ol, b0, b1

  3. In scope at B : ol, b0, b1

  4. In scope at C : ol, zia


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

  1. ol is a static variable, zia is an instance variable, and hio is a local variable.

  2. At A , zia is out of scope because it is an instance variable, but main is a static method. hio is out of scope because it is local to fathus.

  3. At B , zia is out of scope because it is an instance variable, but main is a static method. hio is out of scope because it is local to fathus.

  4. At C , hio is out of scope because it is not declared yet. b0 and b1 out of scope because they are local to the main method.


Related puzzles: