String s = new String(\"abcd\");
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.
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.