Totals, maximum and counting with for-each
for (Type item : collection) visits every element of an array or any Iterable (like a List) in order, with no index to get wrong. The loop variable is a copy of each element, and you must not add to or remove from a collection while walking it this way.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given String[] words = {"java", "loop", "enhanced", "for"}, use for-each to find the longest word and the total number of letters.
Count how many times the letter l appears in "hello world, hello loops" using for-each over the characters.
Given List<Integer> nums = List.of(3, 8, 1, 9, 4), use for-each to build a new ArrayList containing only the numbers greater than 3, then print it.
Explain it without notes
What can the enhanced for loop iterate over, and what does the compiler turn it into?
Why doesn't for (int x : arr) x = 0; clear the array, while for (StringBuilder sb : arr) sb.setLength(0); does clear every builder?
Why does removing from an ArrayList inside a for-each loop throw ConcurrentModificationException, and how should you remove instead?
When must you use a classic for loop instead of for-each?
Expected output
Total: 411
Average: 82.2
Best: 95
90 or above: 2
Vowels: 6