Reputation: 87
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?
Upvotes: 4
Views: 327
Reputation: 196
The usual way to make a class immutable is to ensure that:
String is a bit special, at least in the Sun/Oracle implementation in that it does not actually follow this procedure. The implementation has a mutable field in which it caches the hash code of the object. So while there is a method that changes the internal state of the object (hashCode
), this state change does not change the behaviour of the object in any way. Any subsequent calls to hashCode
will run faster, but the result won't be any different.
Upvotes: 0
Reputation: 65869
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.Upvotes: 11
Reputation: 364868
String is immutable object.
Make a class immutable by following these guidelines :
final
, or use static factories and keep constructors privateprivate
and final
setXXX
methods, but any method which can change state
if the class has any mutable object fields, then they must be defensively copied when passed between the class and its callersetXXX
methods (that is, avoid the Java Beans convention)Upvotes: 3
Reputation: 272407
Being final means it can't be derived from. That doesn't confer immutability
Immutability is achieved by encapsulation and not providing any means to amend the internally held character array. I.e. no methods exist to modify the internal fields.
Upvotes: 1
Reputation: 17049
A pool of strings, initially empty, is maintained privately by the class String.
You should look at the JavaDoc of String:
public native String intern();
See:
Upvotes: 0
Reputation: 786011
No that's not the correct answer. String achieves immutability because it doesn't provide you any method to change its internal contents. Thus you can instantiate a String object, assign a reference to it but cannot change its contents once initialized.
Upvotes: 4
Reputation: 9231
The final
keyword is not the same as immutability. String
is immutable as it does not define any methods that allow a user to change its content and it is final, removing the possibility to change things in a subclass.
Making something like a List
instance variable final will still allow you to change its contents, making it mutable.
Upvotes: 2