Tuesday, October 15, 2013

Java: Best way to use the equals() method

The equals() method compares values for equality. Since this method is defined in the Object class, which is the root of the class hierarchy, it's automatically defined for every class such as the String class.

The best way to use the  .equals() method when comparing values of String objects is to write it as:

"Hello World".equals(fooBar);
"".equals(fooBar);

rather than:

fooBar.equals("Hello World");
fooBar.equals("");


Both sets of examples will compile but the first set guarantees that a NullPointerException is never thrown when you perform the comparison. The second set may risk throwing a  NullPointerException if the object fooBar happens to be null.

No comments:

Post a Comment