Home and Learn: Java Programming Course


For-each in Java

You saw in the previous lesson how we used an iterator to loop though an Array List. However, there is an easier way, and that's with a for-each loop. Let's see how to use them.

Suppose you had an Array List that contained orders:

//IMPORT AT TOP OF CODE
import java.util.ArrayList;

ArrayList listOrder = new ArrayList( );

listOrder.add( 1429 );
listOrder.add( "High Heels" );
listOrder.add( "Red" );
listOrder.add( 59.99 );

listOrder.add( 14390 );
listOrder.add( "Boots" );
listOrder.add( "Black" );
listOrder.add( 89.99 );

As in the previous section, we could set up an iterator and then print out the orders. Instead, you can use the for-each loop in Java. It looks like this:

for (Variable Type variable_name : your_arrayname)
{

//CODE HERE

}

You start with the word for. In between round brackets, you need a variable type (like String, int, Object). After a space, you type a name for your variable. Next comes a colon (:). After the colon, you need the name of your array or collection. Add this to test it out:

for ( Object order : listOrder ) {

System.out.print(order + " " + "\r\n");

}

The whole thing reads, 'for each order in listOrder, print something out'. (Because we have mixed values in our array list, we've used Object as the variable type.)

You can use for-each with ordinary arrays, as well, not just Array Lists. Here's an example to try out.

String[] months = {"Jan", "Feb", "March", "April"};

for (String singleMonth : months) {

System.out.println(singleMonth);

}

Or you can have all numbers:

int[] lotteryNumbers = {2, 5, 7, 18, 45, 46};

for (int num : lotteryNumbers) {

System.out.println(num);

}

The for-each loop in Java is a lot easier to use than iterators. They are perfect for when you don't much care about loop index numbers.


We'll leave arrays, for now, and move on. In the next section, we'll tackle strings.

<-- Array Lists | Java Strings -->

Back to the Java Contents Page

 


Email us: enquiry at homeandlearn.co.uk