How do I exit a while loop in Java?

BalaB picture BalaB · Oct 31, 2011 · Viewed 469k times · Source

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

    }
}

Answer

dacwe picture dacwe · Oct 31, 2011

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) {
    ....
}