在 Java 中重新声明循环内的变量 [英] Re-declaring variables inside loops in Java

查看:29
本文介绍了在 Java 中重新声明循环内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 中重新声明循环内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆