Randomness at its best

Journey from a no one to a someone

Sunday, April 22, 2007

.equals() and ==

After writing buggy code time and again by wrong usage of .equals and ==, here I am writing about it.

Both check the equality, both return a boolean, but but but...
.equals() is for value equality while == is for object equality. To make it clear, .equals() checks if both the objects have same value and == checks if both objects point to the same memory location.

Make sure that you use the two correctly according to the needs. Its obvious that checking of non null values is to be done by == operator, otherwise for null conditions, it is sure to throw a null pointer exception. Also, if you are checking a concrete value with a variable, make sure the concrete value is the first variable in case of .equals(). That will save you from a few null pointer exceptions.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home