Variable scope and lifetime: Correct Solution


Given the following code:

public class Beqic {
    private static int xess = 0;

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

    private int iscu = 0;

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

Solution

  1. Output:

    iscu=1  xess=1  thoc=1
    iscu=11  xess=10  thoc=11
    iscu=111  xess=100  thoc=111
    iscu=1111  xess=1000  thoc=1111
  2. In scope at A : iscu, b0

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

  4. In scope at C : iscu, thoc, xess


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

  1. iscu is a static variable, thoc is an instance variable, and xess is a local variable.

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

  3. At B , thoc is out of scope because it is an instance variable, but main is a static method. xess is out of scope because it is local to indce.

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


Related puzzles: