Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’ll explore ways to create an infinite loop in Java.

Simply put, an infinite loop is an instruction sequence that loops endlessly when a terminating condition isn’t met. Creating an infinite loop might be a programming error, but may also be intentional based on the application behavior.

2. Using while

Let’s start with the while loop. Here we’ll use the boolean literal true to write the while loop condition:

public void infiniteLoopUsingWhile() {
    while (true) {
        // do something
    }
}

3. Using for

Now, let’s use the for loop to create an infinite loop:

public void infiniteLoopUsingFor() {
    for (;;) {
        // do something
    }
}

4. Using do-while

An infinite loop can also be created using the less common do-while loop in Java. Here the looping condition is evaluated after the first execution:

public void infiniteLoopUsingDoWhile() {
    do {
        // do something
    } while (true);
}

5. Conclusion

Even though in most of the cases we’ll avoid creating infinite loops but there could be some cases where we need to create one. In such scenarios, the loop will terminate when the application exits.

The above code samples are available in the GitHub repository.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!