看看下面这个 Java 中的无限 while循环,它会导致下面的语句出现编译时错误。
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;
}
}
这是因为即使 return语句在 try块本身之前遇到,也始终执行 finally块。