Break statement in Java

A break statement in java is a loop control statement in java and us for terminating the loop. The break statement is encountered from within the loop, iteration stops there, and control returns from the loop moves to the first statement after the loop.

Syntax

break;

Break statement in a scenario when the actual number of iteration is not clear or we want to terminate the loop according to some condition.

Break statement in Java


Break: In Java, the break is majorly used for: 

  • Terminate a sequence in a switch statement (discussed above).
  • To exit a loop.
  • Used as a “civilized” form of goto.

Using break to exit a Loop

Using break, we force immediate termination of a loop, bypassing the conditional expression and any remaining as it is code in the body of the loop. 

Break statement in Java



Example

Code

// Java program to illustrate using
// break to exit a loop
class BreakLoopDemo {
   public static void main(String args[])
   {
       // Initially loop is set to run from 0-9
       for (int i = 0i < 10i++) {
           // terminate loop when i is 5.
           if (i == 5)
               break;

           System.out.println("i: " + i);
       }
       System.out.println("Loop complete.");
   }
}

Output

i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.

Post a Comment

0 Comments