Heart containing Coding Chica Java 101

Many Times or Not at All! Java’s While Statement

TIP: References Quick List

Another loop format that Java supports is the while statement. As the placement suggests, the booleanExpression to determine whether to execute the loop’s commands is run at the beginning, before each loop’s logic is executed. This may be helpful if even the first time through the loop we may need to skip the loop’s commands. A while loop’s logic is executed zero or more times.

    while (<booleanExpression>) {
        // Commands to perform in the loop
    }

Example

When processing the results of a JDBC query, we won’t know whether any results are returned from the query. Therefore, we may not want to execute the commands within the loop, not even one time. If we use a while loop, we can check to see if there are any more results to process at the beginning of each loop.

ResultSet resultSet = sqlStatement.executeQuery(query);
int count = 0;
while (resultSet.next()) {
    // Commands to process the current result from the query
    count++;
    System.out.println("Row count: " + count);
}

Continue – Onward

Just like in the for loop, the while loop supports the continue statement. This allows us to skip processing a single element / row, but still process the remainder of the rows / results / elements.

Break – Full Stop

Similar to the for loop, the while loop also supports the break statement. When this statement is encountered, the remainder of the elements / rows / results will not be processed. All remaining looping logic will be skipped and the application’s logic will resume after the end of the loop’s definition.

Many Times or Not at All! Java’s While Statement

Leave a comment

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