You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Where a normal `for` loop is more or less a shorthand for a certain kind of `while` loop,
4
+
a for-each loop[^enhanced] is a shorthand for the general concept of iterating over a collection
5
+
of elements.
6
+
7
+
To use a for-each loop, write `for` then in the parentheses write a variable declaration, a `:`, and the
8
+
collection of elements you are iterating over.
9
+
10
+
```
11
+
for (<VARIABLE DECLARATION> : <COLLECTION>) {
12
+
<BODY>
13
+
}
14
+
```
15
+
16
+
```java
17
+
record Bread(String name, boolean french) {}
18
+
19
+
~classMain {
20
+
~voidmain() {
21
+
Bread[] breads = {
22
+
newBread("Croissant", true),
23
+
newBread("Baguette", true),
24
+
newBread("Boston Brown Bread", false)
25
+
};
26
+
27
+
for (Bread bread : breads) {
28
+
System.out.println(
29
+
bread.name()
30
+
+ (bread.french() ?" is french":" is not french")
31
+
);
32
+
}
33
+
~ }
34
+
~}
35
+
```
36
+
37
+
38
+
[^enhanced]: You might see this referred to as an "enhanced for statement." [That is its name in the language spec](https://docs.oracle.com/javase/specs/jls/se23/html/jls-14.html#jls-14.14.2) but not the name most people will use.
0 commit comments