Java new String and new StringBuilder in heap behavior

风格不统一 提交于 2019-11-29 13:03:27

You are confusing compile time, load time, and runtime.

A string literal is added to the constant pool at class loading time. Just a mention of a literal anywhere in the class code is enough; you don't even have to execute any line of code in that class.

On the other hand, the expression new String("literal") yields a new String instance each time it is evaluated. That instance is distinct from the one in the constant pool and has a copy of the string value.

StringBuilder acts exactly the same way as String in this respect: it is initialized with a copy of the string literal's value.

First, yes, the string pool and the strings it contains are on the heap. Once a string literal is in the string pool it will never be removed from it. Thus, all string literals in the string pool are reachable until the program is terminated and thus not eligible for garbage collection. (Strings added to the string pool by other means might be eligible for garbage collection.)

If we create a new String object by new String("abc"), then two things happen: first, because of the String literal "abc", a new String object with contents "abc" is created an added to the string pool (if it is not already there). Then, because of the new String(...) constructor, a new String object is created which is a copy of the string literal. This new string is not placed in the string pool. Thus, new String("abc") == "abc" does not hold.

The code new StringBuilder("abc") does not do the same thing as new String("abc"), because it creates a StringBuilder object rather than a String. However, because of the String literal "abc", it does make sure that a String object with contents "abc" is in the string pool.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!