Maxim VA
Maxim VA

Reputation: 398

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

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?

Upvotes: 2

Views: 141

Answers (2)

Esc Điệp
Esc Điệp

Reputation: 356

In your case, there are 3 String objects will be created in String pool. greetingand goodbye will be created in heap.

javac has an optimization to put greetingand goodbye to String pool if hello, word and bye are final, the + operation will be performed on compile time instead of run time.
Two of bellow codes will be compiled to the same byte code.

final String hello = "Hello";
final String world = " World!";
final String bye = "Bye";
String greeting = hello + world;
String goodbye = bye + world;
final String hello = "Hello";
final String world = " World!";
final String bye = "Bye";
String greeting = "Hello World!";
String goodbye = "Bye World!";

Upvotes: 3

Ahmad Shabib
Ahmad Shabib

Reputation: 109

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.

Upvotes: 3

Related Questions