[Logo]
Forums Register Login
Difference
Hi,

Please give me a detailed difference between String and StringBuffer

Thanks in Advance

Saravanan
 
Originally posted by Saravanan Jothimani:
Hi,

Please give me a detailed difference between String and StringBuffer

Thanks in Advance

Saravanan


Hmmm... to much typing...

how about this link...

http://java.sun.com/docs/books/tutorial/java/data/strings.html

from the Sun's Java Tutorial...
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.
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
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.
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.
Thanks
You may also want to look at this.

Layne
Hi,

If I am using
Final StringBuffer s = new StringBuffer ("Hello");, Can I append this object s using append();

Thanks in Advance

Saravanan
 
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.
Thanks Ernest Friedman-Hill

Regards

Saravanan
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Nov 17, 2017 10:58:05.