For-Each Loop

Premium Content - Free Preview

If all you had were if-statements and while loops to control your program, your code could accomplish almost everything more 'powerful' code could do. However, it would take longer and be less clear. Programming languages provide additional features to help people write shorter clearer code.

There are several features and 'shortcuts' in Java that may not provide you with new powers, but they let you write shorter code in a clearer manner. We will go through a few of them.

The For-Each Loop

Let's say you have an array called array1:

array1 = {1,2,3,4};

For Loops are often used to iterate through a collection, including the simple array. For example, if you wanted to print out every element in array1, you could use this code:

for(int i=0; i<array1.length; i=i+1){ 

Which will produce the following output:


Notice that you just wanted to access each item in the array, and did not care about the item's array index. These types of cases are very common, so Java introduced the for-each loop, which provides access to each element in a collection without requiring an index variable. This is its basic format:

for (type variable : array) {
    //do stuff.. 

The for-each loop header simply declares a variable to hold each element in the array and states the array it will go through.

The previous basic for-loop code could be replaced with this:

 for(int num : array1){

This loop header can be read in English as:

End of Free Content Preview. Please Sign in or Sign up to buy premium content.


  • Why is (1) incorrect? Can not I write :

    for(int num : array1){
    if(num%2!=0 && num<200){

  • @Lukas, there's no array to go through. And if there was, num would be set to the values in the array, since it's a for-each loop, which is probably different than 1 to 200.

  • I don't really understand fully this challenge... and I'm getting frustrated trying to do this simple task.

    Here's my code:

    String word; for(int num : words){ word+=words[num] };

    I find it really hard to write code in that little field.

  • In the first challenge, you just need to declare the 'header' for the for loop. Since it goes through a String array you'll need to declare the variable as a String.

Contact Us
Sign in or email us at [email protected]