wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes .equals() 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 ".equals()" Watch ".equals()" New topic


sachin agashe
Ranch Hand

Joined: Nov 08, 2000
Posts: 42
In the following code the values assigned to the variable maxElement referenced by bothe the a and b objects is the same. Then why the result of the .equals method is false??
class MyClass{
static int maxElements;
MyClass(int maxElements){
this.maxElements = maxElements;
public class Q19{
public static void main(String[] args){
MyClass a = new MyClass(100);
MyClass b = new MyClass(100);
System.out.println("Objects have the samevalues");
System.out.println("Objects have different values");

System.out.println("a object: "+a.maxElements+" b object: "+b.maxElements);//this prints 100 100
akshaya bhatt

Joined: Dec 24, 2000
Posts: 6
Go for String type of variables (inshort String class or wrapper class) and see the results.
Here u r using primitive data types which won't work as String class variables/objects
Ajith Kallambella

Joined: Mar 17, 2000
Posts: 5782
equals() is a method defined on the Object class. You can override it ( since all classes are subclasses of Object class ) to provide more meaningful comparison. However, when you don't override it, the default implementation of the method is called, which does nothing but plain reference comparison.
This means if not overridden, equals() returns true if the two objects being compared are one and the same( not the content, but the object itself ) and returns false if they are different( even if the content is the same ).
Now lets look at your code. Since MyClass doesn't override the equals method, the behaviour that you are seeing is the result of the method being called on the Object class. Hence it returns false.
Hope that helps,

Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
I agree. Here's the link: http://aspose.com/file-tools
subject: .equals()
It's not a secret anymore!