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
modifymethod 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.)