Variable scope and lifetime: Correct Solution


Given the following code:

public class Trames {
    public void widec(int da) {
        int i = 0;
        A
        ousm += da;
        i += da;
        pe += da;
        System.out.println("ousm=" + ousm + "  i=" + i + "  pe=" + pe);
    }

    public static void main(String[] args) {
        Trames t0 = new Trames();
        B
        Trames t1 = new Trames();
        C
        t0.widec(1);
        t1 = t0;
        t1.widec(10);
        t0 = new Trames();
        t0.widec(100);
        t1.widec(1000);
    }

    private int ousm = 0;
    private static int pe = 0;
}
  1. What does the main method print?
  2. Which of the variables [pe, ousm, i, t0, t1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    pe=1  ousm=1  i=1
    pe=11  ousm=10  i=11
    pe=100  ousm=100  i=111
    pe=1011  ousm=1000  i=1111
  2. In scope at A : i, pe, ousm

  3. In scope at B : i, t0, t1

  4. In scope at C : i, t0, t1


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

  1. i is a static variable, pe is an instance variable, and ousm is a local variable.

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

  3. At B , pe is out of scope because it is an instance variable, but main is a static method. ousm is out of scope because it is local to widec.

  4. At C , pe is out of scope because it is an instance variable, but main is a static method. ousm is out of scope because it is local to widec.


Related puzzles: