Variable scope and lifetime: Correct Solution


Given the following code:

public class CerElmo {
    private static int qir = 0;

    public void uplo(int re) {
        A
        int es = 0;
        qir += re;
        os += re;
        es += re;
        System.out.println("qir=" + qir + "  os=" + os + "  es=" + es);
    }

    private int os = 0;

    public static void main(String[] args) {
        B
        CerElmo c0 = new CerElmo();
        CerElmo c1 = new CerElmo();
        c0.uplo(1);
        c1.uplo(10);
        c0.uplo(100);
        c1 = new CerElmo();
        c0 = new CerElmo();
        c1.uplo(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [es, qir, os, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    es=1  qir=1  os=1
    es=11  qir=10  os=10
    es=111  qir=101  os=100
    es=1111  qir=1000  os=1000
  2. In scope at A : es, qir, os

  3. In scope at B : es, c0

  4. In scope at C : es


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

  1. es is a static variable, qir is an instance variable, and os is a local variable.

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

  3. At B , c1 is out of scope because it is not declared yet. qir is out of scope because it is an instance variable, but main is a static method. os is out of scope because it is local to uplo.

  4. At C , c0 and c1 are out of scope because they are not declared yet. qir is out of scope because it is an instance variable, but main is a static method. os is out of scope because it is local to uplo.


Related puzzles: