Caleb Caleb - 3 months ago 6x
Java Question

What are the pros and cons of creating objects on the heap only in Java?

In C++, we can also create objects on the stack, as we often do. Why did they decide to avoid this feature in Java?


Why did they decided to avoid this feature in Java?

It's simpler. Java doesn't say "Why not add it?" The Java designers usually waits until they really have to add a feature before they do it. (Tends to be a bit late IMHO, though perhaps this is a good thing in some ways) This means there is a minimum of features to learn and understand to be an expert in Java.

One thing you don't have to worry about what happens to your object once your method returns. e.g. in Java you can do

static String str; // In Java str is a reference.

static void setS() {
    String x = "Hello";
    str = x;  // x and str are references to an object on the heap so no problem.
    // if str was now a reference to an object on the stack, 
    // you could have a corruption issue.

However, with Escape Analysis the JVM can "unpack" an object which is notionally on the heap, onto the stack so that no heap allocation actually occurs. The downside of the current implementation is there is no way to force the JVM (or even hint) for it to do this.

On the plus side, it is one less thing you have to worry about in Java.