Why Java’s for(;;) Loop Is Equivalent to while(true) and How the Compiler Treats Both Forms
The article explains that Java’s for(;;) infinite loop and while(true) are historically inherited from C, produce identical bytecode under javac, and their performance depends on the JVM implementation rather than the source syntax.
The author greets readers and shows a quick search in the JDK8u source tree that finds 369 occurrences of a C‑style for‑loop pattern and 323 occurrences of a while‑true pattern, concluding that the difference in usage frequency is minimal.
He then discusses the origin of for (;;) in Java, tracing it back to C where developers accustomed to that syntax carried the habit into Java, often via mentors who previously wrote C.
In C, without a built‑in Boolean type, an infinite loop is commonly written as while(1) { /* ... */ } , but many programmers dislike the literal 1 and prefer the clearer for (;;) which expresses “no condition” directly.
The author notes his personal preference for while (true) in Java but acknowledges that for (;;) is equally acceptable in projects.
Regarding efficiency, he states that the Java language specification does not dictate performance; the actual speed depends on the JVM implementation, which must preserve semantics but may optimize differently.
He then presents the bytecode generated by javac for two equivalent methods—one using while (true) and the other using for (;;) . Both compile to identical bytecode, showing that the compiler performs only minimal constant folding and no substantial optimization at this stage.
public void foo() {
int i = 0;
while (true) { i++; }
}
/* bytecode */
stack=1, locals=2, args_size=1
0: iconst_0
1: istore_1
2: iinc 1, 1
5: goto 2
*/ public void bar() {
int i = 0;
for (;;) { i++; }
}
/* bytecode */
stack=1, locals=2, args_size=1
0: iconst_0
1: istore_1
2: iinc 1, 1
5: goto 2
*/Since both snippets produce the same bytecode, any performance differences would only arise later during interpretation or JIT compilation, where the input bytecode is identical.
The article concludes that, for practical purposes, for (;;) and while (true) are interchangeable in Java, and the choice is a matter of coding style rather than efficiency.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.