The break
keyword can be used to exit a loop in the middle of an iteration.
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.
By default, break
only breaks the immediately enclosing loop. To break out of an outer loop, use labeled statements.
Free Resources