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 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: 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.
Example
Code
// Java program to illustrate using// break to exit a loopclass BreakLoopDemo {public static void main(String args[]){// Initially loop is set to run from 0-9for (int i = 0; i < 10; i++) {// 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.
0 Comments