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

operator and function( )

 
saransh panda
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for comparison between two objects we can use
[1] operator 'obj1==obj2'
[2] function 'obj1.equals(obj2)'
but what is the difference between them? And if they represent the same funcationality what is the significance of equals() function?

thankyou!
 
Bryan Snipes
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm just a newbie myself, but I'll try to answer (also for my own learning).
The "==" operator is for comparing two primitive variables.
The ".equals" is used for comparing the value of two objects.

I'm sure the gurus around here can add more explanation.
 
Balasubramanian Chandrasekaran
Ranch Hand
Posts: 215
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by saransh panda:
for comparison between two objects we can use
[1] operator 'obj1==obj2'
[2] function 'obj1.equals(obj2)'
but what is the difference between them? And if they represent the same funcationality what is the significance of equals() function?

thankyou!


the == operator actually tests the equality of the reference variables, that is, if the two variables are referring to the same object. To test the logical equality, that is, the equality of the object's state, we normally use the equals() method.

And welcome to the ranch
[ May 12, 2008: Message edited by: Balasubramanian Chandrasekaran ]
 
saransh panda
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the reply bryan
but I think '==' operator can be used for comparing objects as well as primitives. In fact I have tried it and it works on objects as well.
 
Vikas Kapoor
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the copy and paste from my old post.

Here is the quick difference between == and equals():

== checks wheather two object refernces points to same instance or not.
Whereas equals() compare the actual contents of two string objects.


Example:

 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vishal Pandya:
== checks wheather two object refernces points to same instance or not.
Whereas equals() compare the actual contents of two string objects.


This is true for Strings but not for all objects. If a class does not override the equals method then it will inherit the equals method from the Object class. The equals method in the Object class compares the two objects using ==.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic