First, I know that strings in java are immutable.
I have a question about String immutability:
public static void stringReplace (String text)
{
text = text.replace ('j' , 'c'); /* Line 5 */
}
public static void bufferReplace (StringBuffer text)
{
text = text.append ("c"); /* Line 9 */
}
public static void main (String args[])
{
String textString = new String ("java");
StringBuffer textBuffer = new StringBuffer ("java"); /* Line 14 */
stringReplace(textString);
bufferReplace(textBuffer);
System.out.println (textString + textBuffer); //Prints javajavac
}
But if we write the following:
public static void bufferReplace (StringBuffer text)
{
text = text.append ("c"); /* Line 9 */
}
public static void main (String args[])
{
String textString = new String ("java");
StringBuffer textBuffer = new StringBuffer ("java"); /* Line 14 */
textString = textString.replace ('j' , 'c');
bufferReplace(textBuffer);
System.out.println (textString + textBuffer); //Prints cavajavac
}
The thing is I expected the first example would print the same as the second printed. the reason is when we pass textString to a function we actually pass a reference to textString. Now in the function's body another string was produced by text.replace ('j' , 'c') and we assigned a reference to that string to the string we passed in.
In the second example I just assign a reference to the string produced by textString.replace ('j' , 'c'); to testString. Why there is so difference?
Follow by that reason, the results must be the same. What's wrong?
StringBufferis much slower thanStringBuilder