Variable scope and lifetime: Correct Solution


Given the following code:

public class Zecchral {
    private static int imo = 0;

    public static void main(String[] args) {
        Zecchral z0 = new Zecchral();
        A
        Zecchral z1 = new Zecchral();
        z0.pifKomarm(1);
        z1.pifKomarm(10);
        z0.pifKomarm(100);
        z0 = new Zecchral();
        z1 = z0;
        z1.pifKomarm(1000);
        B
    }

    public void pifKomarm(int ba) {
        C
        int nung = 0;
        i += ba;
        imo += ba;
        nung += ba;
        System.out.println("i=" + i + "  imo=" + imo + "  nung=" + nung);
    }

    private int i = 0;
}
  1. What does the main method print?
  2. Which of the variables [nung, i, imo, z0, z1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    nung=1  i=1  imo=1
    nung=10  i=11  imo=10
    nung=101  i=111  imo=100
    nung=1000  i=1111  imo=1000
  2. In scope at A : i, z0, z1

  3. In scope at B : i

  4. In scope at C : i, nung, imo


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

  1. i is a static variable, nung is an instance variable, and imo is a local variable.

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

  3. At B , z0 and z1 are out of scope because they are not declared yet. nung is out of scope because it is an instance variable, but main is a static method. imo is out of scope because it is local to pifKomarm.

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


Related puzzles: