To create an indefinite loop in Java, you can use a while
loop with a condition that always evaluates to true
. Here is an example of an indefinite loop in Java:
while (true) { // Code to be executed repeatedly }
This loop will execute the code inside the loop body indefinitely, unless you include a statement inside the loop that breaks out of the loop or you terminate the program.
Here is an example of how you can use a while
loop to read user input indefinitely:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (true) { System.out.print("Enter a number: "); int number = scanner.nextInt(); System.out.println("You entered: " + number); } } }
In this example, the loop will continue to read user input and print it to the console until the program is terminated.
You can also use a do-while
loop to create an indefinite loop in Java. A do-while
loop is similar to a while
loop, except that the loop body is executed at least once before the condition is checked. Here is an example of an indefinite do-while
loop:
do { // Code to be executed repeatedly } while (true);
It is generally a good idea to include a way to break out of an indefinite loop, such as a user input or a timer, to avoid running the loop indefinitely and potentially causing a crash or other issues.