Alex Rivera | Logout

Is it correct to call java.lang.String immutable?

Asked 2013-03-07T15:42:57.143
15

This Java tutorial says that an immutable object cannot change its state after creation.

java.lang.String has a field

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

which is initialized on the first call of the hashCode() method, so it changes after creation:

    String s = new String(new char[] {' '});
    Field hash = s.getClass().getDeclaredField("hash");
    hash.setAccessible(true);
    System.out.println(hash.get(s));
    s.hashCode();
    System.out.println(hash.get(s));

output

0
32

Is it correct to call String immutable?

Edit
Report

1 Answer

0

A class can be immutable while still having mutable fields, as long as it doesn't provide access to its mutable fields.

It's immutable by design. If you use Reflection (getting the declared Field and resetting its accessibility), you are circumventing its design.

answered 2013-03-07T15:46:52.523

Your Answer