Java break Statement to Exit a for Loop

This Java example demonstrates how to use a break statement to exit a for loop in Java with an example.

Using a break to Exit a for Loop

By using a break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop.
Here is a simple example:
package net.javaguides.corejava.controlstatements.loops;

public class BreakWithForLoop {
    public static void main(String args[]) {
        for (int i = 0; i < 100; i++) {
            if (i == 10)
                break; // terminate loop if i is 10
            System.out.println("i: " + i);
        System.out.println("Loop complete.");
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
As we can see, although the for loop is designed to run from 0 to 99, the break statement causes it to terminate early, when i equals 10.