Why Java’s for(;;) Loop Is Equivalent to while(true) and Its Compilation Details
This article explains the origin of Java’s for(;;) infinite loop syntax, compares it with while(true), shows how both compile to identical bytecode in JDK 8, and concludes that performance differences depend on the JVM implementation rather than the source construct.
The author introduces a quick search in the JDK 8u source tree that finds 369 occurrences of the pattern for (;;) , indicating its widespread use.
He traces the origin of for (;;) in Java to the C language, where an infinite loop is often written as while (1) { /* ... */ } . Because for (;;) expresses an empty condition directly in the loop header without any “magic number”, it became a common idiom.
In Java, developers sometimes prefer while (true) , but for (;;) is equally valid and more concise for an infinite loop.
To compare the two forms, the article shows the compiled bytecode produced by javac for the following methods (using JDK 8u):
public void foo() {
int i = 0;
while (true) { i++; }
} public void bar() {
int i = 0;
for (;;) { i++; }
}Both methods generate identical bytecode, e.g.:
0: iconst_0
1: istore_1
2: iinc 1, 1
5: goto 2The compiler performs only minimal optimizations (constant folding, etc.), so the two source forms result in the same bytecode. Consequently, any performance difference would arise later during interpretation or JIT compilation, not from the source construct itself.
The conclusion is that, according to the Java language specification, both loops are semantically equivalent, and their efficiency is determined by the JVM implementation rather than the choice between while (true) and for (;;) .
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.