For in Minitab
The for
loop is Java’s primary looping construct. Here are some basic types of for
loops.
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);
}
// To accomplish the basic "do this N times" iteration,
// we can use a traditional for loop.
for (int k = 0; k < 3; k++) {
System.out.println("range " + k);
}
// An infinite loop will run repeatedly until you break
// out of the loop or return from the enclosing method.
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);
}
}
}
When you run this program, you’ll see:
$ javac ForLoops.java
$ java ForLoops
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
In Java, we use while
loops for the most basic type of loop with a single condition. The classic for
loop syntax is similar to many other languages. Java doesn’t have a built-in range
function like some other languages, so we use traditional for
loops to achieve similar functionality.
The infinite loop in Java is typically written as while (true)
, and you can use break
to exit the loop or return
to exit the method.
The continue
statement works the same way in Java as in many other languages, allowing you to skip to the next iteration of the loop.
We’ll see other forms of iteration later when we look at enhanced for
loops (for-each loops), which are useful for iterating over collections and arrays.