InterviewSolution
| 1. |
Is String an immutable class? Why String has been defined as immutable? |
|
Answer» Yes, String is an immutable class. String is WIDELY used in different situations like sharing as a parameter of a method, loading a class by its name, returning as a value. So, there would be a huge possibility that a String object could be changed without any knowledge of its other users and result in creating difficult to catch bugs in the system. String has been a POPULAR choice as a key in the HASHMAP or HashTable. A good candidate for a key in the HashMap should be immutable. If String had been mutable and changes its state, it might result in retrieving the wrong value for the same key or not finding it at all. String LITERALS are fetched from the String pool instead of creating it every time. Had the String been mutable, this would not be possible as it could not identify whether the value exists in the pool after any CHANGE in its state. |
|