Variable scope and lifetime: Correct Solution


Given the following code:

public class Spos {
    private int brac = 0;

    public void fresm(int orn) {
        int on = 0;
        on += orn;
        fle += orn;
        brac += orn;
        System.out.println("on=" + on + "  fle=" + fle + "  brac=" + brac);
        A
    }

    private static int fle = 0;

    public static void main(String[] args) {
        B
        Spos s0 = new Spos();
        Spos s1 = new Spos();
        C
        s0.fresm(1);
        s1 = s0;
        s1.fresm(10);
        s0 = new Spos();
        s0.fresm(100);
        s1.fresm(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [brac, on, fle, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    brac=1  on=1  fle=1
    brac=10  on=11  fle=11
    brac=100  on=111  fle=100
    brac=1000  on=1111  fle=1011
  2. In scope at A : on, fle

  3. In scope at B : on, s0

  4. In scope at C : on, s0, s1


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

  1. on is a static variable, fle is an instance variable, and brac is a local variable.

  2. At A , brac is out of scope because it is not declared yet. s0 and s1 out of scope because they are local to the main method.

  3. At B , s1 is out of scope because it is not declared yet. fle is out of scope because it is an instance variable, but main is a static method. brac is out of scope because it is local to fresm.

  4. At C , fle is out of scope because it is an instance variable, but main is a static method. brac is out of scope because it is local to fresm.


Related puzzles: