In Java, every objects get garbage collected when its in dead state, so why String object and literals are placed in different memory space..
Asked
Active
Viewed 244 times
0
-
4Possible duplicate of [When exactly the object is created in string constant pool when we use new operator.?](http://stackoverflow.com/questions/39388162/when-exactly-the-object-is-created-in-string-constant-pool-when-we-use-new-opera) have look at the question and all the answers – Pavneet_Singh Oct 10 '16 at 11:09
1 Answers
1
so why String object and literals are placed in different memory space..
As of Java 6, all String literals were all placed in the heap.
Primitive literals are not on the heap, though the values can be stored in objects on the heap.
Class literals are on the heap, though much of the data associated with a class is still stored in Metaspace (previously Perm Gen)
They used to be separate (in Perm Gen) to reduce the load on the heap collection but as you say, this made cleaning up String literals more complicated.

Peter Lawrey
- 525,659
- 79
- 751
- 1,130
-
thanks for the reply, but "Perm Gen" also in Heap memory so what it makes difference from String constant pool in Perm Gen(stores literals) and heap memory(stores String object). – prabhakaran Oct 10 '16 at 11:25
-
1The phrase “String object and literals” seems to be broader than literals, thus, it should be emphasized that non-literal strings were *never* treated specially. – Holger Oct 10 '16 at 12:43
-
@Holger Thank you. I have updated my answer. What would you say about *class literals*? – Peter Lawrey Oct 10 '16 at 12:51
-
1Well, class-literals evaluate to the same objects you get when accessing `Class` objects by other means (`getClass()` or `Class.forName`), so the fact, that they are accessed by literal expressions has no impact on their memory location. But I’m not sure whether the OP also meant string objects in general, rather than string literals only, so it’s worth noting that string objects not created from a literal were ordinary objects in all JVM versions and only string literals had special treatment in older JVMs, though, that “Perm Gen” wasn’t sooo special. The biggest problem was its fixed size. – Holger Oct 10 '16 at 12:59