Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

java - 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?

question from:https://stackoverflow.com/questions/65893789/whats-the-point-of-creating-and-having-an-opportunity-to-create-a-string-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...