Author Topic:   String and String buffer
Himabindu Devulapalli
greenhorn
posted April 19, 2000 03:22 PM             
Maha anna..kindly give me answers to 2 questions:

1.How are string Buffer and String object different ? see the following code :
StringBuffer s1= new StringBuffer("JAVA");
StringBuffer s2= new StringBuffer("JAVA");
if s1.(equals(s2) )
System.out.println( s1 = s2)
else
System.out.println(s1 # s2);

The output is s1#s2.

However if I use String instead of String buffer the answer is
s1 = s2.

2.Also why does comparison with "==" yield different result from .equals() method.

Please explain Maha Anna !! Thanks in advance


maha anna
bartender
posted April 19, 2000 03:29 PM             
I request all others also to participate. After all your share, if anything left for Maha , I will finish up. Generally I welcome others to participate first. If there are no reply at all , then I try to answer.
regds
maha anna

[This message has been edited by maha anna (edited April 19, 2000).]

satya5
ranch hand
posted April 19, 2000 03:37 PM             

StringBuffer inherits the equals() method from the
Object class and so the method does not perform
a char by char comparision.

Re your next question, it has been beaten to death
on the ranch, please do a search on "string" as your
subject and it is all there...hey no pains no gains

Regds,

- satya

maha anna
bartender
posted April 19, 2000 10:03 PM             
Himabindu Devulapalli,
Did u find out? Please reply. If not I can explain.
regds
maha anna

girish
greenhorn
posted April 20, 2000 03:28 AM             
Himbandhu,
The StringBuffer class (String aswell)inherit equals() method
from Object class.

The important difference is String class overrides this method
to do character by character comparision.
Whereas the StringBuffer class doesnot override this method.

So your ans gives they are not equal.

rgds
Girish

Ajith Kallambella
ranch hand
posted April 20, 2000 07:41 AM             
Since lost of people have answered your first
question( why .equals() returns false ) I am
going to skip that one.


Next question - However if I use String instead
of String buffer the answer is s1 = s2.

It is because of String pooling
Java does. Remember Strings are reused by
Java if you created them using = operator
instead of new().

Next Question
2.Also why does comparison with "==" yield
different result from .equals() method.

Generally == compares references, not the
contents. So for reused strings, because the
strings are pointing to the same object(address)
== is returning true.

Does this answer your questions?

Good luck.

Himabindu Devulapalli
greenhorn
posted April 20, 2000 07:43 AM             
Thanks Satya, Girish and Maha Anna. I havd also looked up this mornign the Api for String and string buffer class. Thanks again one and all for your time and patience.

:-) Himabindu D

|