What is the purpose of the “break” statement in Java?
In Java, the break statement is used to end a loop or exit a switch statement.
- In a loop, the break statement can be used to immediately terminate the loop and exit the loop body when a condition is met. This can save unnecessary iteration times during the loop process and improve program execution efficiency.
For example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // 当i等于5时,立即结束循环
}
System.out.println(i);
}
Output results:
0
1
2
3
4
- In a switch statement, the break statement is used to exit the switch block. Without a break statement, the program will continue to execute the next case until a break statement is encountered or the switch block ends.
For example:
int num = 2;
switch (num) {
case 1:
System.out.println("Number is 1");
break;
case 2:
System.out.println("Number is 2");
break;
default:
System.out.println("Number is not 1 or 2");
break;
}
Output result:
Number is 2
By using the break statement, you can control the flow of the program in order to execute it the way you want.