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

String s = new String("abcd");
+3
source share
4 answers

The first pool has one line that will be reused each time the code is run.

Then an extra line is added, which is created each time this line is run. For example:

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

will end with 11 lines with the contents of "abcd" in memory - interned and 10 instances.

+9
source

You create one object. The JVM will create another object off-screen because interns is a string created by a constant when the class is loaded, but this is the JVM thing (you did not ask for it intern). And what's more, you can be pretty sure you did:

String s1 = new String("abcd");

once then

String s2 = new String("abcd");

.

JVM () String : .class. , .

, , String. : , , .

+2

In this statement, the first object is created with an "abcd" value, and it enters the string pool. the new keyword always created a new object, so when executing a new String ("abcd") it created a new object. Thus, a common two objects will be created.

-1
source

One object is created, which is the string = "abcd". You only call once.

-2
source

Source: https://habr.com/ru/post/1796260/


All Articles