[thelist] PHP question... checking string length

Matt Warden mwarden at gmail.com
Sat Mar 26 22:50:09 CST 2005


On Sun, 27 Mar 2005 12:44:15 +0900, Andrew Clover <and-evolt at doxdesk.com> wrote:
> Testing len==0 is a common Java optimisation, as apparently it is
> quicker to do a .length() check than a full string comparison. 

This is true because in Java strings are objects and .length()
retrieves a property of the string object.

> In Java,
> all Strings, even string literals, are mutable and so comparisons have
> to be done using a.equals(b) rather than == (a common source of bugs and
> a horrible design decision IMO), so the .length() test is perhaps not so
> much less readable in this case.

Java strings are not mutable. Further, that's not why you have to use
.equals(). Strings in Java are objects, thus == would test a
reference. So:

String a = "a";
String b = "a";
Strinc c = a;

boolean thisisfalse = (a == b); // because a and b are not pointing to
same object
boolean thisistrue = a.equals(b); // because "a".equals("a") 
boolean thisistrue = (a == c);  // because a and c are pointing to the
same object
boolean thisistrue = a.equals(c); // because "a".equals("a")

StringBuffer is a mutable alternative to String in Java. This wasn't
really a design decision. It's just that a string is not a primative
type, like char, int, etc. I believe StringBuffer uses a character
array (with various capacity optimizations) to acheive a mutable

Matt Warden
Miami University
Oxford, OH, USA

This email proudly and graciously contributes to entropy.

More information about the thelist mailing list