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 (ie setters etc.) to it. 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.
String is immutable object.
Make a class immutable by following these guidelines :
final
, or use static factories and keep constructors private private
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 caller setXXX
methods (that is, avoid the Java Beans convention) 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.
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. Ie no methods exist to modify the internal fields.
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.