As almost everybody knows strings in Java are immutable. Recently I discovered something that might suggest that it's not always true. Let's try out this code:
System.out.println("-------- BEFORE MODIFICATIONS --------");
String beforeTest = new String("Original");
System.out.println(beforeTest);
java.lang.reflect.Field valueField = String.class.getDeclaredField("value");
valueField.setAccessible(true);
valueField.set("Original", "Modified".toCharArray());
System.out.println("-------- AFTER MODIFICATIONS --------");
System.out.println(beforeTest);
System.out.println("Original");
String test = new String("Original");
System.out.println(test);
String test2 = new String("Original 2");
System.out.println(test2);
the output would be:
-------- BEFORE MODIFICATIONS --------
Original
-------- AFTER MODIFICATIONS --------
Original
Modified
Modified
Original 2
How does this trick work? How does the JVM know which objects should be changed and which not? What mechanism are under the hood of this trick? Why already created beforeTest
string was not changed? Does this trick really derogate the strings are immutable
principle?