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?
It is a combination of:
set
methods provided - so they cannot be changed indirectly either.String
is final
- so you cannot add mutability (i.e. setters etc.) to it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With