Heart containing Coding Chica Java 101

And Again! For Loops in Java

TIP: References Quick List

In Java, we can use different styles of loops to perform similar actions upon collections of objects or just patterns for counters, etc.

For Loops

Similar to if-blocks, if you only have a single command to issue, you could do so without the curly braces ({}) that explicitly define the block of code. However, this is not recommended. Just like in the single-line if-statement, omitting the curly braces ({}) could lead to errors in the future as additional logic may be added.

For Loops – Basic

In a basic for loop, we initialize a variable, often a counter for an index, to track where we are in the loop and when it is time to end looping.

    for (<loopVariablenitialization>; <expressionCheckingForEndOfLoop>; <updateVariableCommandBetweenLoops>) {
        // Commands to perform on each loop
    }

For example, if we want to print all of elements in an array in a loop, we might create a for loop like the following:
int[] bookCounts = { 2, 5, 3, 1, };
for (int index = 0; index < bookCounts.length; index++) {
    System.out.println("Book Count " + index + ": " + bookCounts[index]);
}

We initialize the index (loop counter variable) to 0 to match the zero-based array indices. At the start of every loop, Java will check to make sure that index < bookCounts.length (the size of the array). At the end of every loop, the index variable will be incremented. Inside of the for loop, we have one statement that prints out some information about the elements in the array.

For Loops – Enhanced

In an enhanced for loop, we do not have an index variable, we only loop over the values inside of the collection/array. If we want a counter / index tracking variable, then we must declare it separately in order to produce similar output:

int[] bookCounts = { 2, 5, 3, 1, };
int index = 0;
for (int bookCount : bookCounts) {
    System.out.println("Book Count " + index + ": " + bookCount);
    index++;
}

In this style for loop, Java will iterate over the elements in the array / collection provided. We also need not specify the bookCounts element by index, as the variable bookCount is initialized with the current element value from the array.

Continue Onward

If one of the elements in the array doesn’t meet the conditions for processing, but we want to continue forward, processing the remainder of the array, we can use the continue keyword.

int[] bookCounts = { 2, -1, 5, 3, 1, };
int index = 0;
for (int bookCount : bookCounts) {
    if (bookCounts <= 0) {
        continue;
    }
    System.out.println("Book Count " + index + ": " + bookCount);
    index++;
}

In the example above, the elements with negative / zero books will not be printed. Those with at least one book with be printed.

Break – Full Stop

If we are looping over a collection trying to search for some value or other condition that, once satisfied, we need not proceed any further to know the answer to the question, then we can stop processing the rest of the loop once the answer has been found.

int[] bookCounts = { 2, -1, 5, 3, 1, };
boolean haveInvalidBookCounts = false;
for (int bookCount : bookCounts) {
    if (bookCounts <= 0) {
        haveInvalidBookCounts = true;
        break;
    }
}

Once we encounter the break command, the rest of the loop will not be processed. Instead, we will immediately exit the for loop and proceed on with any subsequent commands.

And Again! For Loops in Java

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.