Junior — Middle
How is immutability of String type objects implemented in Java?
sobes.tech AI
Answer from AI
In Java, String objects are immutable due to the following implementation features:
- Final class: the
Stringclass is declared asfinal, preventing inheritance and behavior modification. - Final fields: the internal character array (
char[] value) is declared asfinal, and cannot be changed after object creation. - No methods that modify state: all methods that seem to modify a string (e.g.,
concat,replace) actually create and return a newStringobject. - Thread safety: immutability ensures thread safety without additional synchronization.
Example:
String s = "hello";
String t = s.toUpperCase(); // creates a new object, s remains "hello"
Thus, immutability is achieved through control over internal state and the absence of methods that modify it after creation.