Backend Development 4 min read

Comparison of while(true) and for(;;) Infinite Loops in Java

This article examines the differences between while(true) and for(;;) infinite loops in Java, presenting equivalent code examples, compiling them to bytecode, and showing that both constructs compile to identical bytecode using a goto instruction, concluding there is no performance distinction.

IT Services Circle
IT Services Circle
IT Services Circle
Comparison of while(true) and for(;;) Infinite Loops in Java

This article analyzes the two common ways to write an infinite loop in Java— while(true) and for(;;) —and investigates whether there is any functional or performance difference between them.

Example using for(;;) :

public class HollisTest {
    public static void main(String[] args) {
        for(;;){
            System.out.println("this is hollis testing....");
        }
    }
}

Example using while(true) :

public class HollisTest {
    public static void main(String[] args) {
        while(true){
            System.out.println("this is hollis testing....");
        }
    }
}

Both files are compiled with the standard Java compiler:

javac HollisTest.java

The resulting .class files are then decompiled with javap , revealing that the bytecode for the two versions is identical. The key part of the bytecode shows a goto instruction that creates the infinite loop:

public class HollisTest {
    public HollisTest();
    public static void main(java.lang.String[]);
        Code:
            0: getstatic     #2 // Field java/lang/System.out:Ljava/io/PrintStream;
            3: ldc           #3 // String this is hollis testing....
            5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
            8: goto          0
}

The analysis demonstrates that both constructs compile to the same bytecode and therefore have no performance difference; the choice between them is purely stylistic, with some developers preferring while(true) for clarity and others preferring for(;;) to avoid IDE warnings.

backendJavaPerformancebytecodeforInfinite Loopwhile(true)
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

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.