Break Statement in java



A java break statement is used to stop the execution of a loop ( a for loop or a while loop). We will first take up the for loop, that we studied in previous post. We wish to break the execution of the for loop when value of i reaches 5.

  1. /*
  2.   ReferenceDesigner.com Java Tutorial
  3.   break a for loop
  4.   */
  5. class break1{
  6. public static void main (String args[]) {
  7. int i;
  8. double cm ;
  9. // Print a Table of Inch Centimeter
  10. System.out.println("Inch cm ");
  11. for (i=1; i<=10; i++)
  12. {
  13. cm = i*2.54 ;
  14. System.out.print( i );
  15. System.out.println(" "+cm );
  16. if (i == 5) break;
  17. }
  18. }
  19. }



C:\Program Files\Java\jdk1.7.0_17\bin>java break1
Inch cm
1 2.54
2 5.08
3 7.62
4 10.16
5 12.7




The break statement can also be used inside a while loop. Here is the same example presented to show the use of break statement in a while loop.

  1. /*
  2.   ReferenceDesigner.com Java Tutorial
  3.   break a while loop
  4.   */
  5. class break2{
  6. public static void main (String args[]) {
  7. int i;
  8. double cm ;
  9. // Print a Table of Inch Centimeter
  10. System.out.println("Inch cm ");
  11. i=1;
  12. while (i<=10)
  13. {
  14. cm = i*2.54 ;
  15. System.out.print( i );
  16. System.out.println(" "+cm );
  17. if (i == 5) break;
  18. i++;
  19. }
  20. }
  21. }


Continue Statement in a for loop


The continue statement in a for loop keyword causes flow of control to immediately jump to the update statement. The continue statement is helpful if we want to stop the normal flow of the control return to the loop without executing the statements WRITTEN AFTER the continue statement.

  1. /*
  2.   ReferenceDesigner.com Java Tutorial
  3.   understanding a continue statement
  4.   */
  5.  
  6. class continue1{
  7. public static void main (String args[]) {
  8. int i;
  9. int num3 = 0;
  10. for ( i=1; i<=20; i++)
  11. {
  12. if ( i%3 == 0) continue ;
  13. num3++;
  14. }
  15. System.out.println("Number of numbers not divisible by 3 between 1 and 20 is "+ num3);
  16. }
  17. }


Continue Statement in a while loop


The continue statement in a while or do while loop, causes the flow of control to immediately jumps to the Boolean expression. See the example below.

  1. /*
  2.   ReferenceDesigner.com Java Tutorial
  3.   understanding a continue statement in while loop
  4.   */
  5.  
  6. class continue1{
  7. public static void main (String args[]) {
  8. int i =0 ;
  9. int num3 = 0;
  10. while( i<=20 ) {
  11. i++;
  12. if ( i%3 == 0) continue ;
  13. num3++;
  14. }
  15. System.out.println("Number of numbers not divisible by 3 between 1 and 20 is "+ num3);
  16. }
  17. }