Java Tutorial

What is Java


Control Statements


Java Object Class


Java Inheritance


Java Polymorphism


Java Abstraction


Java Encapsulation


Java Array

Java OOPs Misc


Java Break Statement

The Java break is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop.

Syntax:

break; // this is a break statement.


Java Break Statement with Loop

Example:

package com.ashu;
public class Java64bitDemo {
public static void main(String ab[]) {
int [] numbers = {1, 3, 5, 7, 9,11,13,17,19};
for(int a : numbers ) {
if( a == 17 ) {
break;
// you can not write breake statement of outside if condition
}
System.out.println( a );
}
}
}


Output:1,3,5,7,9,11,13

Java Break Statement with Inner Loop

It breaks inner loop only if you use break statement inside the inner loop.

Example:

package com.ashu;
public class Java64bitDemo {
public static void main(String[] ab) {
//outer loop
for(int i=0;i<=2;i++){
//inner loop
for(int j=0;j<=2;j++){
if(i==1&&j==1){
//using break statement inside the inner loop
break;
}
System.out.println(i+" "+j);
}
// break;
}
}
}


Output:0 0
0 1
0 2
1 0
2 0
2 1
2 2

Java Break Statement with Switch

To understand the example of break with switch statement, please visit here: Java Switch Statement.

Advertisement

Copyright ©2017 Design& develop