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

为什么在 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.

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...