问题
(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.
The answer to this question is false. But why?
回答1:
The statement is false because local variable space is not allocated and deallocated. It exists on the stack and is reserved when the method is entered.
To see how stack space is used, write a small test program with:
public static void test() {
{
int a = 1;
long b = 2;
int c = 3;
}
{
int x = 4;
int y = 5;
long z = 6;
}
}
Now disassemble it with the following command to see the bytecode.
javap -c Test.class
Here is the output. I've added the Java code on the right for your convenience.
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;
What happens is that the method has reserved 4 "slots". An int
variable takes 1 slot, and a long
variable takes 2 slots.
So the code really says:
slot[0] = 1
slot[1-2] = 2L
slot[3] = 3
slot[0] = 4
slot[1] = 5
slot[2-3] = 6L
This shows how the slots are reused by local variables declared in difference code blocks.
回答2:
Yes (as answer requested in binary form)
Local variables are stored in Stack Memory. It is temporary memory allocated to store local variables,when method is invoked. In case of Loop , scope of local variable is restricted to loop start and end. ( eg in case of while(...) { --- scope of local variable -- } ) scope is restricted by {} braces.
When variable is created inside loop , temporary memory is allocated in stack memory and it will be available for reuse , when the scope of variable ends.
Note : Local variables are not garbage collected.
来源:https://stackoverflow.com/questions/51394012/allocation-of-space-for-local-variables-in-loops