In Java, loop control statements are used to control the flow of execution within loops. There are three types of loop control statements in Java: break, continue, and return.
break
The break statement is used to terminate a loop early. When a break statement is encountered within a loop, the loop immediately terminates and control is passed to the statement immediately following the loop. Here is an example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
In this example, the loop will run from i = 0 to i = 9, but when i = 5, the break statement will be executed and the loop will terminate. The output will be:
0 1 2 3 4
continue
The continue statement is used to skip over the current iteration of a loop and move on to the next iteration. When a continue statement is encountered within a loop, the current iteration is immediately terminated and control is passed to the next iteration. Here is an example:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
In this example, the loop will run from i = 0 to i = 9, but when i is an even number, the continue statement will be executed and the current iteration will be skipped. The output will be:
1 3 5 7 9
return
The return statement is used to exit a method early. When a return statement is encountered within a method, the method immediately terminates and control is passed back to the calling method. Here is an example:
public static int sum(int n) {
int total = 0;
for (int i = 1; i <= n; i++) {
if (i == 5) {
return total;
}
total += i;
}
return total;
}
In this example, the sum method calculates the sum of the first n integers, but if i is equal to 5, the return statement will be executed and the method will terminate early. The output will be:
10
This example shows how loop control statements can be used to control the flow of execution within loops and methods in Java.