for Loops

A for loop is used to repeat a statement until a condition is met. Although for loops frequently are used for simple iteration in which a statement is repeated a certain number of times, for loops can be used for just about any kind of loop.

The for loop in Java looks roughly like the following:

for (initialization; test; increment) {
    statement;
}

The start of the for loop has three parts:

  • initialization is an expression that initializes the start of the loop. If you have a loop index, this expression might declare and initialize it, such as int i = 0. Variables that you declare in this part of the for loop are local to the loop itself; they cease to exist after the loop is finished executing. You can initialize more than one variable ...

Get Sams Teach Yourself Java 2 in 21 Days, Second 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.