How to Use a for Statement in Java - dummies

How to Use a for Statement in Java

By Doug Lowe

A for statement in Java 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:

  • 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.

  • 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.

  • The count-expression is evaluated each time the loop executes. Its job is to increment the counter variable.

Here’s a simple for loop that displays the numbers 1 to 10 on the console:

for (int i = 1; i <= 10; i++)
    System.out.print(i + " ");

Run this code, and you’ll see the following on the console:

1 2 3 4 5 6 7 8 9 10

If you declare the counter variable in the initialization statement (as in the previous example), the scope of the counter variable is limited to the for statement itself. Thus, you can use the variable in the other expressions that appear within the parentheses and in the body of the loop, but you can’t use it outside the loop,

If you want, you can declare the counter variable outside the for loop. Then, you can use the counter variable after the loop finishes. For example:

int i;
for (i = 1; i <=10; i++)
   System.out.print(I + " ");
System.out.println("The final value is " + i);

You can exit out of the middle of a loop by using a break statement. You can also use a continue statement to skip an execution of the loop.