Does concatenating strings in Java always lead to new strings being created in memory?

前端 未结 3 626
日久生厌
日久生厌 2020-11-27 06:29

I have a long string that doesn\'t fit the width of the screen. For eg.

String longString = \"This string is very long. It does not fit the width of the scr         


        
3条回答
  •  自闭症患者
    2020-11-27 07:14

    Does concatenating strings in Java always lead to new strings being created in memory?

    No, it does not always do that.

    If the concatenation is a compile-time constant expression, then it is performed by the compiler, and the resulting String is added to the compiled classes constant pool. At runtime, the value of the expression is the interned String that corresponds to the constant pool entry.

    This will happen in the example in your question.

提交回复
热议问题