Java by Example: For

for is one of Java's looping constructs. Here are some basic types of for loops.

public class Main {
    public static void main(String[] args) {

The most basic type, with a single condition.

    for int i = 1; i <= 3; i++) {
        System.out.println(i);
    }

A classic initial/condition/after for loop.

    for int j = 7; j <= 9; j++) {
        System.out.println(j);
    }

for without a condition will loop indefinitely. You can break out of the loop to stop it.

    for ( ; ; ) {
        System.out.println("loop");
        break;
    }

You can also continue to the next iteration of the loop.

    for int n = 0; n <= 5; n++) {
        if (n % 2 == 0) {
            continue;
        }
        System.out.println(n);
    }
}
}
1
2
3
7
8
9
loop
1
3
5

We'll see some other for forms later when we look at enhanced for statements, and other data structures.

Next example: While.

t