Why is String immutable in Java?
Explain the reasons with examples.
Explain the reasons with examples.
Immutability makes String thread-safe and safe to use as HashMap keys (hashCode is cached).
String objects are cached in the String pool; immutability makes sharing them safe.
A repeated question row simply adds more answers to the same question.
Security: class names and file paths passed as strings cannot be changed after validation.
Performance: hash code caching.