• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals and ==

 
Subbu C
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,
I had joines the ranch recently and i had started appreciating the collective effort that is beeen put on.. Cheers!!
Cansomebody enlighten me on the difference between == and equals method with respect to String.
Thanks
Subbu
 
Mary Anitha
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== is used to check whether the object-references point to the same object
equals() is used to compare the contents of the objects i.e. the strings
eg:
String s1 = new String("java");
String s2 = new String("java");
System.out.println(s1 == s2); //result is false
System.out.println(s1.equals(s2)); // result is true
 
mana
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends,
In the foll. code
1.StringBuffer sb1 = new StringBuffer("Amit");
2.StringBuffer sb2= new StringBuffer("Amit");
3.String ss1 = "Amit";
4.System.out.println(sb1==sb2);
5.System.out.println(sb1.equals(sb2));
6.System.out.println(sb1.equals(ss1));
7.System.out.println("Poddar".substring(3));
shouldn't the 6th line give compile error as equals method is not overriden in stringbuffer class.can anybody please explain.
thanks,
mana
 
Surya Bahadur
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi mana
Every class extends object and StringBuffer is no exception,but it does not override the equals method from the object class,it just inherits it.
Surya
 
Kav Bop
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
Mary Anitha is correct when she mentioned the difference between == & equals().
I would like to elaborate a bit more on this one.
In the class Object, equals() method behaves similar to the == operator. i.e. equals() returns true only if
this == object reference of parameter
All available classes in java override the equals() method to compare the contents.
However, if you write your own class (by default it inherits from Object), the behaviour of equals() will be same as that of ==, unless you override equals() to compare contents rather than refernces.
I hope the above clears the difference between == & equals().
One point to remember is equals() method always check the types of the invoking object & the parameter passed. If the types are not the same, it returns false, no matter what the contents. Only if the types match, it goes for checking the contents.
[This message has been edited by Kav Bop (edited October 16, 2000).]
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'Subbu C',
PROPER NAMES ARE NOW REQUIRED!!
Read this post for more details.
Ajith
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic