Is it possible to change a String in Java

Everyone knows String object in Java is immutable. It means it is impossible to change its value after the object was created.

It was my answer to the question How can the value of string be changed? I was asked this question on a job interview.

But is it really impossible? Yes, it is… unless you use reflection. The following program demonstrates how you can change the value stored in a String object:

import java.lang.reflect.Field;

public class StringReflection {

    private static void modify(String s) throws Exception {
        Class<?> cl = s.getClass();
        Field f = cl.getDeclaredField("value");
        f.setAccessible(true);
        char[] chars = (char[]) f.get(s);
        chars[0] = 'e';
    }

    public static void main(String[] args) throws Exception {
        String s = "abc";
        modify(s);
        System.out.println(s);
    }

}

You can download the Java file and try it yourself.

Note: Although it is possible to modify the value stored in a String object using reflection, I do not recommend doing so. First of all, the name of the field, value in this case, is implementation-specific. I tested it with Sun/Oracle JRE, other JRE implementations can have another name for this field: it’s private after all. Moreover, it’s not guaranteed that the name does not change in other JRE versions from the same vendor.

In a real application, there would be a SecurityManager which will deny access to private field of the core class.

Additionally, the code that relies on such a hack is unclear and counterintuitive.

You’ve been warned: never use it in a real application.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: