Java: for(;;) vs. while(true) Java: for(;;) vs. while(true) java java

Java: for(;;) vs. while(true)


Semantically, they're completely equivalent. It's a matter of taste, but I think while(true) looks cleaner, and is easier to read and understand at first glance. In Java neither of them causes compiler warnings.

At the bytecode level, it might depend on the compiler and the level of optimizations, but in principle the code emitted should be the same.

EDIT:

On my compiler, using the Bytecode Outline plugin,the bytecode for for(;;){} looks like this:

   L0    LINENUMBER 6 L0   FRAME SAME    GOTO L0

And the bytecode for while(true){} looks like this:

   L0    LINENUMBER 6 L0   FRAME SAME    GOTO L0

So yes, at least for me, they're identical.


It's up to you which one to use. Cause they are equals to compiler.

create file:

// first testpublic class Test {    public static void main(String[] args) {        while (true) {            System.out.println("Hi");        }    }}

compile:

javac -g:none Test.javarename Test.class Test1.class

create file:

// second testpublic class Test {    public static void main(String[] args) {        for (;;) {            System.out.println("Hi");        }    }}

compile:

javac -g:none Test.javamv Test.class Test2.class

compare:

diff -s Test1.class Test2.classFiles Test1.class and Test2.class are identical


It compiles down to the same byte code, and it is a matter of taste which construct you prefer.

I read a lot of source code from the Oracle distributed JDK, and I cannot easily remember that I've seen a while(true) statement in their code, but I have seen a whole lot of for(;;) statements in their code. Me personally, I favor for(;;) and my reasoning goes a bit like this:

The while-loop "should" require a boolean expression, not a boolean constant. while(true) is a bit like if(true), both of which I think has been made legal only for the added comfort of the masses. An empty while() does not compile. Adding the true in there feels a bit like hacking.

for(;;) on the other hand is a "real loop", albeit an empty one. Also, it saves you a couple of keystrokes! =) (not that it matter)

Therefore, and I know it sounds crazy, but although while(true) reads better in English, I think for(;;) better express your intent and is more akin to the Java programming language. Eternal loops should be avoided anyways. When I read for(;;), I feel secure knowing the developer will brake the execution path somewhere. When I read while(true), I just cannot be that sure anymore. But hey, maybe that's just me! We're all free to pick our own flavor.