There is another kind of loop, called a for-each loop introduced in Java 5. We will cover it later, when we have done arrays and objects.
break
we saw as part of switch
. It can also be used to break out of loops. If loops are nested it just breaks out of the current level.
Example:
for (i = 0; i < 100; i++)
{
if (i == j) break;
// ... //Only process up to j
}
This particular example could be written more neatly without using break
. How?
continue
is used in loops to skip the rest of the current cycle and go to the next one.
Example:
for (i = 0; i < 100; i++)
{
if (i % 3 != 0) continue;
// ... // only process multiples of 3
}
This particular example could be written more neatly without using continue
. How?
It is good practice always to use braces around the statement following an if, while, for, etc, even if it is just a single statement. Eg,
if (n % 7 != 0)
{
nsq = n * n;
}
If maintenance involves adding statements there will then be less risk of unexpected effects, and probably fewer changes to test plans.