问题描述
在Java中,我们不能在具有相同名称的另一个变量的同一范围内声明变量:
In Java, we cannot declare a variable in the same scope with the other variable which has the same name:
int someInteger = 3;
...
int someInteger = 13;
语法错误,无法编译。但是,如果我们把它放在一个循环中:
Syntax error, doesn't compile. However, if we put it inside a loop:
for (int i = 0; i < 10; i++) {
int someInteger = 3;
}
生成错误,效果很好。我们基本上声明了相同的变量。是什么原因?我不明白/理解这背后的逻辑是什么?
Generates no error, works very well. We are basicly declaring the same variable. What is the reason? What is the logic that I don't know/understand behind this?
推荐答案
想想这样,在每次循环之后,范围被破坏,变量消失了。在下一个循环中,创建一个新的范围,并且可以在该范围内再次声明该变量。
Think of this way, after each loop, the scope is "destroyed", and the variable is gone. In the next loop, a new scope is created, and the variable can be declared again in that scope.
您也可以这样做,原因类似
You can also do this, for the similar reason
{
int someInteger = 3;
}
{
int someInteger = 13;
}
顺便说一下,Java不允许局部变量阴影,这可能不方便
By the way, Java does not allow local variable shadowing, which might be inconvenient
int x = 3;
{
int x = 13; // error!
}
Consumer<Integer> consumer = (x)->print(x); // ERROR!
// lambda parameter is treated like local variable
Runnable r = ()->{ int x; ... } // ERROR
// lambda body is treated like local block
这篇关于在Java中重新声明循环内部的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!