How many String object..?

java

Solution

If you write(literals or constants)

String str = "ObjectOne"+"ObjectTwo";

it's equivalent to

String str = "ObjectOneObjectTwo"; // compiler optimize it so one Object

Problem

Me and my friend was discussing on Strings and we stuck on this: ``` String str = "ObjectOne"+"ObjectTwo"; ``` He says total three Object will be created and I say one object will be created. His logic behind 3 objects is: one for "ObjectOne" and one for "ObjectTwo" and third one is the concatenated version of two String objects. My logic behind one object is at compile time both the string objects will be concatenated in the byte code as: ``` String str = "ObjectOneObjectTwo"; ``` And at run time only one object will be created in such a way. What is the truth behind this.

Original source

Related problems