Java 中的无限循环
2022-08-31 12:11:31
看看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
编辑:以下版本的 被困在一个无限循环中是显而易见的,但即使它下面的语句不会发出编译器错误,即使循环中的条件总是这样,因此,循环永远不会返回,并且可以由编译器在编译时确定。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