0

What was the reasoning behind this decision? Why dynamically make objects on the heap and not on the stack? By doing it on the are we saving space?

carlkr
  • 11
  • 2
    My question back is do you know he difference between a heap and a stack? – Rabbit Guy Jul 06 '20 at 20:02
  • 3
    Possible duplicate of: [*Heap vs Stack vs Perm Space*](https://stackoverflow.com/q/6801676/642706) – Basil Bourque Jul 06 '20 at 20:06
  • 3
    When you allocate memory for an object or any sort of data structure it's usually on the heap — free memory in the system — in most programming languages. The stack is commonly used to push memory (variables) for function/method calls. In Java the _handle_ (address, pointer) of the object being passed is put on the stack. In hardware there are sometimes limitations on the stack pointer. The stack is not meant for long-term (program duration) storage; it's used, in a sense, to save and restore context while making subroutine calls. This concept goes way beyond Java. – Stephen P Jul 06 '20 at 20:07
  • Do you understand what the heap and what the stack is, how they differ, etc!? – luk2302 Jul 06 '20 at 20:42
  • Does this answer your question? [Heap vs Stack vs Perm Space](https://stackoverflow.com/questions/6801676/heap-vs-stack-vs-perm-space) – bsaverino Jul 06 '20 at 20:56
  • AFAIK, nothing in Java disallows stack allocation, it is just more complicated than heap allocation because of the required escape analysis. Microsoft recently contributed a prototype patch for stack allocation of objects in a limited set of circumstances. – Mark Rotteveel Jul 07 '20 at 18:41

1 Answers1

0

If you allocate an object on the stack, its life time is limited to the current method call. When the method returns, the object is automatically destroyed, together with everything else stored in the stack frame. This means it's impossible to write a function that returns an object, or a function that adds a new object to a list.

You could make it work by copying or moving the object like c++ does. But then you have to deal with the complexity of C++. Java was supposed to be simpler than that.

Joni
  • 108,737
  • 14
  • 143
  • 193