java的while会错,在java中使用while循环时出现无法访问的语句错误

这篇博客探讨了Java编程中关于do-while和while循环的使用,特别是当条件为常量时出现的不可达语句错误。作者通过示例代码说明了在条件为常量false时,编译器会报错,因为内部语句无法执行。通过引入可变变量,问题得到解决。博客还提到了JLS14.21中关于不可达语句的规则,并指出if语句在某些情况下的特殊处理。
摘要由CSDN通过智能技术生成

This seems very easy question, I found this question in one book. If anyone help me to figure out why I'm getting error.

do {

System.out.print("inside do");

} while (false);

while (false) { // error

System.out.print("inside while");

}

System.out.print("outside");

I thought, and according to me, output should be inside dooutside. But, it is showing Compiler Error : Unreachable Statement. Then, I tried to figure out, why, it is showing Compilation error : Unreachable Statement* . So, I change the above code like this

boolean i = false;

do {

System.out.print("inside do");

} while (false);

while (i) { // ok

System.out.print("inside while");

}

System.out.print("outside");

Now, it is showing expected output i.e. inside dooutside . So, my question is - what makes difference in first and second case ?

Also, when I check

if(false){

//something here

}

Then, above code executes without any error.

解决方案

The main difference between the first two examples is that in the first case, the condition is a constant, whereas in the second it is not.

For example, if you change boolean i = false; into final boolean i = false;, you will get the same compile error because i is now a constant.

The rules for unreachable statements are defined in the JLS 14.21. In particular there is a special treatment for if to allow if(DEBUG) structures where DEBUG might be a constant.

As for the do / while, the statement inside will be executed once so there is no problem.

More details about the constants in this related post.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值