Counting String objects created by Java code

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

    Line 1:String x = new String("xyz");
    Line 2:String y = "abc";
    Line 3:x = x + y;
    

    Strings are Immutable so if any existing string variable need to be changed then new object will be created for assignment. Line 1,Line 2 are string objects where as Line 3 is modification of the existing string variable so new allocation need to be done to add x+y. So it should create creates 3 Objects.

提交回复
热议问题