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

21,483

Solution 1

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.

Solution 2

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

create file:

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

compile:

javac -g:none Test.java
rename Test.class Test1.class

create file:

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

compile:

javac -g:none Test.java
mv Test.class Test2.class

compare:

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

Solution 3

On Oracle Java 7 you get the same byte code. You cannot tell from the byte code which was using in the original. Which is best is a matter of taste. I use while(true)

Solution 4

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.

Solution 5

I have looked at the generated byte code and found that since the condition is always true (at compile time), the compiler will compile away the test and just branch always back to the top of the loop. I assume that a continue statement will also do a branch always back to the top of the loop. So, not only does it not make any difference, there isn't even any code generated to test anything.

Share:
21,483
sjas
Author by

sjas

If there’s PUT, there’s GET. If there’s ADD, there’s DELETE. If I put a string in, I get a string out. (Equals 'Only get a string if one was put in.') If I can generate a time string, I can parse a time string. If there’s an INSTALL, there’s an UNINSTALL. syntax cheatsheet emphasis strong emphasis both strikethrough keyboard input code fragment code block Quote block is written as: *emphasis* **strong emphasis** ***both*** <s>strikethrough</s> <kbd>keyboard input</kbd> `code fragment` code block > Quote block

Updated on July 05, 2022

Comments

  • sjas
    sjas almost 2 years

    What is the difference between a standard while(true) loop and for(;;)?

    Is there any, or will both be mapped to the same bytecode after compiling?

  • sjas
    sjas over 12 years
    Accepted this answer for having provided the code and how it was looked up. Thank you. :)
  • bestsss
    bestsss over 12 years
    for(;;) is the cleaner version, imo (also shorter :P)
  • T.E.D.
    T.E.D. over 10 years
    Note that in VS while(true) causes compilation warnings on the highest settings for C and C++ (C#?). Perhaps not an issue for Java, but if you write in other languages sometimes, for(;;) is a better habit to develop.
  • JacksOnF1re
    JacksOnF1re over 9 years
    Than you could write while(1==1), which is, in my opinion, the most clean way.
  • Ogen
    Ogen about 9 years
    In java source they tend to use for(;;), so I just follow what the pro's do :D
  • vedi0boy
    vedi0boy over 6 years
    I did a little test. Decompiling the classes in jd-gui shows for(;;) and NOT whilte (true) for both classes!
  • 4ndrew
    4ndrew over 6 years
    @vedi0boy at JVM level (and bytecode) — there is no difference, jd-gui selects the most easiest way to show this loop.
  • vedi0boy
    vedi0boy over 6 years
    @4ndrew of course I am aware of that, I was just curious how the decompiler sees it. It seems like while(true) is not "liked" as much.
  • man guy
    man guy over 5 years
    Sort of arcane knowledge, but they use for(;;){} in the datetime tutorial docs.oracle.com/javase/tutorial/datetime/iso/datetime.html
  • Maarten Bodewes
    Maarten Bodewes over 4 years
    private static final boolean NO_BREAK = true;. Unless you (also) use return of course :)
  • Default
    Default almost 4 years
    pronounce for(;;) as forever