Break And Continue In Java

Break Statement

In this tutorial we will discuss, break and continue in java. As we discussed earlier in our switch statement chapter, we said that break is used to show the end of each case. But now in this part we explain how you can use break to jump out of the loop or terminate a loop. See this example here, use of break in for loop;


for (int x = 0; x < 10; x++){
 if(x == 5){
  break;
}
System.out.println(x);
}

In the above example, the loop with stop at the point where the value of x is 5.

-Alternatively, we can use break statement in while loop, see this example;


int x = 0;
while (x<10){
 System.out.println(x);
 x++;
if(x == 5){
 break;
 }
}

Continue Statement

continue statement as its name suggests, it breaks one iteration if the specified condition becomes false, then it continues with the next iteration, we will have examples when using for loop and while loop; see this example;


for (int x = 0; x < 10; x++){
 if(x == 5){
  continue;
}
System.out.println(x);
}

In the above example the loop will first stop at 5, then it continues.

We can have an example here using while loop;


int x = 0;
while (x<10){
if(x == 5){
x++;
 continue;
 }
System.out.println(x);
x++;
}
For better understanding, you may do as many examples as possible. We have also videos on our Youtube Channel, subscribe and be the first to view our videos once uploaded. Let's meet in our next tutorial for an awesome content. Thank you!