Variable scope and lifetime: Correct Solution


Given the following code:

public class Glengsas {
    public static void main(String[] args) {
        Glengsas g0 = new Glengsas();
        A
        Glengsas g1 = new Glengsas();
        g0.tict(1);
        g0 = g1;
        g1.tict(10);
        g1 = new Glengsas();
        g0.tict(100);
        g1.tict(1000);
        B
    }

    private static int an = 0;

    public void tict(int a) {
        int amo = 0;
        amo += a;
        an += a;
        no += a;
        System.out.println("amo=" + amo + "  an=" + an + "  no=" + no);
        C
    }

    private int no = 0;
}
  1. What does the main method print?
  2. Which of the variables [no, amo, an, g0, g1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    no=1  amo=1  an=1
    no=10  amo=11  an=10
    no=100  amo=111  an=110
    no=1000  amo=1111  an=1000
  2. In scope at A : amo, g0, g1

  3. In scope at B : amo

  4. In scope at C : amo, an


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

  1. amo is a static variable, an is an instance variable, and no is a local variable.

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

  3. At B , g0 and g1 are out of scope because they are not declared yet. an is out of scope because it is an instance variable, but main is a static method. no is out of scope because it is local to tict.

  4. At C , no is out of scope because it is not declared yet. g0 and g1 out of scope because they are local to the main method.


Related puzzles: