Java Break Statement

The break statement is a control flow statement that is used to exit a loop or a switch statement in Java. It is a branching statement that allows you to terminate the loop or switch statement and transfer control to the next statement in the program.

Java Break

The break statement is typically used to exit a loop when a certain condition is met, or to break out of a loop when a specific value is found. It can also be used to exit a switch statement early, before all the cases have been evaluated.

Here is an example of how you can use the break statement to exit a loop in Java:

for (int i = 1; i <= 10; i++) {
  if (i == 5) {

In this example, the for loop iterates from 1 to 10 and prints each number to the console. The if statement inside the loop checks if the value of i is 5. If it is, the break statement is executed and the loop is terminated. If it isn’t, the loop continues to the next iteration.

The output of this loop will be the numbers 1 through 4, each on a separate line. The loop will be terminated after the fifth iteration, and the number 5 will not be printed to the console.

Here is an example of how you can use the break statement to exit a switch statement in Java:

int day = 2;

switch (day) {
  case 1:
  case 2:
  case 3:
    System.out.println("Invalid day");

In this example, the day variable is initialized with the value 2. The switch statement checks the value of the day variable and prints the corresponding day of the week to the console. If the value of the day variable is 2, the case for Tuesday is executed and the break statement is reached, causing the switch statement to be terminated. The default case is not executed because the break statement causes the switch statement to exit before it is reached.

The output of this switch statement will be the string “Tuesday”.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *