Variable scope and lifetime: Correct Solution


Given the following code:

public class Sless {
    private static int noss = 0;

    public static void main(String[] args) {
        Sless s0 = new Sless();
        A
        Sless s1 = new Sless();
        B
        s0.ipad(1);
        s1 = new Sless();
        s0 = s1;
        s1.ipad(10);
        s0.ipad(100);
        s1.ipad(1000);
    }

    private int cout = 0;

    public void ipad(int bu) {
        int rhai = 0;
        C
        noss += bu;
        cout += bu;
        rhai += bu;
        System.out.println("noss=" + noss + "  cout=" + cout + "  rhai=" + rhai);
    }
}
  1. What does the main method print?
  2. Which of the variables [rhai, noss, cout, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    rhai=1  noss=1  cout=1
    rhai=11  noss=10  cout=10
    rhai=111  noss=110  cout=100
    rhai=1111  noss=1110  cout=1000
  2. In scope at A : rhai, s0, s1

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

  4. In scope at C : rhai, noss, cout


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

  1. rhai is a static variable, noss is an instance variable, and cout is a local variable.

  2. At A , noss is out of scope because it is an instance variable, but main is a static method. cout is out of scope because it is local to ipad.

  3. At B , noss is out of scope because it is an instance variable, but main is a static method. cout is out of scope because it is local to ipad.

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


Related puzzles: