The break statement in Java is used to exit a loop or switch statement. It can be used to: 1. Exit a loop when a condition is met; 2. Exit a switch statement when a specific case is matched. Note that break can only be used to exit the loop or switch statement in which it is contained.
Usage of break in Java
In Java, the break statement is used to exit the currently executing loop or switch statement. It causes the program to break out of the loop or switch statement and continue executing the statements following the loop or switch statement.
Grammar
The syntax of the break statement is very simple:
<code class="java">break;</code>
Usage
The break statement is usually used In the following situations:
<code class="java">for (int i = 0; i < 10; i++) { if (i == 5) { break; } System.out.println(i); }</code>
<code class="java">switch (color) { case "red": System.out.println("颜色是红色"); break; case "green": System.out.println("颜色是绿色"); break; default: System.out.println("未知颜色"); }</code>
Note: The
The above is the detailed content of How to use break in java. For more information, please follow other related articles on the PHP Chinese website!