How is an infinite loop declared in Java?
In Java, an infinite loop can be declared using various looping constructs. The most common way to create an infinite loop is by using a while
loop or a for
loop. Here are examples of both:
while
loop:while (true) {
// Code to be executed repeatedly
}
for
loop:for (;;) {
// Code to be executed repeatedly
}
do-while
loop:do {
// Code to be executed repeatedly
} while (true);
In all these examples, the loop will continue to execute indefinitely because the condition for termination is never met (in the case of the while
and do-while
loops) or there is no condition specified (in the case of the for
loop).
When using infinite loops, it's crucial to ensure that there is a way to break out of the loop under certain conditions (e.g., using a break
statement) to avoid unintentional program hangs or excessive resource consumption.