Why String is Immutable in Java — Java Technical Interview Questions & Answers
Why String is Immutable in Java
Why String is Immutable in Java
- String is immutable so the String Pool can safely reuse literals — two "Java" literals can point to the same object. If String could change, one variable would surprise the other.
- Immutability also helps HashMap keys (hashCode stays stable) and security (class names, passwords not silently edited).
- When you need to change text many times, use StringBuilder. Don’t fight String with + in a loop.
- Let's take this on the board with one tiny Main class — no extra files. Why String is Immutable in Java — output: Hi then Hi Java. concat without assign leaves a as Hi. a = a.concat(...) creates a new String. Start from main, go line by line, and stop at each print. That output is the proof for Why String is Immutable.
Technical Interview Tip: Why? Pool + HashMap keys + security. Then say StringBuilder when you need to edit.
Code Examples for Why String is Immutable in Java
Example
// Why String is immutable
public class Main {
public static void main(String[] args) {
String a = "Hi";
a.concat(" Java");
System.out.println(a); // still Hi
a = a.concat(" Java");
System.out.println(a); // Hi Java
}
}Why String is Immutable in Java — output: Hi then Hi Java. concat without assign leaves a as Hi. a = a.concat(...) creates a new String.
How to Explain Why String is Immutable in Java to an Interviewer
Why is String immutable?
String Pool safety HashMap keys Security
What if you need to change text?
StringBuilder