Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with string buffer.  RSS feed

 
sachin yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i make two objects reference of StringBuffer and assign them the same value "TEST". now if i invoke '==' or '.equals' method to compare the object references then in the both case i got 'FALSE' while in case of String i got 'FALSE' and 'TRUE'. i know that '==' compares wheather two object reference refers to the same object or not and .equals cheacks the value of two object references. but this dosn't happen with StringBuffer. Why?
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
StringBuffer does not override the "equals" method.
So, I think that "buf1 == buf2" and "buf1.equals(buf2)" is the same.

Note that the String class overrides "equals" to compare the sequence of characters.
 
sachin yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx buddy for answer. is there any other class which doesn't have equals method??
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sachin yadav:
thanx buddy for answer. is there any other class which doesn't have equals method??


EVERY class has the equals() method because it is inherited from Object. Otherwise you would get a compiler error if you try to call it. Your mistake is in assuming that equals() compares the state of two objects. This is only the case if a class overrides the equals() method AND it implents it to give this result. By default, equals() behaves the exact same as the == operator. So the lesson is that you should check the Java API docs to determine whether a given class override it. There are, in fact, many classes that do NOT, so it would take a lot of time to list them here.

Layne
[ January 23, 2006: Message edited by: Layne Lund ]
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!