Java 中的内存分配 - 声明与定义

Geo*_*ton 1 c java

在 C 中,当我们声明某些内容时,我们告诉编译器该变量包含什么类型。只有在定义期间我们才为其分配内存空间。然而,在Java中,当我们声明一个变量时,内存空间就被分配了

int x; // allocates space for an int
Run Code Online (Sandbox Code Playgroud)

我的前提正确吗?这是否意味着我们应该尽可能稀疏声明?

das*_*ght 5

当谈到Java中的变量时,声明和定义之间没有分离。但这并不影响内存分配过程。

Java 中内存分配的情况与 C 中从动态区域(即“堆”)分配内存的情况很接近。定义指针类型的变量会为变量本身分配空间,但不会分配内存指针指向的内容。下面是一个用 C 语言进行简单字符串操作的示例:

// Allocate memory for the pointer
char *str;
// Allocate memory for the string itself
str = malloc(16);
// Copy the data into the string
strcpy(str, "Hello, world!");
Run Code Online (Sandbox Code Playgroud)

当您处理对象时,Java 中也会发生类似的情况。定义变量会为对象引用分配空间,但不会为对象分配空间。您需要调用new才能将该引用“附加”到新对象:

// Allocate memory for the reference
String str;
// Allocate memory for the string, and sets data
str = new String("Hello, world!");
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于对象。基元类型的处理方式有所不同,其方式与 C 中处理基元的方式更加相似。