java交换机状态,在Java交换机中声明和初始化变量

I have a crazy question about Java switches.

int key = 2;

switch (key) {

case 1:

int value = 1;

break;

case 2:

value = 2;

System.out.println(value);

break;

default:

break;

}

Scenario 1 - When the key is two it successfully print the value as 2.

Scenario 2 - When I'm going to comment value = 2 in case 2: it squawks saying the The local variable value may not have been initialized.

Questions :

Scenario 1 : If the execution flow doesn't go to case 1: (when the key = 2), then how does it know the type of the value variable as int?

Scenario 2 : If the compiler knows the type of the value variable as int, then it must have accessed to the int value = 1; expression in case 1:.(Declaration and Initialization). Then why does it sqawrk When I'm going to comment value = 2 in case 2:, saying the The local variable value may not have been initialized.

解决方案

Switch statements are odd in terms of scoping, basically. From section 6.3 of the JLS:

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.

In your case, case 2 is in the same block as case 1 and appears after it, even though case 1 will never execute... so the local variable is in scope and available for writing despite you logically never "executing" the declaration. (A declaration isn't really "executable" although initialization is.)

If you comment out the value = 2; assignment, the compiler still knows which variable you're referring to, but you won't have gone through any execution path which assigns it a value, which is why you get an error as you would when you try to read any other not-definitely-assigned local variable.

I would strongly recommend you not to use local variables declared in other cases - it leads to highly confusing code, as you've seen. When I introduce local variables in switch statements (which I try to do rarely - cases should be very short, ideally) I usually prefer to introduce a new scope:

case 1: {

int value = 1;

...

break;

}

case 2: {

int value = 2;

...

break;

}

I believe this is clearer.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值