I know that String objects are immutable, and I can create String object in heap (String s1 = new String("text1") and in string pool (String s2 = "text2"). So what's the point of having an opportunity to create a String out of string pool? Why Java implicitly doesn't create all String object in the string pool? Maybe to prevent the processor from iteration through string pool if chances that some rare string would be there?
What's the point of creating and having an opportunity to create a String object out of string pool
63 Views Asked by Denys_newbie At
1
If you look at it from the perspective of the
newoperator it makes sense.newalways allocates a new object. That goes for all classes across the board, no exception. It doesn't have any special case behavior for theStringclass, nor any other class. It is completely class agnostic.I don't see any need for an optimization to be added, either. Writing
new String("literal")is usually a mistake. Why bother speeding up a mistake?