How do I exit a while loop in Java?

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

Leave a Comment