When does StringBuffer adds strings to the String Pool?

淺唱寂寞╮ 提交于 2019-11-29 12:57:44

When I define a StringBuffer variable with new, this string is not added to the String pool, right?

Creating a StringBuffer does not create a String at all.

Now, when I define another StringBuffer but not with new, I define it as StrPrev.append("XXX") suddenly it is.

This is totally confused:

  • When you call strBuff.append("XXX") you are NOT defining a new StringBuffer. You are updating the existing StringBuffer that strBuff refers to. Specifically, you are adding extra characters to the end of the buffer.

  • You only get a new String from the StringBuffer when you call strBuff.toString().

  • You only add a String to the string pool when you call intern() on the String. And that only adds the string to the pool if there is not already an equal string in the pool.

  • The String object that represents the literal "XXX" is a member of the string pool. But that happens (i.e. the String is added to the pool) when the class is loaded, not when you execute the append call.

(If you teacher told you that StringBuffer puts strings into the Java string pool, he / she is wrong. But, given your rather garbled description, I suspect that you actually misheard or misunderstood what your teacher really said.)

"XXX" in StrPrev.append("XXX") is a string literal that is interned at class loading time (class loading time of the class that contains the code).

"XXX" is not added to the pool by the StringBuffer.

From the JLS section 3.10.5:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances

From the JLS section 12.5:

Loading of a class or interface that contains a String literal (§3.10.5) may create a new String object to represent that literal. (This might not occur if the same String has previously been interned (§3.10.5).)

buf.append("XXX") followed by buf.toString(), and then returning the string to the pool. With the pool in place, only one StringBuffer object is ever allocated.

Actually your teacher is referring to XXX . which goes to StringPool because all string literals written in java program goes to StringPool while execution...

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