堆和栈都是内存的一部分。一个程序在虚拟机运行,会在不同的位置分配内存。
首先:栈内存用于储存局部变量 和进行方法调用。而堆内存用来存储Java中的对象。无论是成员变量,局部变量,还是类变量,它们指向的对象都存储在堆内存中。
此外,栈内存是线程的私有内存,而堆内存中的对象可以被所有线程访问 是共享的。
此外 在抛出异常的时候,如果栈内存空间不足,抛出的是stackoverflowerror,而如果是对内存空间不足,则会抛出outofmemoryerror.

what is stack?
stack is a special area of computer’s memory which stores temporary variables created by function. in stack, variables are declared, stored and initialized during runtime?

what is heap?
the heap is a memory used by programming lauguages to store global variables, by default, all global varibale are stored in heap memory space, it supports dynamic memory allocation.
the heap is not managed automatically for not and is not as tightly managed by the CPU.

what the key difference between stack and heap?

  1. stack is a linear data structure and heap is a hierarchical data structure.
  2. stack memory will never become fragment but heap will be because blocks of memory are first allocated and then freed.
  3. stack accesses local variables only and heap allows you to access variables globally.
  4. stack variables can’t be resized but heap can
  5. stack allocation and deallocation are done by complier but heap done this through programmer.