Home Java Java-tips Flow Loops Loop break statement

Ask Questions?

View Latest Questions

Advertisement


 
 

Loop break statement
Posted on: July 26, 2006 at 12:00 AM
Loops are often used to accomplish the same kinds of tasks, so many loops tend to be one of several common styles.

Java Notes

Loop break statement

Loops are often used to accomplish the same kinds of tasks, so many loops tend to be one of several common styles.

Loop reading input

Immediate loop exit. When you execute a break statement, the loop is exited immediately and control flow proceeds with the the statement after the loop.

Loop condition is better. Altho you can terminate any loop with a break, it is generally better to use the loop condition to terminate the loop because it's easier to understand.

Sometimes you are in deep nested if statements within a loop, and you want to stop looping. A break is an easy way to do that. An alternative is to set a boolean variable that is tested at various points. The boolean variable solution is OK in simple situations, but it can lead to extremely convoluted code. [Need example here]

Is break evil?

Control flow is simplest to understand when each block has a single exit. You always know that the execution continues to the end. The break statement violates these expectations. It should only be used where it improves readability of the program.

Example with and without break

Here is a an example that shows how break can

Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com