Java Control Statements
- Java if Statement
- Java Nested if Statement
- Java if-else-if Statement
- Java Switch Case
- Java Switch with String
- Java Nested Switch
- Java Simple for Loop
- Java for each Loop
- Java Nested for Loops
- Java while loop
- Java continue Statement with for Loop
- Java continue in do-while Loop
- Java break to Exit a for Loop
- Java break with Nested Loops
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.");
}
}
Output:
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.
Control Statements
Java
Java Tutorial
Comments
Post a Comment