Variable scope and lifetime: Correct Solution


Given the following code:

public class Sphostvaw {
    private int he = 0;

    public void prew(int ne) {
        int heum = 0;
        A
        heum += ne;
        qe += ne;
        he += ne;
        System.out.println("heum=" + heum + "  qe=" + qe + "  he=" + he);
    }

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

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

Solution

  1. Output:

    he=1  heum=1  qe=1
    he=10  heum=11  qe=10
    he=100  heum=111  qe=110
    he=1000  heum=1111  qe=1110
  2. In scope at A : heum, qe, he

  3. In scope at B : heum, s0

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


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

  1. heum is a static variable, qe is an instance variable, and he 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. qe is out of scope because it is an instance variable, but main is a static method. he is out of scope because it is local to prew.

  4. At C , qe is out of scope because it is an instance variable, but main is a static method. he is out of scope because it is local to prew.


Related puzzles: