Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many String object..?

Tags:

java

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.

like image 256
Saurabh Agarwal Avatar asked Apr 02 '13 09:04

Saurabh Agarwal


1 Answers

If you write(literals or constants)

String str = "ObjectOne"+"ObjectTwo";

it's equivalent to

String str = "ObjectOneObjectTwo"; // compiler optimize it so one Object
like image 117
Simon Dorociak Avatar answered Oct 01 '22 00:10

Simon Dorociak