Core Java Fundamentals ยท Loops
Learn how to prematurely exit loops and switch statements using the break keyword.
public class BreakDemo {
public static void main(String[] args) {
int[] numbers = { 10, 25, 34, 48, 56, 77, 82 };
int numberToFind = 34;
boolean found = false;
System.out.println("Searching for " + numberToFind + "...");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Checking index " + i + ": value " + numbers[i]);
if (numbers[i] == numberToFind) {
found = true;
System.out.println("Number found!");
break;
}
}
System.out.println("Loop finished.");
if (found) {
System.out.println("The number " + numberToFind + " was in the array.");
} else {
System.out.println("The number " + numberToFind + " was not in the array.");
}
}
}numbers with some values.numberToFind is declared and initialized to 34. This is the value we will search for.found is initialized to false. We will use this to track if the number was found after the loop finishes.i is initialized to 0.i < numbers.length (0 < 7) is checked. It is true, so the loop body executes.if condition checks if numbers[0] == numberToFind (10 == 34). The condition is false.i is incremented to 1.i < numbers.length (1 < 7) is checked. It is true, so the loop body executes again.if condition checks if numbers[1] == numberToFind (25 == 34). The condition is false.i is incremented to 2.i < numbers.length (2 < 7) is checked. It is true, so the loop body executes.if condition checks if numbers[2] == numberToFind (34 == 34). The condition is TRUE!if block is executed. The found flag is set to true.break statement is executed. This immediately terminates the for loop. The update statement (i++) and the condition check will NOT be executed again. Control transfers to the first statement after the loop.if statement checks the found flag. Since found is true, the if block will be executed.