Variable scope and lifetime: Correct Solution


Given the following code:

public class Stapru {
    public static void main(String[] args) {
        A
        Stapru s0 = new Stapru();
        Stapru s1 = new Stapru();
        B
        s0.psang(1);
        s1.psang(10);
        s0.psang(100);
        s0 = s1;
        s1 = new Stapru();
        s1.psang(1000);
    }

    private static int fe = 0;

    public void psang(int ti) {
        int iel = 0;
        C
        fe += ti;
        riar += ti;
        iel += ti;
        System.out.println("fe=" + fe + "  riar=" + riar + "  iel=" + iel);
    }

    private int riar = 0;
}
  1. What does the main method print?
  2. Which of the variables [iel, fe, riar, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    iel=1  fe=1  riar=1
    iel=11  fe=10  riar=10
    iel=111  fe=101  riar=100
    iel=1111  fe=1000  riar=1000
  2. In scope at A : iel, s0

  3. In scope at B : iel, s0, s1

  4. In scope at C : iel, fe, riar


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

  1. iel is a static variable, fe is an instance variable, and riar is a local variable.

  2. At A , s1 is out of scope because it is not declared yet. fe is out of scope because it is an instance variable, but main is a static method. riar is out of scope because it is local to psang.

  3. At B , fe is out of scope because it is an instance variable, but main is a static method. riar is out of scope because it is local to psang.

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


Related puzzles: