How many String objects will be created here?

String x = new String("xyz");
String y = "abc"; 
x = x + y; 

How many objects Stringwill be created in this code?

+5
source share
4 answers

There will be at least four objects:

  • Interned string "xyz"
  • Copy internment string "xyz"
  • Interned string "abc"
  • The result of concatenating two strings.
+12
source
String x = new String("xyz");

There is one: "xyz"- interned string.
There are two: 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").

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();
+7
source

, String ( ), . ...

, , :

  • new String("xyz") , "xyz".

  • x + y .

, String y = "abc"; . , y. , String , .


, , char[], String. StringBuilder. .

, String. , String String , , , ... String.intern String.


: ZERO . Java, Java , . (!!)

+6

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.

+1
source

All Articles