Why is String immutable in Java?
Must Know🌱 FresherOnce a String is created, its internal character data can never change — every "modifying" method (concat, replace, toUpperCase...) returns a new String object. Java made String immutable for several compounding reasons:
- String pool safety — literals are shared/reused across the whole program; if one reference could mutate a literal, every other reference to that literal would silently corrupt too.
- Thread safety — an immutable object is inherently safe to share across threads with no synchronization.
- Security — class names, file paths, network hosts, and DB URLs are passed around as Strings; if they could be mutated after a security check, that check could be bypassed.
- Safe hashCode caching — since the content can never change, String can compute its
hashCode()once and cache it, making repeated HashMap lookups on String keys fast.