Fundamentals 5 min read

Why Java’s for(;;) and while(true) Are Equivalent: A Deep Dive into Compilation and Performance

The article examines the origins and practical equivalence of Java’s infinite loop constructs for(;;) and while(true), showing through JDK8u source searches and javac bytecode that both compile to identical code and have no performance difference.

Architect's Tech Stack
Architect's Tech Stack
Architect's Tech Stack
Why Java’s for(;;) and while(true) Are Equivalent: A Deep Dive into Compilation and Performance

The author begins by questioning the "why ask why" series and performs a quick search in the JDK8u source tree, finding roughly the same number of occurrences for for (\s?;\s?;) (369) and while (true (323) patterns.

He explains that the for (;;) syntax originates from C, where developers accustomed to C’s style carried the habit into Java, often through mentors or prior experience.

In C, without including certain headers, there is no built‑in bool type, so infinite loops are commonly written as while (1) { /* ... */ } , though many dislike the magic number 1 . Using for (;;) makes the intent of an unconditional loop explicit without any magic constants.

In Java, the author personally prefers while (true) but acknowledges that for (;;) is also acceptable in projects.

Regarding efficiency, the Java Language Specification does not prescribe performance differences; the actual speed depends on the implementation. Examining the Oracle/Sun JDK8u (OpenJDK8u) compilation results, both the while (true) and for (;;) versions generate 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
*/

and

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 both snippets compile to the same bytecode, any performance difference would arise only later during interpretation or JIT compilation, where the input and output remain identical.

The article also includes a promotional note about a 7701‑page PDF of large‑tech‑company interview questions, but the core technical discussion focuses on the equivalence of these infinite loop constructs.

JavaperformanceCompilationJDK8loopsfor loopwhile loop
Architect's Tech Stack
Written by

Architect's Tech Stack

Java backend, microservices, distributed systems, containerized programming, and more.

0 followers
Reader feedback

How this landed with the community

login 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.