Is Java String immutable? [duplicate]

一个人想着一个人 提交于 2019-12-13 23:21:26

问题


I don't understand this code, why my string c don't changing in main method but changing in changeString. Can you explain me?

class MainClass {
    public static void main(String[] args) {
        String c = "lalala";
        changeString(c);
        System.out.println("str in main = "+c);
    }

    public static void changeString(String str) {
        str = str + "CHANGE!!!";
        System.out.println("str in changeString = "+str);
    }

}

Result:

str in changeString = lalalaCHANGE!!!
str in main = lalala

回答1:


Yes, the java string is immutable.

In changeString, you are passing in a reference to the string lalala and then you are changing the reference to one that points to lalalaCHANGE!!!. The original string object is not changed, and the reference in main still refers to that original object.

If you were to use a StringBuilder instead of a string, and append CHANGE!!! to that StringBuilder, then you would see the change reflected in viewing it at main:

class MainClass {
    public static void main(String[] args) {
        StringBuilder c = new StringBuilder("lalala");
        changeString(c);
        System.out.println("str in main = "+c.toString());
    }

    public static void changeString(StringBuilder str) {
        str.append("CHANGE!!!");
        System.out.println("str in changeString = "+str.toString);
    }

}

In this changed version you would get:

str in changeString = lalalaCHANGE!!!
str in main = lalalaCHANGE!!!



回答2:


Is Java String immutable?

String is immutable and it means that you cannot change the object itself, but you can change the reference ofcourse.

So when you do this in your changeString method:

str = str + "CHANGE!!!";

a new string memory object is created. But your c reference in main method is still pointing to the old sting memory object and hence prints lalala.




回答3:


String is immutable, of course:

Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

http://docs.oracle.com/javase/tutorial/java/data/strings.html

str = str + "CHANGE!!!";

this code is returning a different String and replacing its reference into you variable, but the original String didn't change.




回答4:


Yes ,Java String is Immutable.

Strings are constant; their values cannot be changed after they are created.

And String in java has very special treatment

Read more here :

  • Why doesn’t == work on String?



来源:https://stackoverflow.com/questions/18634966/is-java-string-immutable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!