-4

When we write the following code in Java:

object1 == object2;

on what basis does the operator '==' decide equality?

john_science
  • 6,325
  • 6
  • 43
  • 60
  • 1
    http://google.com/?q=java+equality+operator – Scott M. Apr 16 '12 at 13:03
  • Possible Duplicate: **[Comparing strings in java](http://stackoverflow.com/questions/1833538/comparing-strings-in-java)** and **[Strings in Java : equals vs ==](http://stackoverflow.com/questions/3281448/strings-in-java-equals-vs)** – Siva Charan Apr 16 '12 at 13:04
  • possible duplicate of [java == vs Equals() confusion](http://stackoverflow.com/questions/7520432/java-vs-equals-confusion) – Christoffer Hammarström Apr 16 '12 at 13:17

3 Answers3

11

If object1 and object2 are reference types, then == checks if object1 and object2 are both references to the same object.

See 15.21 Equality Operators in the Java Language Specification for full details.

hmjd
  • 120,187
  • 20
  • 207
  • 252
3

object1 == object2; will return true if both are reference to same object. Don't assume that it will return true if both objects has same contents or both are objects of same class, etc.

True when both references to same object, false otherwise.

Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
3
Object a = new Object();
Object b = new Object();
System.out.println(a==b); //not the same
Object c = new Object();
Object d = c; // d points to the same reference
System.out.prinlnt(c==d); // the same
matt freake
  • 4,877
  • 4
  • 27
  • 56