Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About String immutability in Java

Tags:

java

string

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?

like image 303
St.Antario Avatar asked Mar 19 '23 04:03

St.Antario


1 Answers

In the second example textString = textString.replace ('j' , 'c'); happens in your main method, so the textString variable is assigned a new String, and you see the new String's value when printing your output.

In the first example it doesn't happen, since the call to the stringReplace method can't change the String reference passed to it. Therefore, the output you see is as if you never called stringReplace(textString) at all.

This all boils down to Java being a pass by value language. You can't change an Object reference passed to a method, since that reference is being passed by value. If String wasn't immutable, you could change the String instance passed to the method by calling String methods that change its state (if such methods existed), but you still wouldn't be able to assign a new String reference to the method's parameter and see it reflected in the caller of the method.

like image 115
Eran Avatar answered Mar 21 '23 05:03

Eran