Click here to Skip to main content
15,795,398 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,
Please the code below returns false meaning that the 2 String references below are pointing to 2 different objects in memory.
String str1 = "GoodMorning";
String str2 = "Good";
String str3 = "Morning";
str2 += str3; // Line 4
System.out.println("str2 == str1"); // output is false.

Question - Why does java saves Line 4 on the heap and not in the String Constant Pool(SCP) when concatenating two String literals that are in the SCP ?
Thanks for any help in advance.

What I have tried:

System.out.println("str2 == str1"); // output is false.
Updated 17-Feb-23 21:12pm

1 solution

Simple: they are separate strings.
Strings str1 and str3 are "pointing at" constants because they are using literal strings whose value is absolutely known at compile time. These are allocated in the string constant pool.

And remember, string are immutable: once created, they cannot be changed.

str2 is originally set to a literal in the pool, but you then concatenate two strings together: this means a new string is created on the heap, and both the original strings are copied into it. It is not a literal anymore, it is a variable whose value is set at runtime.

Strings whose values are only known at run time are created on the heap, not the pool.
Share this answer
UT7 18-Feb-23 2:31am    
@OriginalGriff, thanks a lot, I'm grateful. Got it.
OriginalGriff 18-Feb-23 3:47am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900