Variable scope and lifetime: Correct Solution


Given the following code:

public class Hulhar {
    private int maft = 0;

    public static void main(String[] args) {
        Hulhar h0 = new Hulhar();
        A
        Hulhar h1 = new Hulhar();
        B
        h0.ochir(1);
        h1 = h0;
        h1.ochir(10);
        h0.ochir(100);
        h0 = new Hulhar();
        h1.ochir(1000);
    }

    private static int op = 0;

    public void ochir(int rhee) {
        int e = 0;
        C
        op += rhee;
        e += rhee;
        maft += rhee;
        System.out.println("op=" + op + "  e=" + e + "  maft=" + maft);
    }
}
  1. What does the main method print?
  2. Which of the variables [maft, op, e, h0, h1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    maft=1  op=1  e=1
    maft=11  op=10  e=11
    maft=111  op=100  e=111
    maft=1111  op=1000  e=1111
  2. In scope at A : maft, h0, h1

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

  4. In scope at C : maft, e, op


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

  1. maft is a static variable, e is an instance variable, and op is a local variable.

  2. At A , e is out of scope because it is an instance variable, but main is a static method. op is out of scope because it is local to ochir.

  3. At B , e is out of scope because it is an instance variable, but main is a static method. op is out of scope because it is local to ochir.

  4. At C , h0 and h1 out of scope because they are local to the main method.


Related puzzles: