• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals() and ==

 
thanvi janu
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is thanvi, i have some doubts in equals() method

1. String a=new String();
String b=new String();
System.out.println((a == b) + " " + (a.equals(b)));
output was false true

2. Test t=new Test(); // user defined class
Test aa=new Test();
Test ab=new Test();
System.out.println((aa == ab) + " " + (aa.equals(ab)));
output was false false

3. Integer c=new Integer(10);
Integer d=new Integer(10);
System.out.println((c == d) + " " + (c.equals(d)));
output was false true

working with these three example i came to a conclusion that

Predefined class equals(): checks for the object
User defined class equals(): checks for the reference

4. Object o1 = new Object();
Object o2 = new Object();

System.out.println((o1 == o2) + " " + (o1.equals
(o2)));

I thought answer for 4 will be false and true because it is a Predefined class, but when i complied it the answer was false and false.

what is actually happening in example 4?
why in user defined class, equals() checks for reference instead of object?
Is my understand correct?
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object is not an immutable class...
 
Henry Wong
author
Marshal
Pie
Posts: 21518
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanvi janu wrote:
working with these three example i came to a conclusion that

Predefined class equals(): checks for the object
User defined class equals(): checks for the reference


Many of the Java core classes (String, Integer, etc.) override the equals() method, in order to provide a definition of equality based on the value of the object. Some don't, in which case they will inherit the equals() method from the super class -- and the Object class uses references to determine equality.

As for user defined classes, it would depend on if they overridden the equals() method. If they don't, then they would inherit the implementation from the Object class.

thanvi janu wrote:
I thought answer for 4 will be false and true because it is a Predefined class, but when i complied it the answer was false and false.

what is actually happening in example 4?
why in user defined class, equals() checks for reference instead of object?
Is my understand correct?


Since the Object class' equal() method is what is inherited when classes don't override equals, it is understandable that it behaves this way -- from your previous experiment.

Henry
 
thanvi janu
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
tanx Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic