In Java, Jump statements are used to interrupt loop or switch-case instantly to transfer the program control from one point to elsewhere in the program.
Java supports three jump statements:
- continue.
- break
- return.
break:
This statement is used within the loop or switch cases to terminate that statement or the current loop is immediately stopped and resumes at the next statement followed by a terminated loop. we can also say that it helps to break out from the middle of the loop.
Syntax of break statement:
1 | break; |
continue:
It is used in loops to jump immediately to the next iteration of the loop. continue is used with while loop or do/while loop and with for loop. When continue is used inside for loop then the control immediately jumps to the increment or decrement part of the for loop. And when used inside while loop or do/while loop then the control immediately jumps to the condition part.
Syntax of continue statement:
1 | continue; |
label break statement
Java does not support goto as it leads to unstructured programming. so instead of ‘goto‘ we can use a label break statement which works like a goto statement.
Syntax of label:
1 2 3 4 5 6 | label: for() { //code break label; } |
Example of label break statement in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class LabelTest { public static void main(String[] args) { // label for outer loop outerlabel: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (j == 3) { break outerlabel; } System.out.println(" value of j = " + j); } } } } |
Output:
1 2 3 | value of j = 0 value of j = 1 value of j = 2 |