When using new String(\"abc\")
, we kn
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.