Iteration means that a code block must be executed several times, depending a condition.
Iterations (or loops) can be designed by using loop formulas.
Every formula has its pros and cons.
Every iterations can be coded by utilizing any iteration formulas, use the one fitting better for the task or expressing the code better.
EXAMPLE FOR FOR LOOP FORMULA:
Initial expression: invokes once, before starting the loop; declaration.
Test expression: tested before every cycle for being true.
Update expression: changes variables of test expression.
In case parts of the test expression comes from a property or a method of an object at the beginning of the iteration, calculating with that will take place at every starting of the loop.
Against that, the initial expression can contain definitions of several variables which will be alive within the loop only.
This technique creates an optimized loop fitting for potentially bigger arrays, ArrayLists etc.
In case the loop should go in decrementing direction or the increment should be different that 1, any expression the incrementing part can accept in case that expression has a return value (i++, i--, i + 3, methodName() etc.).
EXAMPLE FOR FOR LOOP WITH CONSTANTS IN ITS HEAD:
EXAMPLE FOR FOR LOOP WITH VARIABLES IN ITS HEAD (NOT OPTIMIZED):
EXAMPLE FOR FOR LOOP WITH VARIABLES IN ITS HEAD (OPTIMIZED):
For arrays and collections.
With this technique, all elements will be visited in incrementing order but by default, element indexes will not be accessible within.
EXAMPLE FOR FOR-EACH LOOP FORMULA:
EXAMPLE FOR FOR-EACH LOOP:
This technique lets full manipulation of the loop head.
Be aware of handling the test expression to have an ending of the loop.
EXAMPLE FOR WHILE LOOP FORMULA:
Test expression: tested before every cycle for being true (enters only when conditions met). Can be optimized by pre-calculating everything possible before reaching the loop.
EXAMPLE FOR WHILE LOOP:
This technique forms technically an inverted while-loop.
EXAMPLE FOR DO-WHILE LOOP FORMULA:
Test expression: tested after every cycle for being true (enters minimum once).
EXAMPLE FOR DO-WHILE LOOP:
Iteration by using a method which calles itself until condition met, then returns the result.
Typical solution for processing folder tree.
Initialization of a method is a slower process, will happen in all loops.
Fast to write and correct, needs less code.
Fills the stack, therefore with the exception of processing folder tree, it is advised not to implement it.
EXAMPLE FOR RECURSION:
When updating (or not updating at all) the condition prevents the loop condition from turning to false.