• Post Reply Bookmark Topic Watch Topic
  • New Topic

difference between "equal()" and "==" in java.  RSS feed

 
Vinod Vinu
Ranch Hand
Posts: 217
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
difference between "equal()" and "==" in java.
why java have provided a seperate method "equal()" to compare if can do the same with "==" only.

Kindly explain me in brief with some e.g.

thanks in advance......
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vinod Vijay wrote:
why java have provided a seperate method "equal()" to compare if can do the same with "==" only.


Because they are not the same thing. The "==" operator is used detect whether two references are pointing the the exact same object. The equals() method is class specific -- for example, strings are equal when the value is equal, even if it is two different string objects.

Henry
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you have something like

MyClass objectA, object B

what you have are references to the objects. You can think of them as like little cards that tell you the address of a house. using '==' tells you if both pieces of paper say "1600 Pensylvania avenue". using equals() might tell you if both homes are worth $150,000, or if both have three bedrooms, or if both are exactly the same square footage...

equals() can be defined to be whatever 'makes sense' for that object type.
 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is 1600 Pennsylvania Ave really worth as much as $150000?
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!