File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes difference between equals() and == and compareTo() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "difference between equals() and == and compareTo()" Watch "difference between equals() and == and compareTo()" New topic

difference between equals() and == and compareTo()

Amit Goel
Ranch Hand

Joined: Dec 07, 2000
Posts: 50
what is the difference between equals() and == and compareTo() ??

Amit<br /> <br />The Less I have, The more I gain..Off the Beaten Path, I Reign.
Michael Burke
Ranch Hand

Joined: Jul 29, 2000
Posts: 103
The "==" operator should be used for primitive types only. If it's used with objects the value compared is the reference to the object which can give you results that your not expecting. I find this a hard oncept to understand but there are numerous references that have info about it. Check RHE, examcram or the JLS. Mock exam ques. about the difference between the two are numerous and can be quite tricky.
Ajith Kallambella

Joined: Mar 17, 2000
Posts: 5782
== does plain reference comparison. It is an operator.
equals() is a method defined in java.lang.Object class. Subclasses can override this method to provide a meaningful content comparison. The default behaviour implemented by the Object class does nothing but reference comparison. So, if a class doesnot override equals() method, the result of calling this method will be consistent with the results obtained when you use the == operator.
CompareTo() is a method defined by the java.lang.Comparable interface. Unlike the equals() method, this method is designed to be used for determining the natural order of objects while sorting. Java provides various sorting helper classes and method and some of them call the compareTo() method( if implemented by your class ) to findout the natural sorting order of each object that is an instance of your class. So, compareTo() does not check equality, but checks which object comes first when they need to be sorted in a specific order.

Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
I agree. Here's the link:
subject: difference between equals() and == and compareTo()
It's not a secret anymore!