Java: for(;;) vs. while(true)

后端 未结 9 1944
予麋鹿
予麋鹿 2020-12-01 15:29

What is the difference between a standard while(true) loop and for(;;)?

Is there any, or will both be mapped to the same bytecode after com

9条回答
  •  臣服心动
    2020-12-01 16:10

    It's up to you which one to use. Cause they are equals to compiler.

    create file:

    // first test
    public class Test {
        public static void main(String[] args) {
            while (true) {
                System.out.println("Hi");
            }
        }
    }
    

    compile:

    javac -g:none Test.java
    rename Test.class Test1.class
    

    create file:

    // second test
    public class Test {
        public static void main(String[] args) {
            for (;;) {
                System.out.println("Hi");
            }
        }
    }
    

    compile:

    javac -g:none Test.java
    mv Test.class Test2.class
    

    compare:

    diff -s Test1.class Test2.class
    Files Test1.class and Test2.class are identical
    

提交回复
热议问题