2
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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I was checking if it's in the pool or not with the == operator, and as far as i can tell it's not even chekcing the String pool when using the + operator. When i create a new variable with the same text as greeting (so it should be in the string pool) and compare that with the concatinated variable, it still returns false. (hope that makes sense)
I don't think there is a checking here. Without compiler optimization, the + operation on Strings is actually creating StringBuilder object, invoking append and toString methods. For example, with a is a String and b is whatever, a+b is the same as new StringBuilder(a).append(b).toString()
3

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!";

2 Comments

The 5 objects seems correct, although as Ahmad Shabib mentions when i do the check with and operator and not the equals method the last two don't seem to be in the string pool.
Sorry, I make a mistake. I'm going to edit my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.