3

I want to ask that how many objects are created after execution of the following statement in java..

String str = "a"+"b"+"c"+"d"

In my opinion, only one object should get created and that of StringBuilder. Please correct me and explain the logic behind it..thanks in advance.

4
  • 4
    You are creating a single object of type String. There is no StringBuilder in your line of code... Commented Sep 19, 2018 at 10:34
  • I got to know that this code would get internally changed something like new StringBuilder().append("a").append("b").append("c").append("d")...that's why I think the answer should be 1 Commented Sep 19, 2018 at 10:37
  • @deHaar if the assignment to string reference is literal string , object will not be created. because all will be string pooled. Commented Sep 19, 2018 at 10:47
  • @TheScientificMethod thanks, didn't know that and just commented about the code, not the internals... Commented Sep 19, 2018 at 10:51

1 Answer 1

10

The simple answer is zero objects. That is a compile time constant expression, and the bytecode compiler evaluates it to "abcd" ... before creating the ".class" file.

Actually, with modern JVMs, the instantiation of String objects associated with literals and compile time constant expressions is lazy, so a single String object may be created the first time that statement is executed. But only the first time.

So a more correct answer is either zero or one String objects, depending on:

  • the JVM implementation of string literal interning (lazy or eager), and
  • whether this is the first execution of any statement that uses the "abcd" literal or compile time constant.

Then there is the possibility that the statement might be optimized away by the JIT compiler if str is never accessed.

And it gets even more complicated if you consider the possibility of class unloading.

Sign up to request clarification or add additional context in comments.

15 Comments

If "abcd" is evaluated..wouldn't the compiler make an Object of it?
It won't make an object when the statement is executed!
can you mention an example of a modern JVM?
So the exact answer for the question is 0 or 1, right?
@Maxim - strictly speaking, the answer is "zero or, or either zero or one, depending on the Java version". It depends on what strategy the JVM uses for instantiating literal String objects.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.