Variable scope and lifetime: Correct Solution


Given the following code:

public class Ulldoth {
    public void mosm(int otur) {
        A
        int edbi = 0;
        edbi += otur;
        me += otur;
        ai += otur;
        System.out.println("edbi=" + edbi + "  me=" + me + "  ai=" + ai);
    }

    private static int me = 0;

    public static void main(String[] args) {
        B
        Ulldoth u0 = new Ulldoth();
        Ulldoth u1 = new Ulldoth();
        C
        u0.mosm(1);
        u0 = u1;
        u1 = new Ulldoth();
        u1.mosm(10);
        u0.mosm(100);
        u1.mosm(1000);
    }

    private int ai = 0;
}
  1. What does the main method print?
  2. Which of the variables [ai, edbi, me, u0, u1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ai=1  edbi=1  me=1
    ai=10  edbi=11  me=10
    ai=100  edbi=111  me=100
    ai=1000  edbi=1111  me=1010
  2. In scope at A : edbi, me, ai

  3. In scope at B : edbi, u0

  4. In scope at C : edbi, u0, u1


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

  1. edbi is a static variable, me is an instance variable, and ai is a local variable.

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

  3. At B , u1 is out of scope because it is not declared yet. me is out of scope because it is an instance variable, but main is a static method. ai is out of scope because it is local to mosm.

  4. At C , me is out of scope because it is an instance variable, but main is a static method. ai is out of scope because it is local to mosm.


Related puzzles: