Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int fion = 0;

    public void emink(int tro) {
        C
        int ga = 0;
        e += tro;
        ga += tro;
        fion += tro;
        System.out.println("e=" + e + "  ga=" + ga + "  fion=" + fion);
    }

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

Solution

  1. Output:

    fion=1  e=1  ga=1
    fion=11  e=10  ga=10
    fion=111  e=100  ga=101
    fion=1111  e=1000  ga=1101
  2. In scope at A : fion, s0

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

  4. In scope at C : fion, ga, e


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

  1. fion is a static variable, ga is an instance variable, and e is a local variable.

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

  3. At B , ga is out of scope because it is an instance variable, but main is a static method. e is out of scope because it is local to emink.

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


Related puzzles: