How is memory alocated with Strings in Java?

喜你入骨 提交于 2020-01-05 07:08:14

问题


Having the following code:

String s="JAVA";
for(i=0; i<=100; i++)
     s=s+"JVM";

How many Strings are created? My guess is that 103 Strings are created:

1: the String "JAVA" in the String pool

1: the String "JVM" also in the String pool

101: the new String s is created every time in the loop because the String is an Immutable class


回答1:


String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

In your case, 103 strings are created, one for each in the loop and the two Strings Java and JVM.




回答2:


When using '+' operator on string, JAVA replace it by a StringBuilder each time.

So for each loop you create a StringBuilder that concat the two strings (s and JVM) with the method append() then its converted to a String by the toString() method




回答3:


Compile-time string expressions are put into the String pool. s=s+"JVM" is not a compile-time constant expression. so everytime it creates a new string object in heap.

for more details see this Behavior of String literals is confusing



来源:https://stackoverflow.com/questions/42223176/how-is-memory-alocated-with-strings-in-java

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