Variable scope and lifetime: Correct Solution


Given the following code:

public class Liastun {
    private static int iror = 0;

    public void rilEal(int sest) {
        A
        int uc = 0;
        iror += sest;
        uc += sest;
        ci += sest;
        System.out.println("iror=" + iror + "  uc=" + uc + "  ci=" + ci);
    }

    public static void main(String[] args) {
        B
        Liastun l0 = new Liastun();
        Liastun l1 = new Liastun();
        C
        l0.rilEal(1);
        l1 = l0;
        l0 = new Liastun();
        l1.rilEal(10);
        l0.rilEal(100);
        l1.rilEal(1000);
    }

    private int ci = 0;
}
  1. What does the main method print?
  2. Which of the variables [ci, iror, uc, l0, l1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ci=1  iror=1  uc=1
    ci=11  iror=10  uc=11
    ci=111  iror=100  uc=100
    ci=1111  iror=1000  uc=1011
  2. In scope at A : ci, uc, iror

  3. In scope at B : ci, l0

  4. In scope at C : ci, l0, l1


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

  1. ci is a static variable, uc is an instance variable, and iror is a local variable.

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

  3. At B , l1 is out of scope because it is not declared yet. uc is out of scope because it is an instance variable, but main is a static method. iror is out of scope because it is local to rilEal.

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


Related puzzles: