Friday, May 11, 2007

Searching for common bugs

Google Code Search isn't anything new, but I had fun with it today to search for a bug that I ran into in my project's code base.

Its a simple error to make:

if ( s == "" )

Correct usage would be

if ( s.equals( "" ) )

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:

Unknown said...

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.