Friday, February 12, 2010

Usage of equals in Java

Every now and then I take a look on a projects java source code on the web.
I still am amazed that most of that code do not use some basic coding rules.

One of these is to check objects with equals to a static string.
This is mostly done as:

private static final String STATIC_TEXT = "Static Text";

if(object.equals(STATIC_TEXT)
{
.....
}

The though part about this is that people do not see the danger in this.
The fact is that (most) objects in java are initiated with null if.
So the case shown above could result in an easy nullpointerexception.
While this is not necessary, this could be prevented by changed sequence in which you execute this statement.
<br />private static final String STATIC_TEXT = "Static Text";<br /><br />if(STATIC_TEXT.equals(object)<br />{<br />.....<br />}<br />

When changed like this the exception will not occur, only the check will result in 'false'.
Keep in mind that the code than needs to handle a null object(s).

To prevent that the usual check '!= null' can always be executed.
But by putting the objects in the right order it will prevent a lot of unnecessary searches for errors.