What is the best way to exit/terminate a while loop in Java?
For example, my code is currently as follows:
while(true){
if(obj == null){
// I need to exit here
}
}
The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop. To exit a function, use return .
The issue with your while loop not closing is because you have an embedded for loop in your code. What happens, is your code will enter the while loop, because while(test) will result in true . Then, your code will enter the for loop. Inside of your for loop, you have the code looping from 1-10.
Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.
Use break
:
while (true) {
....
if (obj == null) {
break;
}
....
}
However, if your code looks exactly like you have specified you can use a normal while
loop and change the condition to obj != null
:
while (obj != null) {
....
}
while(obj != null){
// statements.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With