Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals and ==

 
Abhi Kumar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gems,

I'm always confused between the equals and "==" .
Can anyone please let me know the exact difference.

Regards
 
Alexander Arenas
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

This guy has a great definition on equals() vs ==

http://leepoint.net/notes-java/data/expressions/22compareobjects.html

 
Muhammad Saifuddin
Ranch Hand
Posts: 1324
Android Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Topic already being discussed on this thread.
 
camilo lopes
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
normally you use equals to compare reference to objects and == when you want to compare values. for instance:


the result is true and false. with == if you are testing reference and no values.


 
Stephen Davies
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically == tests to see if two references point to the same object on the heap, and .equals tests object equality either, by default (see for instance strings) or by your own implementation (ie. by overriding the .equals method).



However, take note you will have to read more about bothe equals and Strings, as strings have a partiular behaviour with equals and ==, especially when it comes to the String pool.
 
Dhruva Mistry
Ranch Hand
Posts: 67
Eclipse IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
equals method if for comparing values of two variables/objects and == for checking whether two objects are pointing to same memory location or not
 
Priyam Srivastava
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'==' will always check whether the two reference variable point to the same object in the heap or not. If they do, it returns true.
Ex:

Cat obj1 = new Cat();
Cat obj2 = new Cat();
Cat obj3 = obj1;

obj1==obj2----------------------> always false as "new" creates two separate objects.
but
obj3==obj1-----------------------> true.


As far as equals() is concerned it checks the content of two objects.
Ex:

String s1 = new String("Test");
String s2 = new String("Test");


s1.equals(s2)-----------------> true since both have value "Test"
but s1==s2--------------------> false as they both refer to two separate objects.


For your own custom made classes like Cat, Dog, Horse, Vehicle you have to override the equals()to decide the criteria on which equals method returns true.
If you don't the default equals() simply checks for == for your custom made classes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic