The Enhanced for Loop

Part of: Array

A Cleaner Way to Read Elements. The enhanced for loop (also called the for-each loop ) visits every element of an array without an explicit index. It reads naturally: "for each value in the array." The variable value takes on each element in turn: first 5, then 10, then 15. The colon : reads as "in". Syntax Rules. The loop header has the form for (Type var : array): - Type must match the array's element type (int for int[], String for String[]). - var is a fresh copy of each element, not the element itself. - There is no index, no length, and no i++ to manage. The Key Limitation: You Cannot Modify the Array. Because the loop variable is a copy, assigning to it does not change the array: To modify elements, you must use an indexed for loop and write a[i] = .... The enhanced for loop is for reading and accumulating (summing, counting, searching), not for changing the array in place. When to Use Which. - Use the enhanced for when you only need each value and do not care about position: summing, counting, finding a max. - Use the standard for when you need the index, want to modify elements, or only traverse part of the array. What usually goes wrong. What you see What caused it How to

Challenge: Count Even Numbers