Enhanced for Loops - the For-Each Loop

Contact Us or call 1-877-932-8228
Enhanced for Loops - the For-Each Loop

Enhanced for Loops - the For-Each Loop

Java 5 introduced the for-each loop, which loops through a collection of values without using an index. Instead, the loop variable repesents each individual value.

The syntax uses a loop variable and a collection of values, separated by a colon character (which can be read as the word "from"). Some things to note:

  • The collection of values can be any array or an instance of one of the Java Collections classes (to be discussed later)
  • The looping variable must be declared in the parentheses that create the loop - you cannot use a preexisting variable as the loop variable
  • The looping variable will represent each item from the collection or array in turn.
for (dataType loopVariable : collectionOfSameType) code using loopVariable;

You cannot write into the array using a for-each loop. The looping variable you declare receives a copy of the data in the array, so, if you change its value, you are only changing the local copy.