☕ Java Beginner

Why is String immutable in Java?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Java basics — a prerequisite for any developer role.

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.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Java answers easy to follow.