Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exit a while loop in Java?

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

    }
}
like image 700
BalaB Avatar asked Oct 31 '11 09:10

BalaB


People also ask

How do you exit a while loop?

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 .

Why does my while loop not stop Java?

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.

How do you escape a loop?

Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.


2 Answers

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) {
    ....
}
like image 128
dacwe Avatar answered Oct 10 '22 06:10

dacwe


while(obj != null){
  // statements.
}
like image 7
Riz Avatar answered Oct 10 '22 05:10

Riz