加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

为什么Java中的switch语句的范围不受限制?

发布时间:2020-12-15 02:54:46 所属栏目:Java 来源:网络整理
导读:为什么在 Java中,变量的范围局限于开关块而不是case块.例如, // Scope limited to a switch blockswitch (number) {case 1: String result = "..."; break;case 2: result = "..."; break; 在上面的示例中,结果只需要声明一次.如果您将其声明两次,则会收到Du
为什么在 Java中,变量的范围局限于开关块而不是case块.例如,
// Scope limited to a switch block
switch (number) {
case 1:
    String result = "...";
    break;
case 2:
    result = "...";
    break;

在上面的示例中,结果只需要声明一次.如果您将其声明两次,则会收到Duplicate local variable message.

我的问题是:如果number = 2,程序如何知道你已经声明了结果?
(它不会属于案例1,也不会声明变量……或者它会吗?)

编辑:

我可能会让所有人感到困惑.我理解如何限制变量的范围,但我的问题是:如果不属于这种情况,Java如何知道结果已被声明?

解决方法

编辑:Java使用词法作用域(也称为静态作用域),因此变量的范围在编译期间确定,与实际评估无关.

Java是块作用域,因此它的范围将尊重上面示例中的{}.

见JLS 6.3:

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears,starting with its own initializer and including any further declarators to the right in the local variable declaration statement.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读