Branching statements are used to change the normal flow of execution in a program.
The break statement is used to exit a loop or switch block prematurely.
xxxxxxxxxxpublic class BreakExample { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 5) { break; // Exit the loop when i is 5 } System.out.println("i = " + i); } }}i = 0
i = 1
i = 2
i = 3
i = 4The continue statement is used to skip the current iteration of a loop and continue with the next iteration.
xxxxxxxxxxpublic class ContinueExample { public static void main(String[] args) { for (int i = 0; i < 5; i++) { if (i == 2) { continue; // Skip when i is 2 } System.out.println("i = " + i); } }}i = 0
i = 1
i = 3
i = 4The return statement is used to exit a method and optionally return a value.
public class ReturnExample { public static void main(String[] args) { System.out.println("Sum = " + add(5, 10)); } public static int add(int a, int b) { return a + b; // Return the sum of a and b }}Sum = 15