Java Break Statement Example
This is an example of how to use the java break statement.
1. Java Break overview
The break
statement can be used to terminate a for
, while
, or do-while
loop. Also it is used in switch
statement to exit the current case.
2. Break in loop example
In the example the break statement is used when checking an array’s elements, as described:
- Create a for statement with an int index from 0 up to an int array length, that checks the elements of the array.
- When an element divided to 2 returns 0, then the break statement is used that terminates the for loop.
Let’s take a look at the code snippet that follows:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 | package com.javacodegeeks.snippets.basics; public class BreakStatement { public static void main(String[] args) { int array[] = new int [] { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 }; System.out.println( "Printing first even number" ); for ( int i = 0 ; i < array.length; i++) { if (array[i] % 2 == 0 ) break ; else System.out.print(array[i] + " " ); } } } |
Output
Printing first even number
1
3. Break in switch example
In case of switch statement is is used as below:
package com.javacodegeeks.snippets.basics;
public class BreakStatementInSwitch {
public static void main(String[] args) {
String day = "Thursday";
switch(day){
case "Monday":
System.out.println("Monday");
break;
case "Tuesday":
System.out.println("Tuesday");
break;
case "Wednesday":
System.out.println("Wednesday");
break;
case "Thursday":
System.out.println("Thursday");
break;
case "Friday":
System.out.println("Friday");
break;
case "Saturday":
System.out.println("Saturday");
break;
case "Sunday":
System.out.println("Sunday");
break;
}
Output: Thursday
In the above example, for each case, the condition day.equals(String_after_case_keyword)
is checked, if it is true, then the name of the day is printed and the break keyword exits the switch statement.
4. Difference between Break and Continue
The differences between break and continue are the following:
- The break can be used in switch statements, the continue cannot.
- The break exits the loop, but the continue jumps to the next iteration of the loop
Let us see the difference in an example:
package com.javacodegeeks.snippets.basics;
public class BreakStatementInSwitch {
public static void main(String[] args) {
for(int i = 0; i < 10 ; i++){
if(i%2 == 0){
continue;
}
System.out.println(i);
if(i%3 == 0) break;
}
}
}
5. Download the Source Code
This was a Java Break Example.
You can download the full source code of this example here: Java Break Statement Example
Last updated on Feb. 21st, 2020