Join waitlist
JavaCommunity question

Why is String immutable in Java (actual reason not the rattafied one)

Asked by Gaurav Sethi 1 month ago 2 answers 10 votes

Every interview I say "security and caching" and move on before they ask a follow up. Can someone explain properly

2 answers

Farhan Ali1 month agoMost voted9

Main ones:

1. String pool. Java reuses the same object for identical literals. If strings could change, changing one would change it for everyone using that literal. Immutability is what makes the pool safe.

2. Security. Things like file paths and DB urls are strings. If they were mutable, code could pass a check with one value and then change it after the check.

3. Thread safety, you can share them between threads without locks.

4. hashCode is cached inside String. That only works because the content can never change, and it's why String keys in HashMap are cheap.

If you can explain 1 and 4 with an example you're fine in most interviews.

Gaurav Sethi1 month ago1

the example for 2 is what I was missing. thanks Farhan

Related questions

Go deeper

Want the full explanation, not just an answer?

Structured lessons on DSA, core CS, Java and interview skills, each ending in a quiz so you know it stuck.