Why is String immutable in Java?
Strings in Java are immutable because:
-
Security: It prevents accidental or malicious changes (e.g., in passwords or file paths).
-
Thread-Safety: Immutable objects are inherently thread-safe.
-
Caching: Strings are stored in the String Pool for reuse, saving memory.
-
Performance: Immutable objects can be safely shared without copying.
In short, immutability ensures safety, efficiency, and reliability.