I am confused taking the difference between equals and == operator.How and where the work?And one more thing,what does it stand foe equating two object references ? if Integer a=2; and Integer b=3; and if i do a=b; so according to me bit pattern of b is copied to a .But when i see output i get value of b is transformed to a.And giving True while using equals() and ==. I m bit confused. please help me out. Thanks n regards Deepak
a.equals(b) <- true but a == b <- false (diferent objects)
Immutability is not the reason that this example is wrong. In the quoted example a == b will actually return true because String literals are held in a pool and there is only one instance of each literal. Therefore a and b are both referencing the same object and so are equal.
Joined: Oct 13, 2005
You are right; I wasn't clear about why those examples wouldn't work as they thought.
The == operator is a simple comparison of values. For object references, the values are the references, so x == y returns true if x and y reference the same object.
The equals method can compare two different objects for equality. But here, "equal" is defined by the programmer when they override the method for a specific class. For example, if you are writing a Car class and all you care about is color, then you could implement equals to return true if both cars are the same color. It's probably not the best way to compare cars, but the point is it's up to the programmer to decide what "equals" means.
(As mentioned above, be careful when comparing Strings to each other, and when comparing autoboxed wrapper instances to each other. Under certain situations, these use "pools." See Strings, Literally and JLS - 5.1.7 Boxing Conversion.)
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org