How many String objects are created by the following code?
String x = new String(\"xyz\");
String y = \"abc\";
x = x + y;
I have visited ma
The answer is 4.
As you have used the new keyword, Java will create a new String object in normal (non pool) memory and x will refer to it. In addition to this, the literal "xyz" will be placed in the string pool which is again another string object.
So, the 4 string objects are:
If your code had been like this:
String x = "xyz";
String y = "abc";
x = x + y;
then the answer would be 3.
Note: String #4 is in non-pool memory because String literals and the strings produced by evaluating constant expressions (see JLS §15.28) are the only strings that are implicitly interned.
Source: SCJP Sun Certified Programmer for Java 6 (Page:434, Chapter 6)