StringBuilder sb = new StringBuilder("mainWord"); sb.append("secondWord" + "thirdWord"); System.out.println(sb); The append method here accepts a String as a parameter. My question is, how does this not allocate memory for this String in the heap?
Our difference between String and StringBuilder is that a new object is created in memory for String, but not for StringBuilder. However, the append method still accepts a String as a parameter, which logically should be stored in memory somewhere.
Stringis already allocated.11: ldc #14 // String secondWordthirdWordStringBuilderoverString(especially in loops) is to prevent the creation of uneccessary amounts ofString:("one" + "two") + "three"(via a loop) will create the intermediate string representations, whereasStringBuilderwill hold the data and compile it into a string at the end (usually in an exponentially growing character array, akin toArrayList) via#toString, which#printlnimplicitly calls onsb."one" + "two"(as literal code) will get compiled down to"onetwo": the compiler sees two constants and optimizes away the extra addition."onetwo"is actually stored in "static memory": it exists within the compiled class file itself, and can be accessed as such. When you want to dynamically concatenate strings (in a way the compiler can't optimize), you will create a newStringobject when you finish adding them together. So loops (hard to pre-optimize) will create tens if not hundreds of intermediate strings.