-1

I'm recently learning Core Java .So , please tell me about the right difference between this two memories Stack and Heap

  • Does this answer your question? [What and where are the stack and heap?](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) – kaya3 Feb 27 '20 at 20:30
  • 1
    [The Java VM specification](https://docs.oracle.com/javase/specs/jvms/se13/jvms13.pdf) is an authoritative answer on this. Start by reading it, and then feel free to ask when more specific issues come up with regard to particular sections of that document. – nanofarad Feb 27 '20 at 20:30

2 Answers2

1

stack and heap in general

Each Thread has a Stack.

Whenever a function is called, parameters and some pointers are pushed to the stack(the stack grows with that)

Whenever a local variable is created, it will also be allocated on the stack.

When the livecycle of a variable ends or a function returns, all those things will be poped from the stack that will therefore shrink.

The heap is a part in memory that is shared by all threads of a process.

Space can be allocated on the heap using malloc and has to be freed with free when it is not used anymore to prevent memory leaks.

As the heap can e.g. be used by other threads, it will not be freed automatically.

Stack and heap in java

In java, primitive local variables will be allocated on the stack. If you call a method and pass a primitive type to it, java will copy the content of the variable(call by value) and pass that copy to the method.

Whenever you create an object with new, it will be allocated on the heap and a reference to that object is stored like a primitive type.

If you pass an object (reference) to a method, the reference will be copied and the method will therefore modify the same object(call by reference).

The JVM will detect if an object is not used and free it automatically(garbage collection).

dan1st
  • 12,568
  • 8
  • 34
  • 67
0

Stack is used for temporary data (variables) inside methods. Heap is used for for data that can live longer, mainly everything that was crated by the "new" command.

Stefan
  • 1,789
  • 1
  • 11
  • 16
  • ooops. Thank you i fixed it. I had to work with C++ in the last days, so was a little confused in my head. – Stefan Feb 27 '20 at 20:39