Random ruminations of a java developer

Tuesday, August 22, 2006

Novice Java Programmer Mistakes, part 1

I've done a lot of code reviews over the years and the same mistakes always pop up. Often they are really trivial ones like this one, maybe I'll write a top 10 of these some day :)

Using == when really should be comparing objects with equals()

String a = "aa";
String b = "bb";

if( a == b ) // this is wrong
{
// do something
}

The previous example of course really should be like this:

if( a.equals( b ) ) // this is correct
{
// do something
}

Here's an additional tip, when comparing string literals to some String variable its quite useful to write the comparison like this:

"foobar".equals( a );

This makes it possible to leave out the null check, which in turn results in cleaner code.

Tags:

No comments: