Search code examples
javastringstring-literals

when is string pool create in java at compile time or run time?


i know that when there is already an existing string in pool then a new string literal wont be made again.

i know the difference between string constant pool and heap also

i just want to know when is string pool created for a class for the below example.

String s="qwerty";
String s1="qwer"+"ty";// this will be resolved at compile time and no new string literal will be made

String s2=s.subString(1); will create qwerty at run time

s==s1; //true
s==s2;//false

i want to know for String s1 is resolved at compile time does that mean string pool is created at compile time ??


Solution

  • The constant pool contains String instances, which are runtime artifacts. Clearly, you cannot create objects before you start the program they are used in. The data specifying which string constants will be created is prepared at compile time and is a part of the class file format.

    However, note that the string constants are created at class loading time, and not on either class initialization time or their first use. This is a point which people often confuse.

    In your example, the difference is not between compile time and runtime, but between creating the string once in the constant pool, and creating it every time a line of code is executed.

    Also do note that the string pool has been a part of the regular heap for a long time in OpenJDK (even before it has become OpenJDK).