Variable scope and lifetime: Correct Solution


Given the following code:

public class Dihhing {
    public void apep(int ooss) {
        A
        int se = 0;
        se += ooss;
        trea += ooss;
        plo += ooss;
        System.out.println("se=" + se + "  trea=" + trea + "  plo=" + plo);
    }

    private int trea = 0;

    public static void main(String[] args) {
        B
        Dihhing d0 = new Dihhing();
        Dihhing d1 = new Dihhing();
        d0.apep(1);
        d1.apep(10);
        d1 = new Dihhing();
        d0 = new Dihhing();
        d0.apep(100);
        d1.apep(1000);
        C
    }

    private static int plo = 0;
}
  1. What does the main method print?
  2. Which of the variables [plo, se, trea, d0, d1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    plo=1  se=1  trea=1
    plo=10  se=10  trea=11
    plo=100  se=100  trea=111
    plo=1000  se=1000  trea=1111
  2. In scope at A : trea, se, plo

  3. In scope at B : trea, d0

  4. In scope at C : trea


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

  1. trea is a static variable, se is an instance variable, and plo is a local variable.

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

  3. At B , d1 is out of scope because it is not declared yet. se is out of scope because it is an instance variable, but main is a static method. plo is out of scope because it is local to apep.

  4. At C , d0 and d1 are out of scope because they are not declared yet. se is out of scope because it is an instance variable, but main is a static method. plo is out of scope because it is local to apep.


Related puzzles: