Break, Continue


Java Break and Continue

Before going into the basics of break and continue statements, we need to address their use in any given programming language. We’re already familiar with loops such as “for” loops, “while” loops, “do-while” loops. Essentially a loop is simply a code piece that helps to iterate through any given data structure. The data structure can be anything varying from Arrays to Trees.

First, let’s talk about the break statement. It primarily has two use-cases:

  • When the break statement is met in the loop, the loop ends immediately, and program control resumes at the next instruction after the loop.
  • It can be used to conclude any case in the switch statement. It terminates the ongoing flow of the program. If there is an inner loop existing, the break statement will only terminate the inner loop.

In simple words, the break statement lets you break a “while” or a “for” loop somewhere in the middle. The loop will undeniably end after the condition, but break essentially helps to terminate it whenever we require and to it clearly saves auxiliary iterations.

An important note: Break statement only works in the case of loops. It doesn’t work in “if” statements.

Coming to the “Continue” statement, in contrast to the “Break” statement it is utilized in loop control structure whenever the code needs to:

  • Jump to the next iteration instantly
  • Ignore the statements below the “Continue” for that particular iteration

The “Continue” statement incorporated in Java is merely used to continue the loop. Continue with the current flow of the program and skip the remaining code under specific conditions. In the case of the inner loop, only the inner loop continues.

If during any iteration, “Continue” is encountered the control flow will directly shift at the beginning of the loop disregarding the instructions below it

break statement

This statement has following uses: It is used to terminate the execution of a loop. It is used to come out of switch statement.

Example No.1:

Com.knowledge2life public class Main { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 2) { break; } System.out.println("Knowledge2life"); } } }

OUTPUT:

Knowledge2life
Knowledge2life

continue statement

This statement is used to force an early iteration in loop skipping subsequent statements

Example No.2:

Com.knowledge2life public class Main { public static void main(String[] args) { for (int i = 0; i <= 5; i++) { if (i == 3) { continue; }System.out.println("Knowledge2life"); } } }

OUTPUT:

Knowledge2life
Knowledge2life
Knowledge2life
Knowledge2life
Knowledge2life