Heart containing Coding Chica Java 101

Once or More! Java’s Do Statement

TIP: References Quick List

If you want a set of commands to run at least once, but possibly many times, then Java’s do statement may be the ticket.

    do {
        // Commands that should run at least once, possibly multiple times.
    } while (<booleanExpressionToContinueLooping>);

Example

I generally don’t find much use for a do statement. Mostly, I find that the test on whether or not to execute the 1st loop also needs to occur before the first loop, so I am more likely to use a while or for loop.

However, it is worth understanding how this statement works, if seen elsewhere in the code.

ResultSet resultSet = sqlStatement.executeQuery(query);
int count = 0;
// Only OK if we know that we are guaranteed to have at least one result - always.  This is generally not the case.
// This method may also throw an exception, for which the handling is not included in this example.
resultSet.next();
do {
    // Commands to process the current result from the query
    count++;
    System.out.println("Row count: " + count);
} while (resultSet.next());

Continue – Onward

Similar to the for loop and the while loop, the continue statement is also supported by the do loop, if we only want to skip a single loop, but proceed on with loop processing after that.

Break – Full Stop

If we want to prematurely stop processing the remainder of the loop (this pass and all of those that may come after), the break statement is also supported for the do statement.

Once or More! Java’s Do Statement

Leave a comment

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