For in Miranda

Java provides several ways to create loops. Here are some basic types of loops in Java.

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 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);
        }
    }
}

To run the program, compile and execute it:

$ javac ForLoops.java
$ java ForLoops
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Java provides different types of loops to suit various programming needs:

  1. The while loop is used when you want to repeat a block of code as long as a condition is true.

  2. The classic for loop is ideal when you know in advance how many times you want to iterate.

  3. Java doesn’t have a direct equivalent to Go’s range over an integer, but you can achieve similar functionality using a standard for loop.

  4. An infinite loop can be created using while(true), which will continue until a break statement is encountered or the method returns.

  5. The continue statement can be used to skip the rest of the current iteration and move to the next one.

Java also provides an enhanced for loop (also known as a “for-each” loop) for iterating over arrays and collections, which we’ll explore when we look at arrays and other data structures.