Possible Duplicate:
Difference Between Equals and ==
in which cases equals()
works exactly like ==
operator?
It seems that they both act similar for primitive data types
. Are there any other cases in which both of them act equal?
Possible Duplicate:
Difference Between Equals and ==
in which cases equals()
works exactly like ==
operator?
It seems that they both act similar for primitive data types
. Are there any other cases in which both of them act equal?
==
compares the bits of reference for Object
type so if you have reference to same Object it would be the case
For example
Integer
for value -128 and 127 (inclusive) it caches (while autoboxing) the instance so it would be the case here for the mentioned range of value of Integer
For primitive data types, there is no equals()
(because they are not objects, and have no methods).
The default implementation (in class Object) for equals()
just does object identity check (i.e. the same as ==
). So if a class does not override it, it will have the same result as ==
.
The operator ==
will always compare references for objects, and the actual value for primitive types.
Note that an array of primitives like int[]
is still an object!
String test1 ="test";
String test2 = test1;
System.out.println(test1 == test2);
System.out.println(test1.equals(test2));
Both will print -
true
true
In addition to primitives (which are a special case) ==
and equals()
behave similarly for every case in which reference equality is the same as actual equality:
Integer
references (normally between -128 and +127, but this is configurable, and it depends on how the instance was constructed)Object
(and any other class that doesn't override equals()
)Obviously, when in doubt, use equals()
The equals()
method evaluates on hashCode
comparisons. While ==
compares objects by reference.