Lesson Weekend

In Intro to Programming, we used two types of JavaScript loops: for and forEach(). forEach() loops iterates through each item in an array, whereas for loops are a little more manual: We had to define how and when the loop starts and stops.

Java also features both for and for each loops, although the syntax does differ. This lesson will walk through each of these two types of loops. Pay careful attention to the new, Java-specific syntax.

For Each Loops

As you know, for each loops cycle through an array and pinpoint each item. In JavaScript, we used for each loops like this:

var theEntireArray = ["zero index", "first index", "second index"];

theEntireArray.forEach(function(individualEntry){
  console.log(individualEntry);
});

However, doing the same thing in Java looks markedly different! First off, defining a similar array in the REPL would look like this:

> String[] theEntireArray = {"zero index", "first index", "second index"}
java.lang.String[] theEntireArray = ["zero index", "first index", "second index"]

And then, to loop through this array, we'd use the following code:

 for ( String individualEntry : theEntireArray ) {
      System.out.println( individualEntry );
  }

Notice here that even though this is considered a "for each" loop, Java uses only a for keyword. Additionally, instead of a callback function, Java simply requires we state the variable name for the individual entry, and the variable name for the entire array separated by a colon, as seen above.

We can run this loop in the REPL, and see that it prints each individual item in the array:

>  for ( String individualEntry : theEntireArray ) {
    |       System.out.println( individualEntry );
    |   }

zero index
first index
second index

Grocery Store Application

Let's practice Java for each loops a little more before moving on. We'll craft an application to manage a grocery list. Create a new project named grocery-list, create a GroceryList.java file with a class name, main() method, and array of grocery list items:

src/main/java/GroceryList.java
public class GroceryList {
  public static void main(String[] args) {
    String[] myGroceryList = { "ice cream", "hot sauce", "pickles", "bananas", "cereal", "rice", "yogurt"  };

    }
}

We can loop through each item in the myGroceryList array like this:

src/main/java/GroceryList.java
public class GroceryList {
  public static void main(String[] args) {
    String[] myGroceryList = { "ice cream", "hot sauce", "pickles", "bananas", "cereal", "rice", "yogurt"  };

    for ( String groceryItem : myGroceryList ) {
      System.out.println( groceryItem );
    }
  }
}

This code will print each item in myGroceryList to the console.

For Loops

For each loops are great when we want to do something to each element of an array. But sometimes we want to do something repeatedly until a condition is met. For that, we can use a for loop.

Let's refactor our GroceryList app to use a for loop instead of a for each loop, so we can check out the differences between these two types of loops:

for-loop/GroceryList.java
public class GroceryList {
  public static void main(String[] args) {
    String[] myGroceryList = { "eggs", "milk", "bread", "bananas", "cereal", "rice" };

    for (Integer index = 0 ; index < myGroceryList.length ; index++) {
      System.out.println( myGroceryList[index] );
    }
  }
}

Notice that both for and for each loops in Java both use the for keyword. It's the syntax within the parentheses following for that differ depending on the type of loop we're defining.

  • Just like in JavaScript, the for statement here takes three parameters: Initialization, condition, and final expression, separated by semicolons ;.

  • The initialization parameter (Integer index = 0) creates an Integer called index that starts at zero.

  • The condition parameter (index < myGroceryList.length) tells the loop when it should stop running. In this case, we've instructed our loop to halt when index is no longer less than myGroceryList.length.

  • The final expression parameter (index++) lets us manipulate the variable that keeps track of where we are in the loop (that is, the same index variable we defined in our initialization parameter). Here we use the increment operator ++ to add 1 to index each time we go through the loop.

  • Within the loop, we include the line System.out.println( myGroceryList[index] );. On each loop through we locate and print the item in myGroceryList at the current index.

Other Loops

There are other kinds of loops in Java too, such as while loops (do something until a condition is met) and do while loops that are very similar. The difference between do while and while is that do while evaluates its expression at the bottom of the loop, whereas while evaluates its expression at the top. This means the statements within the do block are always executed at least once.

Take a look at the Java Documentation on Loops to familiarize yourself.

Break and Continue

break and continue keywords can help us control the loop from inside. break causes a loop to stop and run the statement immediately following the loop. This is useful when we need to stop a loop from a nested conditional. continue does the opposite:

int i;
for (i = 0; i < 5; i++) {
    if (i >= 2) {
        break;
    }
    System.out.println("Yuhu");
}
System.out.println(i);
// Output:
// Yuhu
// Yuhu
// 2