String x = new String("xyz"); String y = "abc"; x = x + y;
How many objects Stringwill be created in this code?
String
There will be at least four objects:
"xyz"
"abc"
String x = new String("xyz");
There is one: "xyz"- interned string.There are two: new String("xyz").
new String("xyz")
String y = "abc";
There are three: "abc"- interned string.
x = x + y;
There are four. Because immutable lines necessary to create a third string object: new String("xyzabc").
new String("xyzabc")
Perhaps there may be a fifth object, because the compiler can use StringBuilder to perform string concatenation.
StringBuilder s = new StringBuilder(x); s.append(y); x = s.toString();
, String ( ), . ...
, , :
new String("xyz") , "xyz".
x + y .
x + y
, String y = "abc"; . , y. , String , .
y
, , char[], String. StringBuilder. .
char[]
StringBuilder
, String. , String String , , , ... String.intern String.
String.intern
: ZERO . Java, Java , . (!!)
x: String String
"abc": , Java String , .
x: concatenation of two strings is converted to StringBuilder.append (X) .append (Y) .toString (), so another object is created here.