| Author |
equals method and StringBuffer
|
mohammad shaid
Ranch Hand
Joined: May 05, 2010
Posts: 86
|
|
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 ..
|
Thanks & Regards,
shaad
|
 |
Prasad Kharkar
Ranch Hand
Joined: Mar 07, 2010
Posts: 438
|
|
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
|
SCJP 6 [86%] June 30th, 2010
If you find any post useful, click the "plus one" sign on the right
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
|
also i suggest you to go through the equals method implementation in java.lang.Object class
|
 |
mohammad shaid
Ranch Hand
Joined: May 05, 2010
Posts: 86
|
|
chack the code inside
|
 |
Prasad Kharkar
Ranch Hand
Joined: Mar 07, 2010
Posts: 438
|
|
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
Joined: May 05, 2010
Posts: 86
|
|
|
alrite brother... Thank you ....
|
 |
 |
|
|
subject: equals method and StringBuffer
|
|
|