• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

equals()

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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....
 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic