Lesson Thursday

Sometimes you may want to create something by combining two collections together in some manner. The DRY-est way to do this is with a nested loop, like this:

``````Integer[] numbers = {1, 2};
String[] letters = {"a", "b"};

for (Integer number : numbers) {
for (String letter : letters) {
System.out.println(number + letter);
}
}
``````

The code above would print:

``````1a
1b
2a
2b
``````

Here's another example of a nested loop being used to re-create a deck of cards:

``````String[] suits = {"Spades", "Clubs"};
String[] values = {"Ace", "2", "3"};

for ( String suit : suits ) {
for ( String value : values) {
System.out.println(value + " of " + suit);
}
}
``````

The code above would print:

``````Ace of Spades
Ace of Clubs
2 of Clubs
3 of Clubs
``````

In each both examples above, one loop is running inside of another loop.

• In the first example we run this loop: `for (Integer number : numbers) {` asking it to create the variable `number`. Then we run a second loop, `for (String letter : letters) {`, creating the variable `letter`. Inside of the second loop we have access to both the `letter` and `number` variables.

• The next time through the nested loop, `for (String letter : letters) {`, our `letter` variable will have changed. However, since we are still inside the first iteration of the outer `for (Integer number : numbers) {` loop, our `number` variable is still `1`.

• After cycling through the entire `for (String letter : letters) {`, loop, our `number` variable in the outer loop will change to `2` . Then, we'll go through the entire `for (String letter : letters) {` loop again.

When applicable, try out nested loops in your own applications!