Understand Java break and continue Statements
Let’s get it right and understand on usage of break and continue Statements in Java Programming Language.
break Statement
This statement causes iteration to stop/exit immediately, any line remained after this statement will be ignored by the JVM.
It is used in the following loop
- for
- while
- do…while
- switch
continue Statement
This statement skips the current iteration of the loop, any line after this statement will not be executed by the JVM until the condition is met.
It is used in the following loop
- for
- while
- do…while
Example code below demonstrating how break and continue statement work
public class BreakContinueStm { public static void main(String[] args) { int aBreak = 0; int bContinue = 0; for (int i=1; i<=10; i++){ if (i == 6){ // that's enough, exit this for loop here break; } aBreak = i; System.out.println("aBreak: " + aBreak); } for (int i=1; i<=10; i++){ if (i <= 5){ // not satisfied yet, keep going continue; } bContinue = i; System.out.println("bContinue: " + bContinue); } } }
Result of this program, aBreak stops when i = 6 and bContinue starts when i = 6 until end of the loop
aBreak: 1 aBreak: 2 aBreak: 3 aBreak: 4 aBreak: 5 bContinue: 6 bContinue: 7 bContinue: 8 bContinue: 9 bContinue: 10
AD ยป Recommended Java book Java How to Program, 7th Edition ( by Harvey M. Deitel, Paul J. Deitel )
Categories: Programming
Amazon

