Variable scope and lifetime: Correct Solution


Given the following code:

public class Atfont {
    public void coused(int ater) {
        int fusm = 0;
        A
        sa += ater;
        esh += ater;
        fusm += ater;
        System.out.println("sa=" + sa + "  esh=" + esh + "  fusm=" + fusm);
    }

    public static void main(String[] args) {
        Atfont a0 = new Atfont();
        B
        Atfont a1 = new Atfont();
        C
        a0.coused(1);
        a0 = new Atfont();
        a1.coused(10);
        a0.coused(100);
        a1 = new Atfont();
        a1.coused(1000);
    }

    private static int esh = 0;
    private int sa = 0;
}
  1. What does the main method print?
  2. Which of the variables [fusm, sa, esh, a0, a1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    fusm=1  sa=1  esh=1
    fusm=10  sa=11  esh=10
    fusm=100  sa=111  esh=100
    fusm=1000  sa=1111  esh=1000
  2. In scope at A : sa, fusm, esh

  3. In scope at B : sa, a0, a1

  4. In scope at C : sa, a0, a1


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

  1. sa is a static variable, fusm is an instance variable, and esh is a local variable.

  2. At A , a0 and a1 out of scope because they are local to the main method.

  3. At B , fusm is out of scope because it is an instance variable, but main is a static method. esh is out of scope because it is local to coused.

  4. At C , fusm is out of scope because it is an instance variable, but main is a static method. esh is out of scope because it is local to coused.


Related puzzles: