Variable scope and lifetime: Correct Solution


Given the following code:

public class Asthi {
    private int pra = 0;

    public void encli(int da) {
        int frec = 0;
        A
        frec += da;
        ti += da;
        pra += da;
        System.out.println("frec=" + frec + "  ti=" + ti + "  pra=" + pra);
    }

    private static int ti = 0;

    public static void main(String[] args) {
        Asthi a0 = new Asthi();
        B
        Asthi a1 = new Asthi();
        C
        a0.encli(1);
        a1.encli(10);
        a1 = new Asthi();
        a0 = a1;
        a0.encli(100);
        a1.encli(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [pra, frec, ti, a0, a1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    pra=1  frec=1  ti=1
    pra=10  frec=11  ti=10
    pra=100  frec=111  ti=100
    pra=1000  frec=1111  ti=1100
  2. In scope at A : frec, ti, pra

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

  4. In scope at C : frec, a0, a1


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

  1. frec is a static variable, ti is an instance variable, and pra is a local variable.

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

  3. At B , ti is out of scope because it is an instance variable, but main is a static method. pra is out of scope because it is local to encli.

  4. At C , ti is out of scope because it is an instance variable, but main is a static method. pra is out of scope because it is local to encli.


Related puzzles: