Breaking out of a for loop in Java

Breaking out of a for loop in Java

In Java, you can break out of a for loop using the break statement. The break statement is used to prematurely exit a loop before it reaches its natural end. Here's how you can use it:

for (int i = 0; i < 10; i++) { if (conditionToBreak) { break; // Exit the loop } // Rest of the loop body } 

Here's a breakdown of how it works:

  1. for (int i = 0; i < 10; i++): This is a typical for loop declaration. It initializes a loop variable i, sets a condition (i < 10) for the loop to continue running, and increments i after each iteration.

  2. if (conditionToBreak) { break; }: Within the loop, you can use an if statement to check a condition. If the condition is met (i.e., conditionToBreak is true), the break statement is executed, causing the loop to exit immediately.

  3. // Rest of the loop body: Any code after the break statement will not be executed if the break is triggered.

Here's an example of breaking out of a for loop when a specific condition is met:

for (int i = 0; i < 10; i++) { if (i == 5) { System.out.println("Breaking out of the loop at i = 5"); break; } System.out.println("i = " + i); } 

In this example, the loop will exit when i becomes equal to 5, and the message "Breaking out of the loop at i = 5" will be printed.

Keep in mind that break statements can be used within nested loops as well. When a break is executed within a nested loop, it will only exit the innermost loop containing it.

Additionally, you can use labeled loops and break with a label to specify which loop you want to break out of in case of nested loops.


More Tags

windows-10 istanbul build-automation robotframework getstring validationattribute amazon-ecs horizontallist semantic-versioning datagridviewrow

More Java Questions

More Math Calculators

More Electronics Circuits Calculators

More General chemistry Calculators

More Genetics Calculators