Variable scope and lifetime: Correct Solution


Given the following code:

public class GhaEsci {
    private static int da = 0;
    private int desh = 0;

    public void motat(int aa) {
        A
        int or = 0;
        da += aa;
        desh += aa;
        or += aa;
        System.out.println("da=" + da + "  desh=" + desh + "  or=" + or);
    }

    public static void main(String[] args) {
        B
        GhaEsci g0 = new GhaEsci();
        GhaEsci g1 = new GhaEsci();
        C
        g0.motat(1);
        g0 = g1;
        g1.motat(10);
        g0.motat(100);
        g1 = g0;
        g1.motat(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [or, da, desh, g0, g1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    or=1  da=1  desh=1
    or=11  da=10  desh=10
    or=111  da=110  desh=100
    or=1111  da=1110  desh=1000
  2. In scope at A : or, da, desh

  3. In scope at B : or, g0

  4. In scope at C : or, g0, g1


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

  1. or is a static variable, da is an instance variable, and desh is a local variable.

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

  3. At B , g1 is out of scope because it is not declared yet. da is out of scope because it is an instance variable, but main is a static method. desh is out of scope because it is local to motat.

  4. At C , da is out of scope because it is an instance variable, but main is a static method. desh is out of scope because it is local to motat.


Related puzzles: