[Solved] Is Java String immutable? [duplicate]


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

solved Is Java String immutable? [duplicate]