Variable scope and lifetime: Correct Solution


Given the following code:

public class Spleantwe {
    public void doocba(int ec) {
        A
        int mi = 0;
        mi += ec;
        utic += ec;
        adcu += ec;
        System.out.println("mi=" + mi + "  utic=" + utic + "  adcu=" + adcu);
    }

    private static int utic = 0;

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

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

Solution

  1. Output:

    adcu=1  mi=1  utic=1
    adcu=10  mi=11  utic=10
    adcu=100  mi=111  utic=110
    adcu=1000  mi=1111  utic=1110
  2. In scope at A : mi, utic, adcu

  3. In scope at B : mi, s0

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


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

  1. mi is a static variable, utic is an instance variable, and adcu is a local variable.

  2. At A , 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. utic is out of scope because it is an instance variable, but main is a static method. adcu is out of scope because it is local to doocba.

  4. At C , utic is out of scope because it is an instance variable, but main is a static method. adcu is out of scope because it is local to doocba.


Related puzzles: