In Java, the break and continue statements are control flow statements and allow us to interrupt (break) the current flow or skip (continue) an iteration within a loop.
Java break Statement
The Java break statement is used to break the loop or switch statement.
Example of a break statement inside a loop:
class Test { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println("Value:" + i); if (i == 3) { break; // terminate the loop if condition is met } } System.out.println("Code after the loop..."); } }
Java break statement and nested loop
The break statement is often used inside nested loops as well.
To work correctly with break and nested loops, we must first label the loops to specify from which loop we want to break.
Take a look at this example:
class Test { public static void main(String[] args) { first:// label for (int i = 1; i < 3; i++) { second:// label for (int j = 1; j < 4; j++) { System.out.println("i: " + i + ", j:" + j); if (j == 3) { break first; } } } System.out.println("Code after the loop..."); } }
Java break statement inside the switch statement
The break statement is widely used in switch statements. This ensures that code execution stops after the matching case’s code block has been executed.
Here is one example:
class Test { public static void main(String[] args) { int number = 10; int newNumber; switch (number) { case 5: // if the number is equal to 5, execute this block of code newNumber = number; break; case 10: // if the number is equal 10, execute this block of code newNumber = number; break; default: // None of the above is true? Then run the default block newNumber = 0; } // outside the switch statement System.out.println(newNumber); } }
class Test { public static void main(String[] args) { String color = "yellow"; switch (color) { case "white": System.out.println("The color is white."); case "yellow": System.out.println("The color is yellow."); case "blue": System.out.println("The color is blue."); case "green": System.out.println("The color is green."); default: System.out.println("Unrecognized color!"); } } }
Java continue statement
The continue statement skips the current iteration of a loop.
Example of the continue statement inside a loop:
class Test { public static void main(String[] args) { for (int i = 1; i < 5; i++) { if (i == 3) { continue; } System.out.println("i: " + i); } System.out.println("Code after the loop..."); } }
Java continue statement and nested loop
The continue statement can be used inside nested loops as well. As in the case of break statements, we need to label loops to control the flow more properly.
class Test { public static void main(String[] args) { first: // label for (int i = 1; i < 3; i++) { second: // label for (int j = 1; j < 4; j++) { if (j == 3) { continue second; } System.out.println("i: " + i + ", j:" + j); } } System.out.println("Code after the loop..."); } }
Happy Learning!