Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the new Object of String created when we concat using + operator

I know this might be quite basic and probably pretty straight forward but i cannot clearly understand what will happen in this situation, so, here it goes.

In the following code:

String str1 = "Hello";
String str2 = "World";
String str3 = new String("HelloWorld");
String str4 = str1 + str2;

i know that str1 and str2 will create an object "Hello" and "World" respectively inside the String Constant Pool. While for str3 a new object is created outside the String Constant Pool which is pointing to "HelloWorld" that is created inside String Constant Pool.

My question is, what will happen if i concat 2 or more string (using '+' or concat() method)?

Will a new object be created outside the pool just like in the case of String str3 or will str4 point directly at the object "HelloWorld" inside the String Constant Pool

PS : And IF it is the case similar as creation of new object outside the pool, then how does it happen without using the new keyword?

like image 452
404 Brain Not Found Avatar asked Jun 01 '18 05:06

404 Brain Not Found


1 Answers

First of all String s = new String("abs"); It will create two objects, one object in the pool area and another one in the non-pool area because you are using new and as well as a string literal as a parameter.

String str1 = "Hello";
String str2 = "World";
String str3 = new String("HelloWorld");
String str4 = str1 + str2;

Till now you have five String objects, four in String Constant Pool and one in Heap. So your str4 is a new object altogether inside the String Pool, Please check the below code also,

 String str5="HelloWorld"; //This line will create one more String Constant Pool object because we are using the variable name as str5.
 String str6="HelloWorld";////This line will not create any object, this will refer the same object str5.

For test

System.out.println(str3==str4); //false
System.out.println(str4==str5);//false
System.out.println(str5==str6);//true
like image 189
ajay tomar Avatar answered Oct 02 '22 19:10

ajay tomar