About String immutability in Java

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'); /* 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
} 

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?

+4
source share
1 answer

textString = textString.replace ('j' , 'c'); , textString String, String.

, stringReplace String, . , , stringReplace(textString).

, Java . , , . String , String, , String, ( ), String , .

+7

All Articles