Variable scope and lifetime: Correct Solution


Given the following code:

public class Bacas {
    private int iuc = 0;

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

    private static int ou = 0;

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

Solution

  1. Output:

    ca=1  ou=1  iuc=1
    ca=11  ou=10  iuc=10
    ca=111  ou=101  iuc=100
    ca=1111  ou=1101  iuc=1000
  2. In scope at A : ca, b0

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

  4. In scope at C : ca, ou


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

  1. ca is a static variable, ou is an instance variable, and iuc is a local variable.

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

  3. At B , ou is out of scope because it is an instance variable, but main is a static method. iuc is out of scope because it is local to caeCosep.

  4. At C , iuc 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: