No, with String s = "lol";
, only one object is created. With every string literal, a String
object is created and placed in the string pool. Here, s
just refers to that pooled string. When you say s = new String("lol")
, the string literal is created and pooled, and another string is allocated and assigned to s
, which is a different, yet equal
, string.
UPDATE
I had forgotten about the char[]
that is used internally by a String
object.
String s1 = "lol";
2 objects are created, the char[]
that holds {'l', 'o', 'l'}
and the String
object that references it internally. It's interned in the string pool.
String s2 = new String("lol");
3 objects are created. First, the string literal: 2 objects are created, the char[]
that holds {'l', 'o', 'l'}
and the String
object that references it. It's interned in the string pool as before. Then, the new String
object that gets assigned to s2
: A new String
is created, but it references the same char array as the original string. Two String
objects, and one char[]
object. (The String(String)
constructor may make a copy of the char[]
in the circumstance that the original string's array's length is somehow greater than its count
, but that doesn't appear to be the case here.)