How many String objects will be created in the java string pool?

Maxim VA :
String hello = "Hello";
String world = " World!";
String bye = "Bye";
String greeting = hello + world;
String goodbye = bye + world;

I know with the first three that there's a new object created in the java String pool, but with the last two i'm not sure.

Are there just references to both string pool objects in the greeting and goodbye variables, or are there 2 new String objects created?

Ahmad Shabib :

In you example just the first 3 will be created in the string pool and the last two will be a string object in the heap. The reason that when you concatenate string using the + operator it will check if the resulting string is existed in the string pool then it will return a reference otherwise it will create a new String object even though the strings that you are using to create the new one are already in the pool. You can test that when you do the following:

greeting == "Hello World!" 
goodbye == "Bye World!"

it will return false in both cases which shows that these are not in the pool.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127700&siteId=1