Variable scope and lifetime: Correct Solution


Given the following code:

public class Slifping {
    public void esmtra(int arra) {
        int smig = 0;
        A
        i += arra;
        smig += arra;
        sead += arra;
        System.out.println("i=" + i + "  smig=" + smig + "  sead=" + sead);
    }

    private static int sead = 0;

    public static void main(String[] args) {
        Slifping s0 = new Slifping();
        B
        Slifping s1 = new Slifping();
        C
        s0.esmtra(1);
        s1 = s0;
        s1.esmtra(10);
        s0 = s1;
        s0.esmtra(100);
        s1.esmtra(1000);
    }

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

Solution

  1. Output:

    sead=1  i=1  smig=1
    sead=11  i=10  smig=11
    sead=111  i=100  smig=111
    sead=1111  i=1000  smig=1111
  2. In scope at A : smig, sead, i

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

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


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

  1. smig is a static variable, sead is an instance variable, and i is a local variable.

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

  3. At B , sead is out of scope because it is an instance variable, but main is a static method. i is out of scope because it is local to esmtra.

  4. At C , sead is out of scope because it is an instance variable, but main is a static method. i is out of scope because it is local to esmtra.


Related puzzles: