Counting String objects created by Java code

前端 未结 13 1693
失恋的感觉
失恋的感觉 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:27

    I would say 4 because:

    • x + y will be replaced by the compiler with a StringBuilder implementation. +1
    • new always creates a new object. +1
    • Different constants are different objects. +2

    Here's how:

    String x = new String("xyz"); // 2 objects created: the variable and the constant
    String y = "abc"; // 1 object created: the variable
    x = x + y; // 1 object created: the one by the StringBuilder class
    

提交回复
热议问题