• Post Reply Bookmark Topic Watch Topic
  • New Topic

equals() versus ==  RSS feed

 
Preethi Chilukuri
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

public class MyClass {

String a;

public MyClass(String ab) {
a = ab;
}

public boolean equals(Object object2) {
return (a == object2);
}

public boolean equals2(Object object2) {
return (a.equals(object2));
}



public static void main(String args[]) {

MyClass object1 = new MyClass("test");
MyClass object2 = new MyClass("test");

object1.equals(object2);
System.out.println(object1.equals(object2));

object1.equals2(object2);
System.out.println(object1.equals2(object2));
}

}

RESULT: 'FALSE' for both print statements.

Could not analyse further. Appreciate any help..
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your equals method is comparting a String (variable a) to an instance of MyClass (in your example). This will always return false.
Your equals2 method calls equals which will always return false. That is not quite true. In your case String#equals is called, not your MyClass#equals. This will always return false anyway.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Start by reading our FAQ about why you should rarely use ==.

What you are doing in that equals() method is checking whether the other object is the exact same object as that on which the equals method is called. In the other method you are testing whether the String field is equal to the object passed as a parameter.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!