• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference between equals() and ==

 
Anjali Vaidya
Ranch Hand
Posts: 40
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! could anybody please tell me what is the difference between equals() and == ?
if possible with an example
 
Lou Pelagalli
Ranch Hand
Posts: 150
1
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I can take this one.

== will determine of the objects share the same reference, that is refer to the same object in memory.
equals will determine if according to the objects equals(obj) method if they contain the same value but may or may not refer to the same object.

Note that if obj1 == obj2 is true then obj2.equals(obj2) should also be true because an object always equals itself.

Here's some code that may help.

 
Anjali Vaidya
Ranch Hand
Posts: 40
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Lou! I'm clear with the concept now
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also use == with primitives, but you can't use equals() on primitives.
 
Dmitry Veber
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You can also use == with primitives, but you can't use equals() on primitives.


He basically got the point, to give you an example (one that you can try at any time), try comparing 2 int values with the == and the .equals() way. Both will work.

Try comparing 2 string values with both ways, and you will notice that you get an error with the == because strings are objects, not primitives. Same thing with any other object you decide to make in the future
 
goel Ashish
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dmitry Veber wrote:
He basically got the point, to give you an example (one that you can try at any time), try comparing 2 int values with the == and the .equals() way. Both will work.

Try comparing 2 string values with both ways, and you will notice that you get an error with the == because strings are objects, not primitives. Same thing with any other object you decide to make in the future


Campbell is right. You cant compare two primitives value with equals method.
The example you gave is incorrect. However we can compare two Integer objects with equals method.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch Dmitry Veber.

Are you sure you can use the .equals() method for two ints? The only way I can imagine it working is via boxing, but I would suggest you show us a working example. I couldn't get it to compile myself.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic