For Loops in Java

This is the reference section for for-loops as they are used in the Java programming language. The general for loop statement consists of three basic parts: initialization, conditional, and update. Additionally, Java includes a for loop that is specifically used to iterate through the entries of an array; this version is sometimes called a for-each loop.

 

Example 1

// A simple for loop with initialization, conditional, and update.
// This code outputs the integers 0 through 9.
for (int iJ = 0; iJ < 10; ++iJ) {
    System.out.println(iJ);
}

Example 2

// A for loop without the initialization step.
// This code outputs the integers 0 through 9.
// It demonstrates that the initialization does not need to happen inside the for.
int iJ = 0;
for (; iJ < 10; ++iJ) {
    System.out.println(iJ);
}

Example 3

// A for loop without the initialization and a different conditional.
// This code outputs the integers 0 through 9.
// It demonstrates the versatility of the conditional.
boolean bDone = false;
int iJ = 0;
for (; !bDone; ++iJ) {
    System.out.println(iJ);
    if (iJ >= 9) {
        bDone = true;
    }
}

Example 4

// A for loop with only a conditional.
// This code outputs the integers 0 through 9.
// It is equivalent to a while loop.
boolean bDone = false;
int iJ = 0;
for (; !bDone;) {
    System.out.println(iJ);
    if (iJ >= 9) {
        bDone = true;
    }
    ++iJ;
}

Example 5

// An empty for loop.
// This code outputs the integers 0 through 9.
// Without the break statement, this would be an infinite loop.
int iJ = 0;
for (;;) {
    System.out.println(iJ);
    if (iJ >= 9) {
        break;
    }
    ++iJ;
}

Example 6

// A for loop with only an initialization.
// This code outputs the integers 0 through 9.
// This is strange, but demonstrates the versatility of the for loop.
for (int iJ = 0; ;) {
    System.out.println(iJ);
    if (iJ >= 9) {
        break;
    }
    ++iJ;
}

Example 7

// This is a "for each" loop that runs through the elements of an array.
// This code outputs the integers 0 through 9.
// Notice the syntax. iJ is set equal to each entry in the array.
int iArray[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int iJ : iArray) {
    System.out.println(iJ);
}