Java Break and Continue

In Java, the break and continue statements are used to alter the flow of control in loops. They are useful in controlling the execution of loops, and in this blog, we will discuss how to use them in Java programs. We will also provide examples to illustrate their usage.

Java Break Statement:

The break statement is used to exit a loop prematurely. It is used to stop the execution of the loop, even if the loop condition has not been met.

Example:

for (int i = 0; i < 10; i++) {
   if (i == 5) {
      break; // Exit the loop when i is equal to 5
   }
   System.out.println(i);
}

Output: 0 1 2 3 4

In the above example, we use a for loop to print numbers from 0 to 9. When i is equal to 5, the break statement is executed, and the loop is exited, so only numbers from 0 to 4 are printed.

Java Continue Statement:

The continue statement is used to skip an iteration of a loop. It is used to skip over certain parts of the loop and continue with the next iteration of the loop.

Example:

for (int i = 0; i < 10; i++) {
   if (i == 5) {
      continue; // Skip the iteration when i is equal to 5
   }
   System.out.println(i);
}

Output: 0 1 2 3 4 6 7 8 9

In the above example, we use a for loop to print numbers from 0 to 9. When i is equal to 5, the continue statement is executed, and the loop skips that iteration, so only numbers from 0 to 4 and 6 to 9 are printed.

Nested Loops with Break and Continue:

You can also use the break and continue statements in nested loops. When you use break or continue in a nested loop, it affects only the inner loop.

Example:

for (int i = 0; i < 5; i++) {
   for (int j = 0; j < 5; j++) {
      if (j == 3) {
         break; // Exit the inner loop when j is equal to 3
      }
      System.out.println("i = " + i + ", j = " + j);
   }
}

Output:

i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2
i = 3, j = 0
i = 3, j = 1
i = 3, j = 2
i = 4, j = 0
i = 4, j = 1
i = 4, j = 2

In the above example, we use a nested for loop to print the values of i and j. When j is equal to 3, the break statement is executed, and the inner loop is exited, so only values of j up to 2 are printed.

Conclusion:

The break and continue statements are powerful tools in controlling the flow of execution in Java loops. By using them effectively, you can make your code more efficient and concise. With the examples provided, you can start using break and continue