Interview Q&A / Java

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Why is the String class immutable in Java?

SHORT ANSWER

Once created, a String cannot change. This makes the string pool safe to share, lets the hash code be cached for fast HashMap use, keeps strings thread-safe, and stops callers from altering values used for security, such as file paths or URLs.

Explain it simply

A String is like a printed railway ticket. If the name could be changed after printing, the TTE could never trust it. Because it cannot be altered, many people can safely hold the same ticket, and everybody sees the same details.

Example

java
String s = "Ravi";
s.concat(" Kumar");           // result is thrown away
System.out.println(s);        // prints: Ravi

s = s.concat(" Kumar");       // new String, s now points to it
System.out.println(s);        // prints: Ravi Kumar

What to say in the interview

"String is final and its internal data cannot be changed, so every operation like concat or toUpperCase returns a new object. That allows four things. The string pool can reuse one object for many references. The hash code is computed once and cached, which makes Strings excellent HashMap keys. Strings are automatically thread-safe. And security-sensitive values like a database URL cannot be modified after validation."

Common mistakes

  • Thinking s.concat("x") changes s.
  • Saying immutability means the variable cannot be reassigned. That is final, not immutable.

#java#strings#immutability

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.