All of us know that String is immutable in java - content can not be changed once the string is created.
String uses character array char[] value
to store string content, here is the java code -
/** The value is used for character storage. */
private final char value[];
What if we get access to the field values[]
and we change it? See this code -
String name = "Harish";
System.out.println(name); // Harish
Field field = name.getClass().getDeclaredField("value");
field.setAccessible(true);
char[] value = (char[]) field.get(name);
value[0] = 'G';
value[1] = 'i';
System.out.println(Arrays.toString(value)); // [G, i, r, i, s, h]
System.out.println(name); // Girish
This way, i think, we can change content of the string which goes against the String Immutability Principle.
am i missing something?