posted 7 years ago
I am virtually 100% certain that Java does not allocate objects on the stack. At the Java source level, I can't think of any possible way to indicate it. The syntax that would do so in C is interpreted in Java as defining a reference, not an actual object. You can ONLY construct Java objects via operator "new" or its underlying method newInstance().
Plus providing such an option even as an undercover VM optimization technique would be a non-trivial affair. The JVM would have to understand the difference between references to on-the-stack object instances and general object references, and since one of the major points of Java over C and C++ is to eliminate the latter's infamous ability to for developers to create pointer bugs, I just can't see it. Plus, an optimizing compiler can only track the handles on an object so far without risking objects leaking out into areas where you'd have an object reference to a stack object that has been popped off.
I prefer not to consider where my objects are allocated. At the Java source level, it's immaterial whether they come from a traditional "heap", are maintained in pools, or beam down from Antares. I've seen quite enough grief just from PermGen space.
Experience keeps a dear School, but Fools will learn in no other.
---
Benjamin Franklin - Postal official and Weather observer