switch case语句中的java范围声明如何? [英] How does java scope declarations in switch case statements?

查看:917
本文介绍了switch case语句中的java范围声明如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Java代码在Java 1.7中无错误地执行

The following java code executes without error in Java 1.7

public static void main(String[] args) {
    int x = 5;

    switch(x) {
        case 4: 
            int y = 3423432;
            break;  
        case 5: {
            y = 33;
        }
    }
}

java如何找出y是一个int,因为声明永远不会运行。在case语句中没有使用大括号时,case语句中的变量声明是否限定为switch语句级别?

How does java figure out that y is an int since the declaration never gets run. Does the declaration of variables within a case statement get scoped to the switch statement level when braces are not used in a case statement?

推荐答案

声明不是运行 - 它们不是需要执行的东西,它们只是告诉编译器变量的类型。 (初始化程序会运行,但是没关系 - 在为它赋值之前你不会尝试读取变量。)

Declarations aren't "run" - they're not something that needs to execute, they just tell the compiler the type of a variable. (An initializer would run, but that's fine - you're not trying to read from the variable before assigning a value to it.)

在switch语句中确定范围绝对是奇数,但基本上在第一个 case 中声明的变量仍在第二个 case 中的范围内。

Scoping within switch statements is definitely odd, but basically the variable declared in the first case is still in scope in the second case.

来自第6.3节JLS


块中的局部变量声明的范围(第14.4节)是块的其余部分声明出现,从它自己的初始化程序开始,并在本地变量声明语句中包含右边的任何其他声明符。

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.

除非你创建额外的块,整个switch语句是一个块。如果你想为每个案例设置一个新的范围,你可以使用大括号:

Unless you create extra blocks, the whole switch statement is one block. If you want a new scope for each case, you can use braces:

case 1: {
    int y = 7;
    ...
}
case 2: {
    int y = 5;
    ...
}

这篇关于switch case语句中的java范围声明如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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