Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java String really immutable?

Tags:

java

In String source it looks like the hash code value (private int hashCode) is set only if the method public int hashCode() was called at least once. That means a different state. But will the hashCode be set in the following example:

String s = "ABC"; ? 

Will

String s = "ABC"; 
s.hashCode();

help with subsequent comparisons performance?

like image 553
Alex Avatar asked Dec 01 '22 09:12

Alex


2 Answers

Technically the string has changed. Some internal field is altered the first time you call hashCode().

But for all practical reasons the string is immutable. The value of the hash code doesn't change due to a call to hashCode(), it simply isn't calculated until the first call. To any consumer of a string, the string is immutable. And that's what matters.

like image 39
Greg Avatar answered Dec 25 '22 10:12

Greg


Immutable means that, from an outside perspective, the value of the object cannot be changed.

If hashCode is being cached, the internal state of the object may be different after the first hashCode call. But that call is read-only, and you can't change the value of the object as it appears to the outside world.

In other words, it's still the same string.

like image 122
Robert Harvey Avatar answered Dec 25 '22 10:12

Robert Harvey