Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How String achieves immutability?

Tags:

java

In one of the interview I was asked 'How String is made immutable?' As i wasnot sure about the answer, i didnot reply. I asked the interviewer later regarding the same. Answer was String class is final that's how immutability is achieved.

Is that the correct answer? if yes, even StringBuffer is also marked as final class. Then why not StringBuffer is immutable?

like image 915
Murali Avatar asked Nov 29 '22 13:11

Murali


1 Answers

It is a combination of:

  1. Fields are private - so you cannot change them directly.
  2. No set methods provided - so they cannot be changed indirectly either.
  3. String is final - so you cannot add mutability (i.e. setters etc.) to it.
like image 173
OldCurmudgeon Avatar answered Dec 04 '22 15:12

OldCurmudgeon