Its a simple error to make:
if ( s == "" )
{
foo();
}
Correct usage would be
if ( s.equals( "" ) )
{
foo();
}
The tricky thing is that the first (incorrect) usage will work a surprisingly large percentage of the time.
Most strings will be empty because they were initialized to "" somewhere, rather than the result of a string operation that returned an empty string:
s.substring( s.length() ) // returns an empty string
Being initialized to the constant "" means that s will be pointing to the same jvm object that will be used in the equality comparison in the first if() statement.
Anyway, here is a link to the results of a code search for == ""
google code search for == ""
Interestingly enough, some of the first hits are valid uses of == "" (at least from their comments), because the string was interned first before being used in the comparison.
1 comment:
Actually, the correct way to say this is "".equals(s). That's because there will be a NullPointerException if s == null the old way, and the Java Language Specification requires s.equals(null) to be always false.
Post a Comment