Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 354
unknown Avatar asked Sep 18 '13 07:09

unknown


People also ask

Where is string pool stored Java?

From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM.

Is string pool in heap or stack?

String constant pool belongs to the permanent generation area of Heap memory.

What is string pool and what is purpose of it?

String Pool is a storage area in Java heap. String allocation, like all object allocation, proves to be a costly affair in both the cases of time and memory. The JVM performs some steps while initializing string literals to increase performance and decrease memory overhead.


2 Answers

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).

like image 105
Marko Topolnik Avatar answered Nov 14 '22 23:11

Marko Topolnik


As per your code :

String s2=s.subString(1); //this will create werty not qwerty so s==s2 will be anyways false

If you use

String s2=s.subString(0); //this will create qwerty 

and then s==s2 will return true.

Also there is a method intern() which looks into constant pool for below case as well:

String s2 = new String("Qwerty").intern();

In this case, s==s2 will return true but if String s2==new String("Qwerty"); then s==s2 will return false.

Also string literal were part of permgen space before JDK 7 after which they became a part of heap space.

like image 43
Vineet Kasat Avatar answered Nov 14 '22 23:11

Vineet Kasat