Java break and continue statement is crucial part of java control statements. When a break statement is executed inside a loop, the loop is instantly terminated and the program control restarted at the next statement of the loop.
Java Break Statement:
Java break statement is used to break the loop or switch statement. Java break statement breaks the current flow of the program at specified conditions. If it executes in the inner loop, then it breaks only the inner loop.
Java Break syntax:
break;
Flow diagram of java break statement:
Example of Java Break Statement
public class BreakExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop when matched case
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java continues statement:
While working with java loops, sometimes we might want to skip some lines of codes or terminate the loop. In such cases, java breaks and continue statements are used.
The Continue statement skips the current iteration of the loop and jumps to the starting of the loop for executing the next iteration.
import java.util.*;
public class ContinueExample{
public static void main(String args[])
{
for (int i = 0; i <= 13; i++) {
// Checking the condition for continue
if (i == 10 || i == 11) {
// Using continue statement to skip the
// execution of loop when i==10 or i==11
continue;
}
System.out.println(i + " ");
}
}
}
Output:
The return
Statement:
The Java return statement exits from the current method, and control flow returns to where the method was invoked. Every Java method has a return type and it is mandatory for all java methods. A return type in Java may be a primitive type such as int, float, double, a reference type or void type(which returns nothing).
Example of Return type:
public class ReturnExample {
int display()
{
return 15;
}
public static void main(String[] args) {
ReturnExample e =new ReturnExample();
System.out.println(e.display());
}
}
Output:
10