Counting String objects created by Java code

前端 未结 13 1695
失恋的感觉
失恋的感觉 2020-12-05 14:04

How many String objects are created by the following code?

String x = new String(\"xyz\");
String y = \"abc\";
x = x + y;

I have visited ma

13条回答
  •  既然无缘
    2020-12-05 14:53

    new String(”xyz“) for sure creates a new instance. "abc" and "xyz" are stored in the class constant pool, x = x + y creates a StringBuilder under the hood and therefore creates a new String, so the count of strings are 4 here.


    The compiler might substitute x + y with a constant ("xyzabc"), though.

提交回复
热议问题