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ब्लॉक के भीतर ही सामने आए ।