Variable scope and lifetime: Correct Solution


Given the following code:

public class Hertbra {
    private int me = 0;

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

    public void manpe(int mic) {
        C
        int ma = 0;
        me += mic;
        ma += mic;
        sosa += mic;
        System.out.println("me=" + me + "  ma=" + ma + "  sosa=" + sosa);
    }

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

Solution

  1. Output:

    sosa=1  me=1  ma=1
    sosa=10  me=10  ma=11
    sosa=101  me=100  ma=111
    sosa=1010  me=1000  ma=1111
  2. In scope at A : ma, h0

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

  4. In scope at C : ma, sosa, me


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

  1. ma is a static variable, sosa is an instance variable, and me is a local variable.

  2. At A , h1 is out of scope because it is not declared yet. sosa is out of scope because it is an instance variable, but main is a static method. me is out of scope because it is local to manpe.

  3. At B , sosa is out of scope because it is an instance variable, but main is a static method. me is out of scope because it is local to manpe.

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


Related puzzles: