For
On this page
for
Here’s the translation of the Go code example and explanation into Java, formatted in Markdown suitable for Hugo:
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);
}
// Java doesn't have a direct equivalent to Go's `range` over integers,
// but we can use a traditional for loop to achieve the same result.
for (int k = 0; k < 3; k++) {
System.out.println("range " + k);
}
// An infinite loop that will run until you break out of it 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);
}
}
}
for
loops are one of Java’s fundamental 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;
}
A classic initial/condition/after for
loop:
for (int j = 0; j < 3; j++) {
System.out.println(j);
}
Java doesn’t have a direct equivalent to Go’s range
over integers, but we can use a traditional for
loop to achieve the same result:
for (int k = 0; k < 3; k++) {
System.out.println("range " + k);
}
An infinite loop that will run until you break
out of it 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 the program:
$ javac ForLoops.java
$ java ForLoops
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
We’ll see other loop forms later when we look at enhanced for
loops (for-each loops), which are similar to Go’s range
statements for iterating over collections and arrays.