Search code examples
javastringimmutabilitystring-pool

Is this compromise to string immutablity in java?


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?


Solution

  • No, you're not missing anything. When you use reflection and make inaccessible fields accessible, you explicitely ask to lose all the guarantees offered by the type when it's used in a "normal" OOP way.