Break and Continue in Java

If you remember switch case, we've used break keyword there. Do you know why? To stop the execution of switch case of block after matching one case.

The keywords break and continue are part of control structures. It is mostly used with loops. Sometimes, both seems to work same but there is slight difference between them.


Break

The break keyword is used to stop a loop execution. Whenever break keyword finds it jumps out of loop and proceed to codes afterwards. We can give some conditions for break to stop the loop.


Example:

Lets say I want to print 1 to 10. But I want to stop the program if any number divisible by 5 is found. See the example below:
Code:

public class LearnBreak { public static void main(String[] args) { for(int i = 1; i <= 10; i++) { if(i%5 == 0) { break; } System.out.println(i); } } }
In every step, it checks if i is divisible by 5 or not. It will print upto 4. But once when i = 5, the if condition satiesfies and it breaks the program.
Output:
1
2
3
4

Continue

The continue keyword is used to skip the current iteration only in loops. Whenever continue keyword finds, it skips the rest of program inside a loop and starts next iteration. We can give some conditions for continue to skip the loop.


Example:

Lets say I want to print 1 to 10. But I want to skip the numbers divisible by 5. See the example below:
Code:

public class LearnContinue { public static void main(String[] args) { for(int i = 1; i <= 10; i++) { if(i%5 == 0) { continue; } System.out.println(i); } } }
In every step, it checks if i is divisible by 5 or not. When if condition satiesfies and it skips the program and goes for next iteration. Output:
1
2
3
4
6
7
8
9

Do While Loop in Java Previous Next Arrays in Java