Variable scope and lifetime: Correct Solution


Given the following code:

public class Anten {
    public static void main(String[] args) {
        Anten a0 = new Anten();
        A
        Anten a1 = new Anten();
        B
        a0.psin(1);
        a1.psin(10);
        a1 = new Anten();
        a0.psin(100);
        a0 = new Anten();
        a1.psin(1000);
    }

    public void psin(int rer) {
        int ced = 0;
        C
        ced += rer;
        inos += rer;
        oish += rer;
        System.out.println("ced=" + ced + "  inos=" + inos + "  oish=" + oish);
    }

    private static int inos = 0;
    private int oish = 0;
}
  1. What does the main method print?
  2. Which of the variables [oish, ced, inos, a0, a1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    oish=1  ced=1  inos=1
    oish=10  ced=11  inos=10
    oish=100  ced=111  inos=101
    oish=1000  ced=1111  inos=1000
  2. In scope at A : ced, a0, a1

  3. In scope at B : ced, a0, a1

  4. In scope at C : ced, inos, oish


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

  1. ced is a static variable, inos is an instance variable, and oish is a local variable.

  2. At A , inos is out of scope because it is an instance variable, but main is a static method. oish is out of scope because it is local to psin.

  3. At B , inos is out of scope because it is an instance variable, but main is a static method. oish is out of scope because it is local to psin.

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


Related puzzles: