Wednesday, April 18, 2007

Java string comparison tip

Today's tip is just a simple reminder to always use th "equals" function when comparting Strings in Java and not the comparison operator "==".

For example:

String a="a";

//Good
if (a.equals("a"))
fnA();

// Bad
if (a=="a") fnA();

The comparsion operator will compare the value of the String pointer which is probably not what is desired. Generally, you should use the equals function to compare the contents of teh string.

1 comment:

Anonymous said...

You write very well.