Benji said:
That doesn't have anything to do with strings being immutable. Immutable
No, it shows Strings are not passed by value. As in "Notice the string
is left untouched (because it was passed by value) ...". (The reference
is passed by value.)
types (String, Integer) depend on immutability for optimizations. Even if
calling setAccessible(true) could let you modify a String, it would really
screw up your program. For example...if I have
String a = "foo";
String b = "foo";
You don't need to change final fields to modify String. You can get the
value array. You can fiddle with the hashCode cache. In old versions,
value is not final. synchronize also modifies the object.
And I modify a, I will also end up modifying b because of the way that the
compiler stores Strings. (since they're immutable, they might as well be
the same object)
Yup.
Another optimization that a compiler can make (that I'm not sure if it does
or not), if you have
String a = "sub";
String b = "I live on a submarine";
a can be stored as a substring of b. I believe current JVMs do this.
Not on the version I use.
class InternSubstring {
public static void main(String[] args) throws Exception {
String a = "$sub$";
String b = "I live on a $sub$marine";
show(a);
show(b);
}
private static void show(String str) throws Exception {
System.err.println(
field("value", str)+", "+
field("offset", str)+", "+
field("count", str)
);
}
private static String field(
String name, Object object
) throws Exception {
java.lang.reflect.Field field =
String.class.getDeclaredField(name);
field.setAccessible(true);
return name+" <"+field.get(object)+">";
}
}