Fundamentals 5 min read

Is java.lang.String Truly Immutable? Reflection Can Modify Its Value in Java 11 but Not in Java 17

This article demonstrates how reflection can alter the internal byte array of a java.lang.String in Java 11, causing both identical literals to change, explains why the hashCode remains unchanged, and shows that Java 17 blocks such modifications with runtime exceptions.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Is java.lang.String Truly Immutable? Reflection Can Modify Its Value in Java 11 but Not in Java 17

Java strings are commonly described as immutable, but using reflection it is possible to access and modify the private byte[] value field that stores the characters. The article provides a complete example that runs on Java 11, where the modification succeeds and affects all string literals sharing the same internal array.

package com.example.demo;

import java.lang.reflect.Field;
import java.util.Arrays;

public class Demo {
    public static void main(String[] args) throws ReflectiveOperationException {
        String a = "崔认知";
        String b = "崔认知";
        System.out.println("反射更改String前");
        System.out.println(a);
        System.out.println(b);
        System.out.println(a.hashCode());
        System.out.println(b.hashCode());

        Field value = String.class.getDeclaredField("value");
        value.setAccessible(true);
        byte[] byteValue = (byte[]) value.get(a);
        Arrays.fill(byteValue, (byte)0);

        System.out.println("反射更改String后");
        System.out.println(a);
        System.out.println(b);
        System.out.println(a.hashCode());
        System.out.println(b.hashCode());
    }
}

The key operation is retrieving the private final byte[] value field and overwriting its contents with zeros. After the change, both a and b print as empty strings, demonstrating that the modification propagates to other references that share the same string pool entry.

Even though the characters change, the hashCode() of the string remains the same because the hash code is cached inside the String object. The source of this caching is the private int hash field and the implementation of hashCode() that stores the computed value on first use.

/** Cache the hash code for the string */
private int hash; // Default to 0

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        hash = h = isLatin1() ? StringLatin1.hashCode(value)
                               : StringUTF16.hashCode(value);
    }
    return h;
}

Running the program on Java 11 also produces a series of illegal‑reflective‑access warnings, indicating that such manipulation is not officially supported and may be restricted in future releases.

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.example.demo.Demo ... to field java.lang.String.value
WARNING: Please consider reporting this to the maintainers of com.example.demo.Demo
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

When the same code is executed on Java 17, the reflective access is denied outright: the JVM throws an InaccessibleObjectException and the program terminates, confirming that the newer module system enforces stricter access controls.

In summary, the immutability of java.lang.String can be bypassed via reflection in older Java versions, but the change also reveals internal caching behavior and the risks of relying on such hacks. Starting with Java 17, the platform prevents these modifications, reinforcing the intended immutable contract.

JavareflectionstringimmutabilityJava11Java17
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.