在 Java 编程中,break
、continue
、goto
和 return
是控制流程的关键字。它们用于控制程序的执行流程。
1. break
break
用于终止循环或switch
语句,并跳出当前循环或switch
语句的执行。public class BreakExample { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 5) { break; // Terminates the loop when i is 5 } System.out.println("i: " + i); } } }
2. continue
continue
用于跳过当前循环中的剩余语句,并立即开始下一次循环迭代。public class ContinueExample { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 5) { continue; // Skips the rest of the loop body when i is 5 } System.out.println("i: " + i); } } }
3. goto
在 Java 中,没有直接的
goto
关键字,因为它容易导致代码的可读性和可维护性变差。但是,Java 支持通过标签和break
或continue
结合使用来实现类似goto
的行为。public class GotoExample { public static void main(String[] args) { outerLoop: // Label for the outer loop for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outerLoop; // Exits both loops when i is 1 and j is 1 } System.out.println("i: " + i + ", j: " + j); } } } }
4. return
return
用于从方法中返回值或终止方法的执行。public class ReturnExample { public static void main(String[] args) { int result = sum(5, 10); System.out.println("Sum: " + result); } public static int sum(int a, int b) { return a + b; // Returns the sum of a and b } }