请看下面的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块本身中遇到之前也总是执行该块。