Counting String objects created by Java code

前端 未结 13 1734
失恋的感觉
失恋的感觉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 14:28

    The answer is 4.

    As you have used the new keyword, Java will create a new String object in normal (non pool) memory and x will refer to it. In addition to this, the literal "xyz" will be placed in the string pool which is again another string object.

    So, the 4 string objects are:

    1. "xyz" (in non-pool memory)
    2. "xyz" (in pool memory)
    3. "abc" (in pool memory)
    4. "xyzabc" (in non-pool memory)

    If your code had been like this:

    String x = "xyz";
    String y = "abc";
    x = x + y;
    

    then the answer would be 3.

    Note: String #4 is in non-pool memory because String literals and the strings produced by evaluating constant expressions (see JLS §15.28) are the only strings that are implicitly interned.

    Source: SCJP Sun Certified Programmer for Java 6 (Page:434, Chapter 6)

提交回复
热议问题