In Java, the for loop is one of several looping constructs. Here are some basic types of loops in Java.
The most basic type is a while loop with a single condition:
Java also has a classic initial/condition/after for loop:
To iterate over a range of numbers in Java, you can use a standard for loop:
For an infinite loop in Java, you can use while(true). This will loop repeatedly until you break out of the loop or return from the enclosing function:
You can also use continue to skip to the next iteration of the loop:
To run this program, save it as ForLoops.java, compile it with javac ForLoops.java, and then run it with java ForLoops. The output will be:
Java also provides enhanced for loops (also known as for-each loops) for iterating over collections and arrays, which we’ll see when we look at those data structures.