While else statement equivalent for Java?

The closest Java equivalent is to explicitly keep track of whether you exited the loop with a break… but you don’t actually have a break in your code, so using a while-else was pointless in the first place.

For Java folks (and Python folks) who don’t know what Python’s while-else does, an else clause on a while loop executes if the loop ends without a break. Another way to think about it is that it executes if the while condition is false, just like with an if statement.

A while-else that actually had a break:

while whatever():
    if whatever_else():
        break
    do_stuff()
else:
    finish_up()

could be translated to

boolean noBreak = true;
while (whatever()) {
    if (whateverElse()) {
        noBreak = false;
        break;
    }
    doStuff();
}
if (noBreak) {
    finishUp();
}

Leave a Comment