break outer loop java code example
Example 1: break java
//Conclusion
break == jump out side the loop
continue == next loop cycle
return == return the method/end the method.
for(int i = 0; i < 5; i++) {
System.out.println(i +"");
if(i == 3){
break;
}
}
System.out.println("finish!");
/* Output
0
1
2
3
finish!
*/
Example 2: how to break out for loop java
//Java Program to demonstrate the use of break statement
//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Example 3: how to break from a loop in java
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Example 4: how to break two loop in java
import java.io.IOException;
/**
* How to break from nested loop in Java. You can use labeled
* statement with break statement to break from nested loop.
*
* @author WINDOWS 8
*/
public class BreakingFromNestedLoop{
public static void main(String args[]) throws IOException {
// this is our outer loop
outer: for (int i = 0; i < 4; i++) {
// this is the inner loop
for (int j = 0; j < 4; j++) {
// condition to break from nested loop
if (i * j > 5) {
System.out.println("Breaking from nested loop");
break outer;
}
System.out.println(i + " " + j);
}
}
System.out.println("exited");
// better way is to encapsulate nested loop in a method
// and use return to break from outer loop
breakFromNestedLoop();
}
/**
* You can use return statement to return at any point from a method.
* This will help you to break from nested loop as well
*/
public static void breakFromNestedLoop(){
for(int i=0; i<6; i++){
for(int j=0; j<3; j++){
int product = i*j;
if(product > 4){
System.out.println("breaking from nested loop using return");
return;
}
}
}
System.out.println("Done");
}
}
Output
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
Breaking from nested loop
exited
breaking from nested loop using return
Example 5: break statement in java
// break statement in java
public class BreakStatementExample
{
public static void main(String[] args)
{
for(int a = 1; a <= 10; a++)
{
if(a == 3)
{
// breaking loop
break;
}
System.out.println(a);
}
}
}
Example 6: break for loop java
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}