Java Loops: for, while, do…while

The next step after working with conditional statements is to handle loops. Like JavaScript, Java supports a for loop, a while loop, and a do…while loop.

Here's how you use a Java for loop in general; note that the statement that makes up the body of the for loop can be a compound statement—it can be made up of several single statements enclosed in curly braces:

for (initialization_expression; test_condition; iteration_expression) {
    statement
}

You place an expression in the initialization part of the for loop (which often initializes a variable—that is, a loop index—to 0), and then you place a test condition in the test part of the loop to be tested each time the code in the loop has been executed. If the test ...

Get Inside XML 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.