In Java If we instantiate an object then it will be located at Heap memory But what happens if we instantiate a singleton class object then it object locates where ???(Heap or class area as it static reference)
-
Doesn't matter where the reference is, the object is always on the heap. – Marko Topolnik Sep 19 '16 at 16:36
-
Side note: AFAIK, there is no "class area." The JVM has a "[*method* area](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.5.4)," but as the name suggests, it's for methods, not classes. – T.J. Crowder Sep 19 '16 at 16:39
-
1Possible duplicate of [where is a static method and a static variable stored in java. In heap or in stack memory](http://stackoverflow.com/questions/8387989/where-is-a-static-method-and-a-static-variable-stored-in-java-in-heap-or-in-sta) – Sensei James Sep 19 '16 at 16:45
-
then garbage collector will able to destroy singleton class object when object reference will be null. right? @Marko Topolnik – Newaz Sharif Amit Sep 19 '16 at 16:51
-
Yes, just like any other object. – Marko Topolnik Sep 19 '16 at 16:52
2 Answers
Instances that aren't purely local to methods are created and stored in the heap, even if they're only referenced from static
fields.
(If the instance is local to a method and doesn't survive method termination, the JVM may, as an optimization, allocate it on the stack. Which isn't strictly applicable to your question, just explaining the caveat in the initial sentence above.)

- 1,031,962
- 187
- 1,923
- 1,875
All created instances will be stored in the heap. so even though it is a singleton class, the only instance will be created in the heap. but that reference will be kept by a static filed. because the static filed is a part of class definition (not the instance), that reference will be stored along with the class meta data which is stored in the PermGen which is actually a part of the heap

- 3,963
- 1
- 16
- 19