简体   繁体   中英

String immutability question

I know that Java strings are immutable. However, when I run the function below, the output is not what I expect it to be.

    public static void main(String[] args) {
        String s = "wicked";
        String [] ss = new String [1];
        ss[0] = "witch";
        modify(s, ss);
        System.out.println(s+" "+ ss[0]);
    }
    private static void modify(String s, String[] ss) {
        s = "sad";
        ss[0] = "sod";          
    }

The output I get is wicked sod , and not wicked witch as I expected it to be. Is it because I am passing an array reference as the second argument to the modify function as opposed to passing the String object itself? Any clarification is highly appreciated.

You've changed the contents of the array - arrays are always mutable.

The array initially contains a reference to the string "witch". Your modify method changes the array to contain a reference to the string "sod". None of the strings themselves have been changed - just the contents of the array.

(Note that the value of ss[0] isn't a string - it's a reference to a string.)

Is it because I am passing an array reference as the second argument to the modify function as opposed to passing the String object itself?

Exactly. You are passing a reference to a mutable object (the array). When the method changes this object, the changes will be visible outside the method.

Read a VERY good article about passing method parameters by Yoda Parameter passing in Java - by reference or by value?

Strings being immutable means that you cannot change "hello world" to "hello". But you can assign an entire new string. And this is what you are doing here.

You are giving reference to an array object. That's why the contents of the array are changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM