String is immutable (it can't change) whilst a StringBuffer is not (it can change). Its a popular inteview question. When you invoke methods on a String object, you may think you can edit it, but you are actually getting a new String object back.
Post by:Saravanan Jothimani
, Greenhorn
class stringbufferexample { String str = "TATA"; StringBuffer strbuff = new StringBuffer(); String strone = "Infotech"; StringBuffer strbuffone = strbuff.append("ICICI"); public void print() { System.out.println(str); System.out.println(strone); System.out.println(strbuff); System.out.println(strbuffone); } public static void main(String args[]) { stringbufferexample sbe = new stringbufferexample(); sbe.print(); } }
My out put is
TATA Infotech ICICI ICICI
Why I am getting the output like this System.out.println(str); - TATA -Correct System.out.println(strone); - Infotech - Correct System.out.println(strbuff); - ?. - I have createad an object System.out.println(strbuffone); -ICICI - Correct - Because I am appending a string.
Pls help me out I am little bit confused.
Thanks in Advance
Saravanan
Post by:Marilyn de Queiroz
, Sheriff
The key is in this line StringBuffer strbuffone = strbuff.append("ICICI"); Although you are assigning the result to strbuffone, you have also changed the original strbuff object. When you print strbuff, you get the modified StringBuffer object, the one with "ICICI" appended.
Post by:David Harkness
, Ranch Hand
The reason StringBuffer.append() is confusing is that the StringBuffer it returns is not a new StringBuffer with the text appended but the same StringBuffer to support method chaining.
If I am using Final StringBuffer s = new StringBuffer ("Hello");, Can I append this object s using append();
Thanks in Advance
Saravanan
Post by:Ernest Friedman-Hill
, Sheriff
Originally posted by Saravanan Jothimani:
If I am using Final StringBuffer s = new StringBuffer ("Hello");, Can I append this object s using append();
Yes. The variable "s" is final -- i.e., it can't be made to point to another StringBuffer -- but the StringBuffer itself is mutable. There's no equivalent to C++'s "const" in Java.
Post by:Saravanan Jothimani
, Greenhorn
Thanks Ernest Friedman-Hill
Regards
Saravanan
Post by:autobot
You didn't tell me he was so big. Unlike this tiny ad:
Thread Boost - a very different sort of advertising