Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int ru = 0;
    private static int sian = 0;

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

Solution

  1. Output:

    ru=1  ca=1  sian=1
    ru=10  ca=11  sian=10
    ru=100  ca=111  sian=100
    ru=1000  ca=1111  sian=1100
  2. In scope at A : ca, b0

  3. In scope at B : ca

  4. In scope at C : ca, sian, ru


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

  1. ca is a static variable, sian is an instance variable, and ru is a local variable.

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

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

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


Related puzzles: