What is the convention for an infinite loop in Java? Should I write while(true)
or for(;;)
? I personally would use while(true)
because I use while loops less often.
5 Answers
There is no difference in bytecode between while(true)
and for(;;)
but I prefer while(true)
since it is less confusing (especially for someone new to Java).
You can check it with this code example
void test1(){
for (;;){
System.out.println("hello");
}
}
void test2(){
while(true){
System.out.println("world");
}
}
When you use command javap -c ClassWithThoseMethods
you will get
void test1();
Code:
0: getstatic #15 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #21 // String hello
5: invokevirtual #23 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: goto 0
void test2();
Code:
0: getstatic #15 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #31 // String world
5: invokevirtual #23 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: goto 0
which shows same structure (except "hello" vs "world" strings) .
-
2I think it's time for Java to come up with an infinite loop construction so we don't need workarounds, like other languages have. May I suggest
do {}
withoutwhile
being required, or simplyloop {}
. Nov 4, 2015 at 18:55 -
@OliverHausler I'd prefer
forever
, like e.g. in Scratch wiki.scratch.mit.edu/wiki/Forever_%28block%29 Apr 28, 2016 at 10:37
I prefer while(true)
, because I use while loops less often than for loops. For loops have better uses and while(true)
is much cleaner and easy to read than for(;;)
-
1Another argument in favor of while( true ) is maintainability: true may become a logic condition in the future– AubinApr 13, 2013 at 15:52
-
5
-
3@Aubin, so can the middle part of the
for
! Just stick it in likefor(; condition(););
. Using afor
also means you could easily add a variable to count iterations of the loop (or other 'between iterations' stuff) after the second of the two semicola. Nov 11, 2013 at 21:39 -
1There's nothing "hard to read" about
for...
its a three letter word. Oct 20, 2014 at 0:34
It's up to you. I don't think there is a convention for such a thing. You can either use while(true)
or for(;;)
I would say I encounter more often while(true)
in the source codes. for(;;)
is less often used and harder to read.
-
1Another argument in favor of while( true ) is maintainability: true may become a logic condition in the future– AubinApr 13, 2013 at 15:50
-
There's nothing "hard to read" about
for...
its a three letter word. Oct 20, 2014 at 0:35
for(;;)
sucks, it is completely unintuitive to read for rookies. Please use while(true)
instead.
while(running)
, so I have a way out of it.