Here’s the translation of the Go code example and explanation into Java, formatted in Markdown suitable for Hugo:
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:
A classic initial/condition/after for loop:
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:
An infinite loop that will run until you break out of it or return from the enclosing function:
You can also use continue to skip to the next iteration of the loop:
To run the program:
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.