java switch的范围,switch case语句中的java范围声明如何?

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;

}

}

}

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.)

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

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.

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;

...

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值