Java Break Statement

The Java Break and Continue are two important statements used to alter the flow of a program in any programming language.

In Java Programming, Loops are used to execute certain block of statements for n number of times until the test condition is false. There will be some situations where, we have terminate the loop without executing all the statements. In these situations we can use this Java Break statement and Continue statements.

Java Break Statement

The Java Break statement is very useful to exit from any loop such as For Loop, While Loop and Do While Loop. While executing these loops, if compiler finds the break statement inside them, it will stop executing the statements and immediately exit from the loop.

For example, we have 10 statements inside the loop and we want to exit from the loop when certain condition is True otherwise, it has to execute all of them. In this situation we can use If Statement to check for the condition and place the Break statement inside the If block. If the condition is True then compiler will execute the break statement and, the Java break statement will exit the controller from the loop completely otherwise, it will execute all the statements.

In this Java Break Statement in For loop example, First, We initialized the value of i as: i = 10 at the beginning of the code. Within the For loop we initialized the value of i as: i = 0 and the condition will check whether i is less than or equal to 10 and lastly, we used Increment Operator to increment the value by 1.

Inside the For loop we placed If statement to test whether i is equal to 7.

If the condition is false then it will skip the Break statement and prints that number as output (In Our case 0, 1, 2, 3, 4, 5, 6).

If this condition is True then Break statement will be executed and the iteration will stop at that number without printing the System.out.format(“%d”, i) statement.

Java While Loop Break Statement

In this program, We are going to use the Java break statement inside the While loop to exit from the loop iteration.