-2

I know Stack memory stores primitive types and the addresses of objects and the object values are stored in heap memory.

But if primitive is part of object then where it will be stored in Heap or Stack ?

How can I verify it ?

Thanks.

user2510115
  • 674
  • 2
  • 8
  • 17
  • Dup: http://stackoverflow.com/questions/3698078/where-does-the-jvm-store-primitive-variables – Amir Afghani Sep 05 '13 at 21:45
  • but no one has accept the answer and I have additional question But if primitive is part of object then where it will be stored in Heap or Stack ? – user2510115 Sep 05 '13 at 21:49
  • @user2510115 Read my answer. It's there. And it's there in the dupe as well. The answer provided by Jon Skeet should be sufficient, accepted or not. – nanofarad Sep 05 '13 at 21:50

2 Answers2

0

The stack is used for only local primitives and references to objects that is in the scope of a method (or block within) and not a class. The heap is used for all object data including the primitive fields thereof.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • ok. Do u know how can i verify it using any code or something else ? – user2510115 Sep 05 '13 at 21:50
  • @user2510115 You don't. It's defined this way. It's not something Java code really messes with. – nanofarad Sep 05 '13 at 21:50
  • @user2510115 Why? Why do you think it needs verification? Where else could it possibly be? What difference does it make to you either way? – user207421 Sep 05 '13 at 21:56
  • Part of the whole point of Java is that you don't care whether memory is in the stack or the heap; it's _deliberate_ that you can't tell where a certain piece of data is stored. – Louis Wasserman Sep 05 '13 at 21:57
  • @EJB I need verification if there is a way otherwise it's fine. I trust you guys blindly :) – user2510115 Sep 05 '13 at 22:00
  • You 'need verification' *why?* It's almost certainly *stated* in the JLS somewhere, but in any case it's implicit in the language. – user207421 Sep 05 '13 at 22:12
0

I think that it's not possible to know whether any data in the JVM is allocated on the stack or the heap. For example, for Hotspot, see: http://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance-enhancements-7.html#escapeAnalysis

In Hotspot, you could turn off Escape Analysis, in which case I think it will always be allocated on the heap, but I wouldn't like to guarantee it (it depends on the internal workings of the JVM).

As for determining if something is allocated on the heap, you could use jmap to take a heap dump, and analyze it using jhat (or another similar tool). Then you should be able to inspect the contents of the heap.

Neil
  • 1,754
  • 2
  • 17
  • 30