☕ Java Beginner

Why is String immutable in Java?

Answer

A String in Java is immutable — once created, its value cannot be changed. Any operation that appears to modify a String (like concat or replace) actually creates a new String object. This design was intentional for several reasons: security (strings are used as keys in HashMaps and network connections — immutability prevents tampering), thread safety (immutable objects can be shared between threads without synchronization), and performance via the String pool (the JVM can cache and reuse String literals). String objects are stored in a special area of the heap called the String Constant Pool.