Wednesday, April 21, 2010

[TF001] An empty string doesn't contain anything! (true/false?)

Note: This is the start of a (daily, hopefully!) series of articles exploring various "True or False?" statements regarding Java. Hint: they're all false. The idea is to correct misconceptions through counterproofs just have fun.
(true/false?) By definition, something is empty if it doesn't contains anything, so given String s1, s2, if s1.isEmpty(), then !s1.contains(s2).
static void tf001(String s1, String s2) {
   if (s1.isEmpty()) {
      assert !(s1.contains(s2));

FALSE! An empty string contains itself.
tf001("", ""); // throws AssertionError
For all s instanceof String, s.contains(""), and s.indexOf("") == 0. In fact, s.indexOf("", i) == i for all in-range values of i.

Perhaps a reworded question would've been more intriguing: "Which instanceof a J2EE class is both isEmpty() and contains itself?"

No comments:

Post a Comment