Cover Image for Java Break
165 views

Java Break

The break statement in Java is used to exit from a loop or a switch statement prematurely. It allows you to immediately terminate the execution of the innermost loop or exit from a switch statement. The break statement is commonly used to control the flow of your program in various situations.

Here’s how the break statement is used in different contexts:

  1. Breaking from a Loop:
    The break statement is often used in loops, such as for, while, and do-while, to exit the loop before it completes all its iterations.
   for (int i = 1; i <= 10; i++) {
       if (i == 5) {
           break; // Exit the loop when i is 5
       }
       System.out.println(i);
   }

In this example, the loop will exit when i becomes 5, and the remaining iterations will be skipped.

  1. Breaking from a Switch:
    The break statement is used in a switch statement to exit the switch block after executing a case. Without break, execution would “fall through” to the next case.
   int day = 2;

   switch (day) {
       case 1:
           System.out.println("Sunday");
           break;
       case 2:
           System.out.println("Monday");
           break;
       default:
           System.out.println("Other day");
   }

In this example, when day is 2, “Monday” will be printed, and the break statement will exit the switch statement. Without the break, both “Monday” and “Other day” would be printed.

  1. Breaking from Labeled Blocks:
    You can also use the break statement to exit from a labeled block or nested loops. A labeled block is marked with an identifier followed by a colon, and you can specify the label as an argument to break.
   outerLoop: for (int i = 1; i <= 5; i++) {
       for (int j = 1; j <= 5; j++) {
           if (i * j == 12) {
               break outerLoop; // Exit both loops when i*j is 12
           }
           System.out.println(i * j);
       }
   }

In this example, when i * j equals 12, the break statement with the label outerLoop will exit both the outer and inner loops.

The break statement provides a way to control the flow of your program and is useful for exiting loops or switch statements when certain conditions are met. It is important to use it judiciously to avoid unexpected program behavior.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS