java - 循环中局部变量的空间分配

标签 java loops variables

(true or false) The space for a local variable that is declared in the body of the loop is allocated whenever the loop body is executed and deallocated when the body finishes.

这个问题的答案是错误的。但是为什么?

最佳答案

该语句是错误的,因为局部变量空间没有分配和释放。存在于栈中,在方法进入时保留。

要查看堆栈空间的使用情况,请编写一个小测试程序:

public static void test() {
    {
        int a = 1;
        long b = 2;
        int c = 3;
    }
    {
        int x = 4;
        int y = 5;
        long z = 6;
    }
}

现在使用以下命令反汇编它以查看字节码。

javap -c Test.class

这是输出。为了您的方便,我在右侧添加了 Java 代码。

  public static void test();
    Code:
       0: iconst_1                     int a = 1;
       1: istore_0
       2: ldc2_w     #22   long 2l     long b = 2;
       5: lstore_1
       6: iconst_3                     int c = 3;
       7: istore_3
       8: iconst_4                     int x = 4;
       9: istore_0
      10: iconst_5                     int y = 5;
      11: istore_1
      12: ldc2_w     #24   long 6l     long z = 6;
      15: lstore_2
      16: return                       return;

发生的事情是该方法保留了 4 个“槽”。 int 变量占用 1 个槽位,long 变量占用 2 个槽位。

所以代码实际上是这样说的:

slot[0] = 1
slot[1-2] = 2L
slot[3] = 3

slot[0] = 4
slot[1] = 5
slot[2-3] = 6L

这显示了在不同代码块中声明的局部变量如何重用槽。

关于java - 循环中局部变量的空间分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51394012/

相关文章:

php - MySQL make 查询包括包含另一个变量的 PHP 变量

c++ - 在 C++ 中是否有等效的 Java equals 方法?

java - 无法使用 .transform 更改 Path2D.Double

java - Hadoop Mapreduce实践

Java 和 Google 日历

java - 将多个整数值混淆为固定长度值并将其读回

java - 在 Java 中获取列表中不存在于另一个列表中的下一个项目

r - 循环遍历数据框的行以进行模拟

Python,在字母列表中找到多个索引

javascript - 在多个 Photoshop 文件中查找和替换文本?