What is an infinite loop?

Welcome to Java MCQ (Mulitple Choice Question) series. In this post, we will see one more quiz question on Java Loops.

What is an infinite loop? 

a) A loop that executes only once
b) A loop that never terminates naturally
c) A loop that contains an unreachable code block
d) A loop that uses the continue statement 

Answer:

b) A loop that never terminates naturally 

Explanation:

An infinite loop in programming refers to a loop where the terminating condition is never satisfied or if there's no terminating condition at all. As a result, the loop continues to execute indefinitely. Infinite loops are often caused by programming errors, but they can also be used intentionally, depending on the program's needs. 

Here is an example of an infinite loop in Java:
while(true) {
    System.out.println("This is an infinite loop!");
}
In this example, true is a constant condition that will always be true, so the loop will continue to execute indefinitely, printing "This is an infinite loop!" repeatedly. 

Be aware that an infinite loop can cause a program to become unresponsive or use a significant amount of CPU resources, and it usually needs to be terminated manually.


Comments