Variable scope and lifetime: Correct Solution


Given the following code:

public class Cenpa {
    public static void main(String[] args) {
        Cenpa c0 = new Cenpa();
        A
        Cenpa c1 = new Cenpa();
        c0.ussIlna(1);
        c1.ussIlna(10);
        c0 = c1;
        c1 = c0;
        c0.ussIlna(100);
        c1.ussIlna(1000);
        B
    }

    public void ussIlna(int mi) {
        int be = 0;
        C
        ues += mi;
        prar += mi;
        be += mi;
        System.out.println("ues=" + ues + "  prar=" + prar + "  be=" + be);
    }

    private static int ues = 0;
    private int prar = 0;
}
  1. What does the main method print?
  2. Which of the variables [be, ues, prar, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    be=1  ues=1  prar=1
    be=11  ues=10  prar=10
    be=111  ues=110  prar=100
    be=1111  ues=1110  prar=1000
  2. In scope at A : be, c0, c1

  3. In scope at B : be

  4. In scope at C : be, ues, prar


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

  1. be is a static variable, ues is an instance variable, and prar is a local variable.

  2. At A , ues is out of scope because it is an instance variable, but main is a static method. prar is out of scope because it is local to ussIlna.

  3. At B , c0 and c1 are out of scope because they are not declared yet. ues is out of scope because it is an instance variable, but main is a static method. prar is out of scope because it is local to ussIlna.

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


Related puzzles: