Variable scope and lifetime: Correct Solution


Given the following code:

public class Bessna {
    private static int phad = 0;
    private int ioss = 0;

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

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

Solution

  1. Output:

    ioss=1  phad=1  chlo=1
    ioss=11  phad=10  chlo=11
    ioss=111  phad=100  chlo=100
    ioss=1111  phad=1000  chlo=1011
  2. In scope at A : ioss, b0

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

  4. In scope at C : ioss, chlo, phad


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

  1. ioss is a static variable, chlo is an instance variable, and phad is a local variable.

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

  3. At B , chlo is out of scope because it is an instance variable, but main is a static method. phad is out of scope because it is local to tred.

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


Related puzzles: