0

In C and C++, you can use int num[100];, so space allocation happends on stack memory. In Java, you can NOT use int[100] num;, but only like int[] number = new Integer[100] which make allocation on heap-memory.

So, is it true that Java does NOT support fixed size array on stack? If so, why?

Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70
RoFF
  • 529
  • 5
  • 27
  • 2
    I don't have a reference for it, but I seem to recall that if `number` is a local and it doesn't survive the method call, it's entirely possible the JVM will optimize it onto a stack frame rather than using heap *if it's worth doing*. Remember that the JVM does the vast majority of minute Java optimization like this, rather than the programmer or compiler doing them. – T.J. Crowder Oct 12 '16 at 10:33
  • http://programmers.stackexchange.com/questions/65281/stack-and-heap-memory-in-java – Herr Derb Oct 12 '16 at 10:34
  • 1
    http://stackoverflow.com/questions/10953806/java-array-using-stack-space – Jose Rui Santos Oct 12 '16 at 10:35
  • 2
    @T.J.Crowder More specifically, see [here](http://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance-enhancements-7.html#escapeAnalysis). – biziclop Oct 12 '16 at 10:35
  • @biziclop: Thank you, that's the term I was trying to remember! – T.J. Crowder Oct 12 '16 at 10:38
  • @biziclop: Am I reading that correctly that it *won't* use the stack for a non-escaping array? I can see that there would need to be several guards on doing so (not least size), but I'm a bit surprised to read *"It does **not** replace a heap allocation with a stack allocation for non-globally escaping objects."* – T.J. Crowder Oct 12 '16 at 10:41
  • 1
    @T.J.Crowder No, that only means objects that escape the method but not the thread (parse it as `(non-globally) escaping` rather than `non-(globally escaping)` :)). They can't be allocated on the stack for obvious reasons but any locking on them will still be optimised away. – biziclop Oct 12 '16 at 10:55
  • @biziclop: Thanks! I see what you mean. – T.J. Crowder Oct 12 '16 at 11:06

0 Answers0