Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Whant is 'equals' and '==' in JAVA mean......?  RSS feed

 
Abhishek Dhar
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody help me in explaining what do we mean by following operators in JAVA:

'equals' and '=='

Please give a brief definition about how can i use them and try to give a simple example
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Object class defines a method called equals that is inherited by all classes.

This method allows us to define what it means for two different objects to be meaningfully equal.

However, if a class does not override equals, then the default behavior is simply to check to see if the object reference calling the method and the object reference sent to the method refer to the same object.

Consider the following example.



first and second refer to different objects, but they are meaningfully equal.
 
Campbell Ritchie
Marshal
Posts: 55735
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More about what Keith Lynn says. If you are dealing with a primitive type, you can only use the == operator.
Whenever you are trying to use an equals() method, go to the API for that class and look for its equals method. If it appears in the block headed "mothods inherited from java.lang.Object" then it hasn't been overridden and does what Keith Lynn calls default behaviour.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!