Why Java’s for(;;) Loop Exists and Its Bytecode Equivalence to while(true)
The article explains the origin of Java’s for(;;) infinite loop syntax, compares it with while(true) through source‑code searches and bytecode analysis, and concludes that both constructs compile to identical bytecode, making performance differences negligible while also providing related promotional links.
Hello, I am a senior architect.
First, I performed a quick search in the JDK 8u source tree for the patterns "for ( ; ; )" and "while (true)" and found 369 and 323 occurrences respectively, showing only a small difference.
The for(;;) syntax in Java is inherited from C; developers who used C or were taught by C‑experienced mentors tend to adopt it, even if they no longer write C themselves.
In C, without including certain headers, a typical infinite loop without a magic number looks like:
while (1) {
/* ... */
}Using for(;;) expresses an infinite loop without any magic number, making the intent clear and avoiding the literal 1.
In Java, many prefer while(true), but for(;;) is equally acceptable in projects.
Examining the bytecode generated by javac for two methods—one using while(true) and the other using for(;;)—shows they produce identical bytecode:
public void foo() {
int i = 0;
while (true) { i++; }
}
/*
public void foo();
Code:
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++; }
}
/*
public void bar();
Code:
stack=1, locals=2, args_size=1
0: iconst_0
1: istore_1
2: iinc 1, 1
5: goto 2
*/Since javac performs minimal optimizations, both versions compile to the same bytecode; any performance differences would depend on later stages like JIT compilation, which are outside the language specification.
The article also includes promotional links to open‑source projects, interview question collections, and a BAT interview question list.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.