Loops in Java

Loops are used to execute a block of code multiple times. In this tutorial, you’ll learn about for loops, while loops, and do-while loops.

For Loops

The for loop is used when you know in advance how many times the script should run:


public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println(i);
        }
    }
}
      

While Loops

The while loop is used when you want the loop to execute as long as a condition is true:


public class Main {
    public static void main(String[] args) {
        int i = 0;
        while (i < 5) {
            System.out.println(i);
            i++;
        }
    }
}
      

Do-While Loops

The do-while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true:


public class Main {
    public static void main(String[] args) {
        int i = 0;
        do {
            System.out.println(i);
            i++;
        } while (i < 5);
    }
}
      

Nesting Loops

You can nest loops by placing one loop inside the body of another:


public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.println("i: " + i + ", j: " + j);
            }
        }
    }
}
      

Continue exploring our beginner tutorials to learn more about Java programming.

Scroll to Top