wood burning stoves 2.0*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals()" Watch "equals()" New topic
Author

equals()

Sai Ram9
Greenhorn

Joined: Feb 13, 2001
Posts: 18
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);
if(a.equals(b))
System.out.println("objects have the same value");
else
System.out.println("objects have different values");
}
}
answer says: objects have different values.
Please somebody explain me....
qionghua yang
Ranch Hand

Joined: Oct 31, 2000
Posts: 68
Hi,
When a.equals(b) is called, it will call the super class Object's equals method. This equals methos will check to see if the two object references are point to the same object. Since in your code, you are creating two different objects. So they are different.
Try the follwoing:
public static void main(String[] args)
{
MyClass a = new MyClass(100);
MyClass b= a;
if(a.equals(b))
System.out.println("objects have the same value");
else
System.out.println("objects have different values");
}

Hope this helps.
qionghua
Sandeep Nachane
Ranch Hand

Joined: Dec 06, 2000
Posts: 57
Sai,
I had posted this answer few days back but could not locate it.. hence giving it here again. Hope it will help you.
All classes extend Object class, directly or indirectly and therefore inherit Object's methods. The equals() method is one of these inherited method. Unless you override
equals() method in your class , you get default implementation of equals(). This default implementation assumes that an object is equal to itself. i.e It compares object references for equality, returning true if they have same
value or else would return false if the references have different values.
If you need to look at more self review questions on this topic, you may visit my homepages at http://www.tipsmart.com/javacert/selfreview/objequiv.htm
Sandeep Nachane

<A HREF="http://www.tipsmart.com" TARGET=_blank rel="nofollow">www.tipsmart.com</A>
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: equals()
 
Similar Threads
equivalence
equals method
Equals
One Question
Tell me the output?