BJAB?cO{WV|iyQ[BJAB?cOOhyqOhyhyhyb|OhhQ[hBJAB?cOzhy9WUwiyh^mhxQ[hBJAB?cOOhy{WOwOhh{OmhQ[hBJAB?cO{Wj|iyQ[BJAB?cO{||iy|iyQ[}}BJAB?cOzy{|9p||Q[Q[Q[BJA?ib?z{U8?zUyqzUyUyUyKUB?cO{gVp||ihQ[hBJAB?cOy{]j|zyQ[j}jBJAB?cOOhy{Wj^P|iyh^{kgyhQ[BJAB?cOzUyzUyzUybyQ{Uwiyiy|iyU^U|iyU^U|iyU^UmQ[yQ{wiyiy|iyU^UUUmQ[yQ9Q[Q[||BJAB?cOzUyqzbyQ{8pwiywiyU^UyQ{VnwiyUUyUyUyUyyQ9Q[Q[|gCbCsBffEfCEefrAX-~~~| G7VZC 847VBCC 9VBCC 886647V G7VC G774VC 5G74VCC 56G75VC G754VB 4G79V~~C 9474749846F55W~ 64646F55ZX

For.` Most runtime in programs is spent in loops. The for-loop iterates over numbers. It is commonly used. It is ideal for processing known ranges.`For each.` In Java no foreach keyword is used. Instead we use the for-keyword to iterate over each element in a collection. We do not need an index to do this.`Example.` This program uses a simple for-loop. It declares the iteration variable "i" inside the condition of the loop. It starts at 0, and continues until it is equal to 5. `First part: `The first part of the for-loop condition is where the loop iteration variable is declared and initialized.`Second part: `This is the terminating condition. In this loop, we terminate when the variable reaches 5.`Third part: `The third and final part of the for-loop is the iteration statement. This is applied after each pass through the loop.`Recommendation.` A for-loop is best when the starting and ending numbers are known. If the end index is unknown, consider a while-loop. Use a break when the end is reached.`For each.` This is a simple syntax form. If we loop over a collection, we use a colon, not an index variable. This enumerates each element in the collection (array, ArrayList). `Arrays `array-java`Info: `This is called a foreach-loop statement. The Java language does not support a "foreach" keyword. Please use the "for" keyword.`Break.` A for-loop can be stopped at any time, based on any condition. We use the "break" statement. It takes no arguments and terminates the nearest enclosing loop. `Break `break-java`More complex logic is needed to fully break out of a nested loop. A flag boolean, or the use of methods, is needed.`However: `This for-loop example scans each element in the values array. It stops (breaks) when a negative one element is found.`Continue.` This keyword stops the current loop iteration and moves to the next one. Further statements are not executed. In a loop with an iteration condition, the next iteration begins. `Continue `continue-java`Caution: `A continue statement can sometimes lead to an infinite loop. Be sure the iteration variable is incremented.`We use "continue" to skip over Strings in an array that start with the letter "b." We filter Strings.`Decrement loop.` Often we use decrementing for-loops to iterate backwards through a series of numbers. The >= operator means we include zero in the loop body. `Nested for-loops.` All kinds of loops can be nested. When we use a break or continue statement with a nested loop, only the innermost loop is affected. `However: `A return statement will exit all loops in the current method. Sometimes flag variables of boolean type are needed.`Reuse iteration variable.` Sometimes an iteration variable needs to be reused outside of a for-loop. We can use any local variable in a new for-loop. `The local variable, like x in this program, remains reachable after the loop itself terminates.`Method, for-each.` A method can be called in the for-loop. This method is evaluated once and then the results of it are accessed in the loop iteration variable. `This program shows that the method getElements is only called once. It is not called three times.`So: `When calling a variable or method in a for-each loop, we can see that the result is cached in a local and not evaluated more than once.`Overflow behavior.` Loops in Java can wrap around. This can happen in loops where we increment or decrement. The int type overflows and becomes negative, then reaches the target. `Caution: `This mistake can cause a serious performance problem. Be sure to validate your looping logic. A for-each loop also helps.`String loop.` This program uses a for-loop over a String. We start at index 0 and process until the length() is reached. With charAt we get each character at an index. `Strings `string-java`Performance, loop jamming.` In loop jamming many loops are combined into one. Consider this program—three arrays, all of the same length, must be looped over. `Version 1: `The first part loops over the three arrays separately and sums their elements.`Version 2: `The second part loops over the arrays in a single, jammed loop. This version is faster.`Result: `The single loop is nearly twice as fast as the three loops put together. And it has the same result on every iteration.`Performance, loop unrolling.` Sometimes loops are unnecessary. In loop unrolling, we change a loop to a list of statements. We can loop over groups of statements at once. `In this example we simply remove the entire loop and place the statements that need to be executed.`Unwinding: `Loop unrolling is sometimes called loop unwinding. It can improve, or reduce, performance—we must benchmark.`ArrayList.` A for-loop can be used on an ArrayList. We can iterate through the indexes, bounded by size(), or directly through the elements with simpler syntax. `ArrayList, For `arraylist-java`Loops are key to optimizations.` Often we eliminate steps from the loop body by changing the loop declaration. Loops affect control flow, causing it to repeat.`With loops,` programs gain complexity and power. Statements no longer occur in the order of program's text lines. Control flow branches, repeats, changes as time passes.

XYZ YYY { XYYYmain(Y[] args) {Z XXYYthrough 0, 1, 2, 3Y4. XXZYZ (YiY0; i < 5; i++) { XXXY.out.Yln(i); XX} X} } Z 0 1 2 3 4Z YYY { XYYYmain(Y[] args) { XXY[] YsYYY[3]; XXYs[0]YZ"Dot"Z; XXYs[1]YZ"Net"Z; XXYs[2]YZ"Perls"ZYXXZYZ (Y Y : Ys) { XXXY.out.Yln(Y); XX} X} } Z Dot Net PerlsZ YYY { XYYYmain(Y[] args) { XXY[] YsY{ 1, 2, 3, -1 };Z XXYYover Y indexes, but break on negative one. XXZY(YiY0; i < Ys.lY; i++) { XXXYYs[i]Y-1) { XXXXZbreakZ; XXX} XXXY.out.Yln(Ys[i]); XX} X} } Z 1 2 3Z YYY { XYYYmain(Y[] args) { XXY[] YsY{ Z"cat"Z, Z"bear"Z, Z"dog"Z, Z"bird"Z };Z XXYYover all Ys. XXZY(Y Y : Ys) {Z XXXYSkip Ys starting with letter b. XXXZYY.startsWith(Z"b"Z)) { XXXXZcontinueZ; XXX} XXXY.out.Yln(Y); XX} X} } Z cat dogZ YYY { XYYYmain(Y[] args) {Z XXYYfrom fiveYzero, decrementing. XXZYZ (YiY5; i >= 0; i--) { XXXY.out.Yln(i); XX} X} } Z 5 4 3 2 1 0Z YYY { XYYYmain(Y[] args) {Z XXYUse nested Y-loops. XXZYZ (YiY0; i < 3; i++) { XXXZYZ (YyY0; y < 3; y++) { XXXXY.out.Yln(iYZ","ZYy); XXX} XX} X} } Z 0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2Z YYY { XYYYmain(Y[] args) { XXZYZ xY0;Z XXYParts of the Y-loop can be omitted. XXYHere we use no variable declarationYthe Y-statement. XXZYZ (; x < 3; x++) { XXXY.out.Yln(x); XX} XXY.out.Yln(Z"x is still reachable!"Z); XXY.out.Yln(x); X} } Z 0 1 2 x is still reachable! 3Z YYY { XYYcountYXYY[] ZgetElementsZ() {Z XXYSet Y Ys based on a Yfield. XXZY[] YYYY[3]; XXY[0]Ycount++; XXY[1]Ycount++; XXY[2]Ycount++; XXY Y; X} XYYYmain(Y[] args) {Z XXYThe mY is called onceYnot many timesYthe Y-loop. XXZYZ (YY : ZgetElementsZ()) { XXXY.out.Yln(Y); XX} X} } Z 0 1 2Z YYY { XYYYmain(Y[] args) { XXlong iterationsY0;Z XXYY iterations from 100Y200 decrementing. XXZYZ (ZYZ uY100; u <= 200; u--) { XXXiterations++; XX} XXY.out.Yln(Z"Iterations from 100Y200: "ZYiterations); X} } Z Iterations from 100Y200: 2147483749Z YYY { XYYYmain(Y[] args) { XXY YYZ"art"Z;Z XXYYfrom 0YlY() of the Y. XXZYZ (YiY0; i < Y.lY(); i++) {Z XXXYYletters with charAt mY. XXXZchar letterYY.ZcharAtZ(i); XXXY.out.Yln(letter); XX} X} } Z a r tZ YYY { XYYYmain(Y[] args) { XXY[] Y1Y{ 10, 20, 30 }; XXY[] Y2Y{ 20, 10, 30 }; XXY[] Y3Y{ 40, 40, 10 }YXXlong t1YY.currentTimeMillis();Z XXYVersion 1: loop over each Y separately. XXZY(YiY0; i < 10000000; i++) { XXXYsumY0; XXXZYZ (YxY0; x < Y1.lY; x++) { XXXXsum Z+=Z Y1[x]; XXX} XXXZYZ (YxY0; x < Y2.lY; x++) { XXXXsum Z+=Z Y2[x]; XXX} XXXZYZ (YxY0; x < Y3.lY; x++) { XXXXsum Z+=Z Y3[x]; XXX} XXXYsum != 210) { XXXXY.out.Yln(false); XXX} XX} XXlong t2YY.currentTimeMillis();Z XXYVersion 2: jam loops together. XXZY(YiY0; i < 10000000; i++) { XXXYsumY0; XXXZYZ (YxY0; x < Y1.lY; x++) { XXXXsum Z+=Z Y1[x]; XXXXsum Z+=Z Y2[x]; XXXXsum Z+=Z Y3[x]; XXX} XXXYsum != 210) { XXXXY.out.Yln(false); XXX} XX} XXlong t3YY.currentTimeMillis();Z XXYTimes. XXZY.out.Yln(t2 - t1); XXY.out.Yln(t3 - t2); X} } ZResultsZ Z109 msZ, 3 Y-loops Z 48 msZ, 1 Y-loop (jammed)Z YYY { XYYYmain(Y[] args) { XXY[] Y1YYY[5]YXXlong t1YY.currentTimeMillis();Z XXYVersion 1: assign YsYa loop. XXZY(YiY0; i < 10000000; i++) { XXXY(YxY0; x < Y1.lY; x++) { XXXXY1[x] Z=Z x; XXX} XX} XXlong t2YY.currentTimeMillis();Z XXYVersion 2: unroll the loopYuse a Y of statements. XXZY(YiY0; i < 10000000; i++) { XXXY1[0] Z=Z 0; XXXY1[1]Y1; XXXY1[2]Y2; XXXY1[3]Y3; XXXY1[4]Y4; XX} XXlong t3YY.currentTimeMillis();Z XXYTimes. XXZY.out.Yln(t2 - t1); XXY.out.Yln(t3 - t2); X} } ZResultsZ Z56 msZ, Y-loop Z17 msZ, unrolled statementsZ

,XeUX6`9e7`4-for-loopfor, alternate syntaxbreakcontinuedecrements in for-loopnested for-loopsreuses iteration variablemethod, for-each loophas loop overflow errorfor-loop, stringapplies loop jammingunrolls loops