• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals method and StringBuffer

 
mohammad shaid
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From K&B 5.. page 494..
regarding StringBuffer class.. its mentioned in the book that StringBuffer equals is not overridden, it doesnt compare values.. so i tried a program and i observed that equals method works on StringBuffer.. and output is "az"..
how is that??? is it that the "Hello" value of StringBuffer is stored in the String literal pool?? i know the second variable is pointing to the same object ..

 
Prasad Kharkar
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the equals method is not overriden for any class then the equals method checks whether the reference variables refer to the same object
if they refer to the same object then the equals method returns true
also == operator checks whether the bit pattern is same in those variables and if two variables refer to the same object
then the bit pattern is same for them and hence == return true for them
so in your question

buffer and buffer2 refer to the same "Hello"
hence both
equals method and == operators return true and az gets printed
I had tried a sample program that can help you understand a little more
this is it


and the output is
F:\Java\Concepts\dokyatun Nighalele\source files>java StringBufferTest
sb1.equals(sb2) false
sb2.equals(sb3) false
sb1.equals(sb3) false
sb1 == sb2 false
sb2 == sb3 false
sb1 == sb3 false
sb1 == sb4 true
sb4 == sb5 false
sb3 == sb6 true
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also i suggest you to go through the equals method implementation in java.lang.Object class
 
mohammad shaid
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chack the code inside

 
Prasad Kharkar
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shaid
you are forgetting something
I have mentioned before that
If a class does not override the equals method then the equals method return true if those objects refer to the same object
here in this case
StringBuffer does not override the equals method
we have written that
sb1 = sb4;
hence
sb1.equals(sb4) returns true
hope this is clear to you now
 
mohammad shaid
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
alrite brother... Thank you ....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic