12 Jul break continue statements in Java
break statement in Java
The break statement in C, C++ and Java terminates the statement sequence. We saw it in the Switch case as well. In Java, we can use break as,
- break in switch
- break as goto
- break outside label
Let us first see the syntax,
Syntax
1 2 3 |
break; |
Example
Let us see an example to learn more about 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 StudyopediaDemo { public static void main(String args[]) { System.out.println("'Break statement' in Java - Studyopedia"); int i = 5; while( i < 10 ) { System.out.println(i); i++; if( i > 7) { break; } } } } |
Output
The following is the output,
break in switch statement in Java
Let us see an example to learn about the usage of break in switch statement in Java,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class StudyopediaDemo { public static void main(String args[]) { System.out.println("'Switch' in Java - Studyopedia"); int marks = 75 ; switch(marks) { case 90: System.out.println("Grade A"); break; case 75: System.out.println("Grade B"); break; case 60: System.out.println("Grade C"); break; } } } |
The following is the output,
break as goto in Java
Let us see an example to learn about the usage of break as goto in Java,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class StudyopediaDemo { public static void main(String args[]) { boolean a = true; System.out.println("'Break as Goto' in Java - Studyopedia"); first: { second: { third: { System.out.println("Inside Third Section"); if(a) { break second; } } System.out.println("Inside Second Section"); } System.out.println("Inside First Section"); } } } |
The following is the output,
continue statement in Java
The continue statement transfers control to the conditional expression and jumps to the next iteration of the loop.
Syntax
1 2 3 |
continue; |
Example
The following is an example showing the usage of continue statement,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class StudyopediaDemo { public static void main(String args[]) { System.out.println("'continue statement' in Java - Studyopedia"); int val1 = 100; do { if( val1 == 110) { val1 = val1 + 1; continue; } System.out.println(val1); val1++; } while( val1 < 115 ); } } |
The following is the output,
continue as goto in Java
Let us learn about how to work with continue statement as goto in Java,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class StudyopediaDemo { public static void main(String args[]) { System.out.println("'continue as goto' in Java - Studyopedia"); first: for(int i=1; i<6;i++) { second: for(int j=1; i<=10;j++) { if(j==2) { continue first; } System.out.println("i="+i+", j="+j); } } } } |
The following is the output,
In this lesson, we learned how to work with break and continue in Java.
No Comments