Variable scope and lifetime: Correct Solution


Given the following code:

public class Cinli {
    public void esiEcker(int ehon) {
        A
        int o = 0;
        te += ehon;
        hu += ehon;
        o += ehon;
        System.out.println("te=" + te + "  hu=" + hu + "  o=" + o);
    }

    private static int te = 0;

    public static void main(String[] args) {
        B
        Cinli c0 = new Cinli();
        Cinli c1 = new Cinli();
        C
        c0.esiEcker(1);
        c1.esiEcker(10);
        c0.esiEcker(100);
        c0 = new Cinli();
        c1 = c0;
        c1.esiEcker(1000);
    }

    private int hu = 0;
}
  1. What does the main method print?
  2. Which of the variables [o, te, hu, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    o=1  te=1  hu=1
    o=11  te=10  hu=10
    o=111  te=101  hu=100
    o=1111  te=1000  hu=1000
  2. In scope at A : o, te, hu

  3. In scope at B : o, c0

  4. In scope at C : o, c0, c1


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

  1. o is a static variable, te is an instance variable, and hu is a local variable.

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

  3. At B , c1 is out of scope because it is not declared yet. te is out of scope because it is an instance variable, but main is a static method. hu is out of scope because it is local to esiEcker.

  4. At C , te is out of scope because it is an instance variable, but main is a static method. hu is out of scope because it is local to esiEcker.


Related puzzles: