for Statement

A for statement creates loops in which a counter variable is automatically maintained. The for statement lets you set an initial value for the counter variable, the amount to be added to the counter variable on each execution of the loop, and the condition that’s evaluated to determine when the loop should end.

A for statement follows this basic format:

for (initialization-expression; test-expression; count-expression)

statement;

The three expressions in the parentheses following the keyword for control how the for loop works:

check.png The initialization-expression is executed before the loop begins. This expression initializes the counter variable. If you haven’t declared the counter variable before the for statement, you can declare it here.

check.png The test-expression is evaluated each time the loop is executed to determine whether the loop should keep looping. This expression tests the counter variable to make sure that it’s still less than or equal to the value you want to count to. The loop keeps executing as long as this expression evaluates to true. When the test expression evaluates to false, the loop ends.

check.png The count-expression is evaluated each time the loop executes. ...

Get Java For Dummies Quick Reference 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.