Variable scope and lifetime: Correct Solution


Given the following code:

public class Sisu {
    private int le = 0;

    public void gehes(int nurk) {
        int qoi = 0;
        A
        le += nurk;
        qoi += nurk;
        reco += nurk;
        System.out.println("le=" + le + "  qoi=" + qoi + "  reco=" + reco);
    }

    public static void main(String[] args) {
        Sisu s0 = new Sisu();
        B
        Sisu s1 = new Sisu();
        C
        s0.gehes(1);
        s1.gehes(10);
        s0.gehes(100);
        s1 = s0;
        s0 = new Sisu();
        s1.gehes(1000);
    }

    private static int reco = 0;
}
  1. What does the main method print?
  2. Which of the variables [reco, le, qoi, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    reco=1  le=1  qoi=1
    reco=10  le=10  qoi=11
    reco=101  le=100  qoi=111
    reco=1101  le=1000  qoi=1111
  2. In scope at A : qoi, reco, le

  3. In scope at B : qoi, s0, s1

  4. In scope at C : qoi, s0, s1


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

  1. qoi is a static variable, reco is an instance variable, and le is a local variable.

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

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

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


Related puzzles: