• Post Reply Bookmark Topic Watch Topic
  • New Topic

difference betn == and equals()  RSS feed

 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the fundamental difference between == and equals() method.when i use them...what actually they deal with?

thanking u
amal
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== checks if the instances are pointing to the same object , wheras equals checks out if both the objects are of same value.
equals will return true always when == returns true, but the reverse is not necessarily true.
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== operator is the equality operator

equals() is for content comparison

== operator checks if both object references refer to the same memory location eg: if (a==b) it means it verifies whether both a and b refer to the same location in memory.

equals() if for content comparison.

eg:String a ="chandra"; String b="chandra"; String c ="radha";

if ( a.equals(b)) returns true bcoz both contains the same content.

if (a.equals(c)) returns false bcoz a and c contents are different.

I hope this would have solved your doubt.
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you have something like

MyClass foo = new MyClass();

you have to remember that the variable "foo" does NOT hold the actual object, but a REFERENCE to it. it holds the address of where the real object is.

so when you say

foo == bar;

you are testing to see if both references "foo" and "bar" refer to the same object, or the same physical place in the computer's memory.

when you say

foo.equals(bar);

you are saying "compare the objects in a special way, to see if they are functionally equivilent". Note that for just about any class you define yourself, you will need to define the equals() method for it to work how you want it to.
 
Marshal
Posts: 56605
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . but remember you have to override your equals() method (and the hashCode() method) in any classes where you wish to use equals().
 
amal shah
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks all for help...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!