1

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?

Community
  • 1
  • 1
MBZ
  • 26,084
  • 47
  • 114
  • 191

6 Answers6

4

== 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

jmj
  • 237,923
  • 42
  • 401
  • 438
3

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 ==.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • This is the only strictly accurate answer. All other cases depend on the way that the objects are created / managed. – Stephen C Jun 13 '12 at 10:44
1

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!

Miquel
  • 15,405
  • 8
  • 54
  • 87
1
    String test1 ="test";
    String test2 = test1;
    System.out.println(test1 == test2);
    System.out.println(test1.equals(test2));

Both will print -

true

true

Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37
1

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:

  • Interned Strings
  • Certain Integer references (normally between -128 and +127, but this is configurable, and it depends on how the instance was constructed)
  • Singletons
  • Instances of Object (and any other class that doesn't override equals())

Obviously, when in doubt, use equals()

Sean Reilly
  • 21,526
  • 4
  • 48
  • 62
  • In the case of `Integer` references, it depends on *how* the reference was created; e.g. `new Integer(1) == new Integer(1)` evaluates to `false`. – Stephen C Jun 13 '12 at 10:40
  • Obviously. To be perfectly honest, the sometimes-interning of Integers isn't the best feature. I'd almost prefer if it only happened during auto-boxing. – Sean Reilly Jun 13 '12 at 10:43
  • And you can break the singleton-ness of a singleton if you play nasty tricks with reflection. – Stephen C Jun 13 '12 at 10:48
  • @Sean Reilly In addition to primitives (which are a special case) == and equals() behave similarly for every case. -- primitive data types don't have equals() method. – Pramod Kumar Jun 13 '12 at 10:48
0

The equals() method evaluates on hashCode comparisons. While == compares objects by reference.

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
Rupesh
  • 1