Strings – How do they work?

How do String objects work in Java? How does term “immutable” exactly apply to string objects? Why don’t we see modified string after passing through some method, though we operate on original string object value?


a String has a private final char[] . when a new String object is created, the array is also created and filled. it cannot be later accessed [from outside] or modified [actually it can be done with reflection, but we’ll leave this aside].

it is “immutable” because once a string is created, its value cannot be changed, a “cow” string will always have the value “cow”.

We don’t see modified string because it is immutable, the same object will never be changed, no matter what you do with it [besides modifying it with reflection]. so “cow” + ” horse” will create a new String object, and NOT modify the last object.

if you define:

void foo(String arg) {
  arg= arg + " horse";

and you call:

String str = "cow";

the str where the call is is not modified [since it is the original reference to the same object!] when you changed arg, you simply changed it to reference another String object, and did NOT change the actual original object. so str, will be the same object, which was not changed, still containing "cow"

if you still want to change a String object, you can do it with reflection. However, it is unadvised and can have some serious side-affects:

    String str = "cow";
    try { 
    Field value = str.getClass().getDeclaredField("value");
    Field count = str.getClass().getDeclaredField("count");
    Field hash = str.getClass().getDeclaredField("hash");
    Field offset = str.getClass().getDeclaredField("offset");
    char[] newVal = { 'c','o','w',' ','h','o','r','s','e' };
    } catch (NoSuchFieldException e) {
    } catch (IllegalAccessException e) {}

Leave a Reply

Your email address will not be published. Required fields are marked *