views:

78

answers:

4

I'm a bit confused on the degree of "absolutes" here.

I know that memory allocation in C++ can be done by either heap or stack. And I know that Java's memory allocation can only be done via the heap.

Basically, is the following correct?

"Java doesn't have stack-based memory allocation [that programmers can directly access]" shouldn't be conflated with "Java still uses a function call stack to implement function calls, just like every other language".

http://en.wikipedia.org/wiki/Stack-based_memory_allocation http://en.wikipedia.org/wiki/Dynamic_memory_allocation

+4  A: 

I would say programmers can directly access it. You can't place arrays on the stack, but you can declare local variables, whether primitives or references. E.g.:

static void foo(double baz)
{
  int foo = ...;
  JFrame baz = ...;
}

foo, bar, and baz are all placed on the stack (while the JFrame object is placed on the heap).

You're right that it uses a stack frame quite similarly to most languages. In fact, the JVM itself is stack-oriented, meaning that operations work on the top of the stack (rather the contents of registers). For example, ladd pops the top two stack elements, adds them, then pushes the result. And we shouldn't forget our old friend StackOverflowError.

Matthew Flaschen
+4  A: 

Java saves local primitives on the call stack. So, not everything is on the heap.

The main difference between the memory model of Java and C++ is that in Java you cannot choose where to save your objects, Java decides for you.

jjnguy
Thank you, that's exactly where my understanding was heading. People who say "Java is heap-only" are over-simplifying.
Aaron F.
Not only local primitives but also references to objects. But the objects themselves are always allocated in the heap.
leonbloy
+1  A: 

Java does indeed have a function call stack, even though all memory allocations happen on the heap. Here's an example

static LinkedList<Object> foo(int x)        // x is pushed onto the stack
{
    int y = x;                // this is a basic data type, so it goes on the stack
    Object o = new Object();  // the Object is in the heap, but the pointer to it is on the stack
    List<Object> xs = new LinkedList<Object>();  // ditto
    xs.append(o);             // a copy of the pointer to my object is now in the LinkedList on the heap
    return xs;                // the pointer to the structure is returned through the stack
}
Eli Courtwright
Great example, thank you!
Aaron F.
A: 

Java has both a stack and a heap space.

The general rule is: every object you create with new goes in the heap space, everything else is on the call stack.

References to objects (and arrays, that are special kinds of object) can create some confusion. When you have Object o = new Object(), the object is allocated with new, so it's saved in the heap space, but the reference to that object (some kind of pointer) that you have in o, is in the call stack.

frm