Avatar ·

How does the for-each loop actually work in Java? Detailed explanation with examples

Hi everyone! I recently started learning Java and came across the for-each loop. It seems clear enough: for (int x : numbers) { ... } — it just iterates over array or collection elements. But when I started digging deeper, many questions arose.\n\nFor example, I wrote this code:\n\n
List<String> list = new ArrayList<>();\nlist.add("A");\nlist.add("B");\nlist.add("C");\n\nfor (String s : list) {\n    if (s.equals("B")) {\n        list.remove(s); // ConcurrentModificationException!\n    }\n}\n
\n\nAnd got a ConcurrentModificationException. Why? In a regular for (int i = 0; i < list.size(); i++) this doesn't happen.\n\nAnother example — I tried to modify array elements through for-each:\n\n
int[] arr = {1, 2, 3};\nfor (int x : arr) {\n    x = x * 2; //