String abc[]={"abc"};
String def[]={};
def=abc;
def[0]=def[0]+"changed";
System.out.println(abc[0]);
by changing “def” object, my abc object is changed as well. Beside String[] array has this characteristic what other java object has similar characteristic? can explain more? in order to prevent abc from changed when i changed def, i will have to do def = abc.clone();
You are confusing object mutability/immutability with copying of reference values.
In these diagrams,
[var/index]is a reference variable, and{{an Object}}is an object.Now you make
defreference variable points to the same object asabcreference variable:At this point, the array of length zero is unreferenced, and should be garbage-collectable. We can narrow our discussion to the array of length one. Note that a
String[]is an array of references. With this next line, you changed what the only element in the length one array points to.Note that
{{a String "abc"}}itself was not mutated.[abc]and[def]now points to the same{{a String[1]}}, which is mutable (i.e. you can make the elements of the array, which are references toStringobjects, to point to anything).Actually, that’s not quite accurate. Let’s see what happens if you
clone()an array of references to a mutable typeStringBuilder.I won’t make the diagrams for you this time, but you can easily draw it out on paper. What’s happening here is that even though
clone()makes a second{{a StringBuilder[1]}}object with its own element (i.e.def != abc), that element is pointing to the same{{a StringBuilder}}object (i.e.def[0] == abc[0]).In short:
Integer,String, etc are immutableIf you want more in-depth understanding of the issues, I recommend the following: