Fundamentals 4 min read

Why Does Java’s for(;;) Loop Exist and Is It Faster Than while(true)?

An exploration of Java’s infinite loop constructs reveals that for(;;) originates from C, offers a concise syntax without magic numbers, and, according to bytecode analysis of JDK8u, performs identically to while(true), with performance determined solely by the JVM implementation.

Programmer DD
Programmer DD
Programmer DD
Why Does Java’s for(;;) Loop Exist and Is It Faster Than while(true)?

Searching the JDK8u source tree shows roughly the same number of infinite loops written as for(;;) and while(true) (369 vs 323 occurrences).

The for(;;) syntax in Java traces back to C, where developers used it to avoid writing a literal constant such as while(1). It provides a clear way to express an infinite loop without a “magic number”.

In C, without including certain headers, there is no built‑in bool type, so while(1) was common, but many preferred for(;;) for readability.

In Java the author prefers while(true), though for(;;) is also acceptable.

Which is faster in Java, for(;;) or while(true) ?

The Java language specification does not dictate performance; it depends on the implementation. Compiling both versions with javac (Oracle/Sun JDK8u / OpenJDK8u) yields identical bytecode, as shown below.

public void foo() {
    int i = 0;
    while (true) { i++; }
}

/* Bytecode:
   0: iconst_0
   1: istore_1
   2: iinc 1, 1
   5: goto 2
*/
public void bar() {
    int i = 0;
    for (;;) { i++; }
}

/* Bytecode:
   0: iconst_0
   1: istore_1
   2: iinc 1, 1
   5: goto 2
*/

Since the generated bytecode is identical, any performance difference would only arise later during interpretation or JIT compilation, where the input is the same, so the output is effectively identical.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavabytecodeLoopsforlanguage fundamentalswhile true
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.