Can a for loop be written in Java to create an infinite loop or is it only while loops that cause that problem?
You can also do such with for loops. E.g. the following is identical to while(true)
:
for(;;) {
}
Apart from issues of scope and one other thing, this:
for(<init>; <test>; <step>) {
<body>
}
is the same as:
<init>
while(<test>) {
<body>
<step>
}
As other people have alluded to, in the same way that you can have a while
loop without an <init>
form or <step>
form, you can have a for
loop without them:
while(<test>) {
<body>
}
is the same as
for(;<test>;) {
<body>
} //Although this is terrible style
And finally, you could have a
for(;true;) {
<body>
}
Now, remember when I said there was one other thing? It's that for
loops don't need a test--yielding the solution everyone else has posted:
for(;;) {
<body>
}
for(;;){}
is same as
while(true){}
Dont forget mistakes like
for (int i=0; i<30; i++)
{
//code
i--;
}
It's not as uncommon as it should be.
I'll just add this since nobody did this version:
for(;;);
Ofcourse for loops can cause infinite loops. An example is:
for(int i = 0; i < 99; i /= 2){ ... }
Because i
is never incremented, it will stay in the body of the for
loop forever until you quit the program.