How to break out of a loop in Java
In Java, the break statement can be used to exit a loop. When the break statement is executed, the program will immediately exit the current loop and continue executing the code after the loop.
Here is an example demonstrating how to use the break statement to exit a loop:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // 当i等于5时跳出循环
}
System.out.println(i);
}
In the above example, when i equals 5, the break statement is executed, causing the program to exit the loop with the output as:
0
1
2
3
4
It is important to note that the break statement can only exit the current loop. If there are multiple nested loops, it will only exit the innermost loop. If you want to break out of multiple loops, you can use a label to identify the outer loop and specify the label in the break statement to exit the specified loop.