Write one or two examples of an infinite loop.
Exercise – Infinite loop
Answer
Here is one possible infinite loop implementation:
while(true){
System.out.println("try and stop me"); //prints indefinitely
}
The following is another one:
for (;;){
System.out.println("try and stop me"); //prints indefinitely
}
And this one is an infinite loop, too:
for (int x=2; x > 0; x--){
System.out.println(x++ + " "); //prints 2 indefinitely
}
In this code, the Boolean expression x > 0 is always evaluated to true because x is initialized to 2 and then incremented and decremented by 1 in each iteration.