Firstly, 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');
}
public static void bufferReplace (StringBuffer text)
{
text = text.append ("c");
}
public static void main (String args[])
{
String textString = new String ("java");
StringBuffer textBuffer = new StringBuffer ("java");
stringReplace(textString);
bufferReplace(textBuffer);
System.out.println (textString + textBuffer);
}
But if we write the following:
public static void bufferReplace (StringBuffer text)
{
text = text.append ("c");
}
public static void main (String args[])
{
String textString = new String ("java");
StringBuffer textBuffer = new StringBuffer ("java");
textString = textString.replace ('j' , 'c');
bufferReplace(textBuffer);
System.out.println (textString + textBuffer);
}
I expected the first example to be printed the same as the second. the reason is that when we pass textStringfunctions, we actually pass a link to textString. Now in the body of the function another line was created text.replace ('j' , 'c'), and we assigned a link to this line to the line into which we passed. In the second example, I simply assign a link to a string created with textString.replace ('j' , 'c');, on testString. Why is there such a difference?
Follow for this reason, the results should be the same. What's wrong?
source
share