Loops with No Body

In Java, the body associated with a for loop (or any other loop) can be empty. This is because a null statement is syntactically valid. Body-less loops are often useful. For example, the following program uses one to sum the numbers 1 through 5:

Image

Notice that the summation process is handled entirely within the for statement, and no body is needed. Pay special attention to the iteration expression:

Image

Don’t be intimidated by statements like this. They are common in professionally written Java programs and are easy to understand if ...

Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.