java语句无限循环语句_Java中的无限循环

请看下面的whileJava 无限循环。它导致其下面的语句的编译时错误。

while(true) {

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

}

System.out.println("while terminated"); //Unreachable statement - compiler-error.

以下相同的无限while循环可正常工作,并且不会发出任何错误,其中我只是用布尔变量替换了条件。

boolean b=true;

while(b) {

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

}

System.out.println("while terminated"); //No error here.

同样在第二种情况下,循环之后的语句显然不可访问,因为布尔变量b为true,但编译器根本没有抱怨。为什么?

编辑:while显然,以下版本的卡在无限循环中,但是即使if循环中的条件始终存在false,因此循环下面的语句也不会对该语句下的语句发出任何编译器错误,因此循环永远不会返回,并且可以由编译器在以下位置确定编译时本身。

while(true) {

if(false) {

break;

}

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

}

System.out.println("while terminated"); //No error here.

while(true) {

if(false) { //if true then also

return; //Replacing return with break fixes the following error.

}

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

}

System.out.println("while terminated"); //Compiler-error - unreachable statement.

while(true) {

if(true) {

System.out.println("inside if");

return;

}

System.out.println("inside while"); //No error here.

}

System.out.println("while terminated"); //Compiler-error - unreachable statement.

编辑: 有同样的事情if和while。

if(false) {

System.out.println("inside if"); //No error here.

}

while(false) {

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

// Compiler's complain - unreachable statement.

}

while(true) {

if(true) {

System.out.println("inside if");

break;

}

System.out.println("inside while"); //No error here.

}

以下版本的while也陷入无限循环。

while(true) {

try {

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

return; //Replacing return with break makes no difference here.

} finally {

continue;

}

}

这是因为finally即使return语句在try块本身中遇到之前也总是执行该块。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值