Java Loops: break

break can be used to exit a loop in the middle of an iteration:

while (…) { if (condition) { break; } }

Example: Simple REPL

while (true) {
    String command = System.console().readLine();
    if (command.equals("quit")) {

break works precisely the same in for and dowhile loops.

Nested Loops

By default break only breaks the immediately enclosing loop. To break out of an outer loop, used labelled statements.

Example: Breaking out of an inner vs an outer loop.

while (…) { while (…) { break; } }
outer: while (…) { while (…) { break outer; } }


Be the first to comment!