How many Java string objects will be created in the following statement?
String s = "abc" + "xyz";
I guess three?
The answer is: 2 String objects are created.
Two objects will be created for this: String s = new String("abc");
Correct Answer: C In statement 2, first of all “abcd” is created in the string pool. Then it's passed as an argument to the String new operator and another string gets created in the heap memory. So a total of 3 string objects gets created.
By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap.
The compiler creates 1 String per JVM start, because the compiler can determine the resulting String at compile time, it is interned and statically stored in the JVM's String Table.
FYI, if the statement were concatenating variables (not determinable at runtime), 1 String would be created, but it would create a StringBuilder
too. The code would compile to:
new StringBuilder().append(abcVar).append(xyzVar).toString()
The answer is one global String object per program run, and zero new String objects per statement execution. This is because the Java Language Specification says the expression "abc" + "xyz"
is a compile-time constant [0], and that no new String object will be created when the statement is executed [1].
[0]: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313
Examples of constant expressions:
"The integer " + Long.MAX_VALUE + " is mighty big."
[1]: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1
If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28)) that is the concatenation of the
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With