Was Java’s “for each” version of its for
statement originally called foreach
?
Java 5 introduced the "for each" syntax. But why did they have to use the keyword for
, instead of the keyword foreach
used by practically every other language?
PHP | foreach (list as element) |
Perl | foreach my element (list) |
Java | for (element : list) |
Javascript | for (var element in list) |
C# | foreach (element in list) |
Java already has the keyword for
to do the traditional C-style loops, as do most other languages. For example:
for ( ... ; ... ; ... ) { .. } # standard C stuff for (Object x : list) { ... } # new "for each" syntax
Check out the documentation for the Iterable
interface.
Implementing this interface allows an object to be the target of the "foreach" statement.
They specifically refer to the foreach
statement which, as discussed above, doesn't exist in Java.
I conclude from this that they weren't quite sure themselves how to name the keyword, and that they made their decision quite late in the day.
(It's been corrected in Java 8's documentation.)