Java中的静态和动态内存

use*_*114 2 java memory allocation

int x;
int y=10;
Run Code Online (Sandbox Code Playgroud)

在Java中分配什么类型的内存?我听说Java中的所有内容都分配了动态内存.这是真正的对象,但是相同的规则遵循基本数据类型也(如int,float等)?

Nar*_*hai 6

在一行中,它取决于声明变量的位置.

局部变量(在方法中声明的变量)存储在堆栈中,而实例和静态变量存储在堆上.*

注意: 变量的类型无关紧要.

class A{
  private int a = 10;  ---> Will be allocated in heap

  public void method(){
     int b = 4; ----> Will be allocated in stack
  }
}
Run Code Online (Sandbox Code Playgroud)