Ale*_*lex 4 java variables loops
(true或false)在循环体执行时分配在循环体中声明的局部变量的空间,并在主体完成时释放.
这个问题的答案是错误的.但为什么?
该语句为false,因为未分配和释放本地变量空间.它存在于堆栈中,并在输入方法时保留.
要查看堆栈空间的使用方式,请编写一个小型测试程序:
public static void test() {
{
int a = 1;
long b = 2;
int c = 3;
}
{
int x = 4;
int y = 5;
long z = 6;
}
}
Run Code Online (Sandbox Code Playgroud)
现在使用以下命令对其进行反汇编以查看字节码.
javap -c Test.class
Run Code Online (Sandbox Code Playgroud)
这是输出.为方便起见,我在右侧添加了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;
Run Code Online (Sandbox Code Playgroud)
会发生什么是该方法保留了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
Run Code Online (Sandbox Code Playgroud)
这显示了如何在差异代码块中声明的局部变量重用槽.