Curriculum
In Java, the break
statement is used to exit a loop or switch statement prematurely. When encountered, the break
statement causes the program to immediately exit the loop or switch statement and continue executing the code that comes after the loop or switch.
The break
statement is often used in loops to prematurely exit the loop if a certain condition is met. Here’s an example:
for (int i = 0; i < 10; i++) { if (i == 5) { break; } System.out.println(i); }
In this example, the for
loop will execute 10 times, but when i
equals 5, the break
statement is encountered, causing the loop to exit prematurely. Therefore, only the numbers 0 through 4 will be printed to the console.
The break
statement can also be used in switch statements to prematurely exit the switch statement. Here’s an example:
int month = 2; String season; switch (month) { case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Fall"; break; default: season = "Invalid month"; } System.out.println("The current season is " + season);
In this example, the break
statement is used to exit each case block in the switch statement. If the break
statement was omitted from each case block, the program would “fall through” the cases and execute the code for each subsequent case until a break
statement is encountered or the end of the switch statement is reached.
The break
statement can also be used with labeled loops to exit a specific loop in a nested loop structure. This can be useful when working with complex control flow structures.