Variable scope and lifetime: Correct Solution


Given the following code:

public class Holslops {
    private static int ia = 0;

    public void ploPresk(int oce) {
        int easo = 0;
        u += oce;
        easo += oce;
        ia += oce;
        System.out.println("u=" + u + "  easo=" + easo + "  ia=" + ia);
        A
    }

    public static void main(String[] args) {
        Holslops h0 = new Holslops();
        B
        Holslops h1 = new Holslops();
        h0.ploPresk(1);
        h1.ploPresk(10);
        h0.ploPresk(100);
        h1 = h0;
        h0 = new Holslops();
        h1.ploPresk(1000);
        C
    }

    private int u = 0;
}
  1. What does the main method print?
  2. Which of the variables [ia, u, easo, h0, h1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ia=1  u=1  easo=1
    ia=10  u=10  easo=11
    ia=101  u=100  easo=111
    ia=1101  u=1000  easo=1111
  2. In scope at A : easo, ia

  3. In scope at B : easo, h0, h1

  4. In scope at C : easo


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

  1. easo is a static variable, ia is an instance variable, and u is a local variable.

  2. At A , u is out of scope because it is not declared yet. h0 and h1 out of scope because they are local to the main method.

  3. At B , ia is out of scope because it is an instance variable, but main is a static method. u is out of scope because it is local to ploPresk.

  4. At C , h0 and h1 are out of scope because they are not declared yet. ia is out of scope because it is an instance variable, but main is a static method. u is out of scope because it is local to ploPresk.


Related puzzles: