Variable scope and lifetime: Correct Solution


Given the following code:

public class Godmus {
    public void ipra(int in) {
        int ca = 0;
        A
        ca += in;
        sti += in;
        a += in;
        System.out.println("ca=" + ca + "  sti=" + sti + "  a=" + a);
    }

    private int sti = 0;

    public static void main(String[] args) {
        Godmus g0 = new Godmus();
        B
        Godmus g1 = new Godmus();
        C
        g0.ipra(1);
        g1 = new Godmus();
        g0 = g1;
        g1.ipra(10);
        g0.ipra(100);
        g1.ipra(1000);
    }

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

Solution

  1. Output:

    a=1  ca=1  sti=1
    a=10  ca=10  sti=11
    a=100  ca=110  sti=111
    a=1000  ca=1110  sti=1111
  2. In scope at A : sti, ca, a

  3. In scope at B : sti, g0, g1

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


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

  1. sti is a static variable, ca is an instance variable, and a is a local variable.

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

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

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


Related puzzles: