Originally posted by wise owen:
Yes. But they are a litte different. s1's string object is created on heap and s2's string object is in string pool.
"s1 is a reference to an object that's already in the heap when this code executes."
"It is created while the class is loaded."
"The string pool is just like a Set of String references; it's not a special area of memory in which objects can be created"
String pool is a special memory area where String str = "abc" are stored. When the compiler sees a new String then it first searches through this String pool to find this String for reuse, otherwise the new String is created and stored in this pool.
String pool is a special memory area where String str = "abc" are stored.
String pool is a NOT a special memory area, only String references are stored and NOT the actual String Object.
Objects are stored in HEAP.
When the compiler sees a new String then it first searches through this String pool to find this String for reuse, otherwise the new String is created and stored in this pool.
The Java virtual machine maintains a per-type constant pool (�3.5.5), a runtime data structure that serves many of the purposes of the symbol table of a conventional programming language implementation.
The constant_pool table (�4.4) in the binary representation of a class or interface is used to construct the runtime constant pool upon class or interface creation (�5.3). All references in the runtime constant pool are initially symbolic. The symbolic references in the runtime constant pool are derived from structures in the binary representation of the class or interface as follows:
Originally posted by rama murthy:
Let me explain my understanding. Correct me if I am wrong.
String name = "abc";
So the JVM checks the string constant pool to see if any reference points to a string object with the same value(abc). If so NO new string object with the value "abc" is created on the heap. Instead the already existing reference is used internally which is assigned to the reference name. Or else new new string object is created on the heap and the reference "name" is placed in string constant pool.
Though it does seem to be true in general that many people do not realize that this process occurs at class loading time, so it's probably worth explicitly pointing out.