How many Java objects are generated by this - new String(“abcd”)

后端 未结 2 1071
情歌与酒
情歌与酒 2020-11-30 13:02
String s = new String(\"abcd\");
相关标签:
2条回答
  • 2020-11-30 13:55

    You're creating one object. The JVM will create another object behind-the-scenes because it interns the string created by the constant at class load, but that's a JVM thing (you haven't asked it to intern). And more to the point, you can be fairly certain that having done:

    String s1 = new String("abcd");
    

    once, then

    String s2 = new String("abcd");
    

    will only create one object.

    The JVM creates the the other (first) String object at class load: The compiler puts the string in the string constants area in the .class file. Those are read into the class's constant pool and interned when the class is loaded.

    So when that line of code executes, a single String is created. But the fact of having that line in the class creates two: One for the constant which is created when the class is loaded, and one for that line of code.

    0 讨论(0)
  • 2020-11-30 14:07

    There's one string in the intern pool, which will be reused every time you run the code.

    Then there's the extra string which is constructed each time you run that line. So for example:

    for (int i = 0; i < 10; i++) {
        String s = new String("abcd");
    }
    

    will end up with 11 strings with the contents "abcd" in memory - the interned one and 10 copies.

    0 讨论(0)
提交回复
热议问题