Java Break Page
Syntax
break;
Example
Loop through an array in Java and break out of the loop when a specific value is found.
int[] numArray = {5, 10, 15, 20, 25};
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == 15) {
break;
}
System.out.println(numArray[i]);
}
Output
5
10
Explanation
The break
statement in Java is used to exit a loop prematurely. When the break
statement is encountered inside a loop, the loop is terminated immediately and the program continues execution at the next statement following the loop.
In the example above, we loop through an array of integers and print out each value until we reach the value of 15. When the loop reaches the value of 15, the break
statement is executed, and the loop is terminated prematurely. The program then moves on to the next statement, which is outside the loop.
Use
The break
statement in Java is often used to terminate loops early when a certain condition is met. It is also commonly used in switch statements to exit the switch block when a particular case is matched.
Important Points
- The
break
statement in Java is used to exit a loop or switch block prematurely. - When the
break
statement is encountered inside a loop, the loop is terminated immediately and execution continues at the next statement following the loop. - The
break
statement is often used to terminate loops early when a certain condition is met. - The
break
statement is also used in switch statements to exit the switch block when a particular case is matched.
Summary
In Java, the break
statement is a powerful tool for terminating loops or switch blocks prematurely. It is used to exit a loop immediately when a certain condition is met or to exit a switch block when a particular case is matched. The break
statement is an essential tool for any Java programmer and is used frequently in many kinds of programs.