Thursday, February 13, 2014

Java Equality (==) Operator

You probably know you should use equals method instead of == in order to check equality of object values (non primitive values). I've written the following test code to show my friend that he shouldn't use == operator to compare Integer or String values.


I've expected that the expressions in 12th and 17th lines will return false because they belong to different variables but I guess Java optimizes them and make them share the same variable :) Happily, the expressions in 13th, 18th and 19th lines returns false as I expect.

The following is a very nice explanation by Jops @Stackoverflow: stackoverflow.com/a/16194428/878710

Jorman is a successful businessman and has 2 houses.


When you ask neighbours from either Madison or Burke streets, this is the only thing they can say:


Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons.

That's how the operator == behaves. So it will say that datos[0]==usuario is false, because it only compares the addresses.

No comments:

Post a Comment