The String[]
array does not contain references to string variables, as some people might say. The String[]
array contains values (or more exactly references to values), but not references to variables.
public class Main {
public static void main(String[] args) {
String one="1";
String two="2";
String[] arr = {one, two};
System.out.println(arr[1]);
// Result is "2"
two="3";
System.out.println(arr[1]);
// Result is still "2"
}
}
So, as you can see, the arr[1]
is not a reference to String two
. It got the value from the variable two
and that's it. Changing the variable two
did not affect arr[1]
.
The same thing about ArrayList
:
//...
String one="1";
String two="2";
List arr2 = new ArrayList<String>();
arr2.add(one);
arr2.add(two);
System.out.println(arr2.get(0));
// Result is "1"
one = "one";
System.out.println(arr2.get(0));
// Result is still "1", not "one"
//...
Therefore the array String
elements are immutable (which is logical, because String
s are immutable).
The mutability occurs when you pass the arrays arr
or arr2
themselves to a procedure, not their immutable String
elements.
For example:
change(arr);
// where arr is a String[] array of {"1","2"}
// see the procedure below
System.out.println(arr[0]);
// Result is "one"
// ...
static void change(String[] someArray){
someArray[0]="one";
}
In other words, the array is passed by reference (=mutable), but its string elements are passed by value (immutable).