What is a break in Java?

The break keyword can be used to exit a loop in the middle of an iteration.

widget

Example

Here’s a simple loop that iterates through an array and breaks if the string "quit" is found.

class BreakLoop {
public static void main( String args[] ) {
String[] arr = {"Edpresso", "shots", "quit", "continue"};
for (String s : arr){
if (s == "quit"){
break;
}
System.out.println(s);
}
}
}

The first two strings in the array are printed without any issues. However, when "quit" is encountered, the loop breaks and the remaining strings are not printed.

break works precisely the same way for while and do...while loops.

Nested Loops

By default, break only breaks the immediately enclosing loop. To break out of an outer loop, use​ labeled​ statements.

widget

Free Resources

Attributions:
  1. undefined by undefined