For in Fortress
public class ForLoops {
public static void main(String[] args) {
// The most basic type, with a single condition.
int i = 1;
while (i <= 3) {
System.out.println(i);
i = i + 1;
}
// A classic initial/condition/after for loop.
for (int j = 0; j < 3; j++) {
System.out.println(j);
}
// Another way of accomplishing the basic "do this
// N times" iteration is using a for loop with a range.
for (int k = 0; k < 3; k++) {
System.out.println("range " + k);
}
// A while(true) loop will run repeatedly
// until you break out of the loop or return from
// the enclosing function.
while (true) {
System.out.println("loop");
break;
}
// You can also continue to the next iteration of
// the loop.
for (int n = 0; n < 6; n++) {
if (n % 2 == 0) {
continue;
}
System.out.println(n);
}
}
}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:
int i = 1;
while (i <= 3) {
System.out.println(i);
i = i + 1;
}Java also has a classic initial/condition/after for loop:
for (int j = 0; j < 3; j++) {
System.out.println(j);
}To iterate over a range of numbers in Java, you can use a standard for loop:
for (int k = 0; k < 3; k++) {
System.out.println("range " + k);
}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:
while (true) {
System.out.println("loop");
break;
}You can also use continue to skip to the next iteration of the loop:
for (int n = 0; n < 6; n++) {
if (n % 2 == 0) {
continue;
}
System.out.println(n);
}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:
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5Java 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.