javastringstring-pool

What's the point of creating and having an opportunity to create a String object out of string pool


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?


Solution

  • If you look at it from the perspective of the new operator it makes sense.

    new always allocates a new object. That goes for all classes across the board, no exception. It doesn't have any special case behavior for the String class, 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?