Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many Java string objects created in the code String s="abc"+"xyz";?

Tags:

How many Java string objects will be created in the following statement?

String s = "abc" + "xyz"; 

I guess three?

like image 293
Deep Avatar asked Jul 05 '11 05:07

Deep


People also ask

How many string objects are created in Java?

The answer is: 2 String objects are created.

How many objects are created with this code string's new string ABC );?

Two objects will be created for this: String s = new String("abc");

How many string objects are created in ABCD?

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.

How many objects will be created for the Java program string s new string learning?

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.


2 Answers

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()
like image 140
Bohemian Avatar answered Nov 09 '22 09:11

Bohemian


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].

References

[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

like image 32
Nayuki Avatar answered Nov 09 '22 09:11

Nayuki