Home > Blockchain >  Are these string in concat command created in string pool?
Are these string in concat command created in string pool?

Time:06-17

Assume I write something like this in Java:

String a = args[0]; // user input from keyboard
String b = a   "foo1";
String c = "foo2"   "foo3";

Will "foo1", "foo2", "foo3" be created in String pool?

CodePudding user response:

The strings "foo1" and "foo2foo3" are values of compile time constant expressions and both will be interned.

None of the other strings will be.

  • a is not interned.

  • a "foo1" is not interned.

  • neither "foo2" or "foo3" is interned. In fact runtime String objects are not even created for these 2 literals. The "foo2" "foo3" expression is evaluated at compile time.


The fact that strings are immutable doesn't predict whether a string value is interned or not. (All strings are immutable, but only some are interned.)

Finally, all of this is irrelevant to practical programming. If you consistently use equals(...) to test strings, interning (or not) has no effect on program behavior.

In a modern JVM, the GC's string de-duplication feature is a better way to manage space consumed by possible duplicate strings than interning. And the amount of memory occupied by literals / constant expressions should be insignificant anyway.

  • Related