string
Why is String immutable in Java?
Reasons for Immutability:
- String Pool: Efficient space management by sharing string literals. If strings were mutable, changing one would affect all other shared references.
- Security: Strings are frequently used as parameters for network connections, database URLs, and file paths. Immutability ensures these cannot be changed mid-process.
- Thread Safety: Immutable objects are inherently thread-safe and can be shared across threads without synchronization.
- Caching Hashcode: The hashcode is cached during creation, making strings ideal keys for HashMaps.