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){
Finding a while...do
construct with while(true)
in my code would make my eyes bleed. Use a standard while
loop instead:
while (obj != null){
...
}
And take a look at the link Yacoby provided in his answer, and this one too. Seriously.
The while and do-while Statements
You can use "break" to break the loop, which will not allow the loop to process more conditions
Take a look at the Java™ Tutorials by Oracle.
But basically, as dacwe said, use break
.
If you can it is often clearer to avoid using break and put the check as a condition of the while loop, or using something like a do while loop. This isn't always possible though.
You can use "break", already mentioned in the answers above. If you need to return some values. You can use "return" like the code below:
while(true){
if(some condition){
do something;
return;}
else{
do something;
return;}
}
in this case, this while is in under a method which is returning some kind of values.