Java: Infinite Loop Convention [closed]

2019-01-11 12:39发布

What is the convention for an infinite loop in Java? Should I write while(true) or for(;;)? I personally would use while(true) because I use while loops less often.

5条回答
▲ chillily
2楼-- · 2019-01-11 12:49

for(;;) sucks, it is completely unintuitive to read for rookies. Please use while(true) instead.

查看更多
欢心
3楼-- · 2019-01-11 13:02

It's up to you. I don't think there is a convention for such a thing. You can either use while(true) or for(;;)

I would say I encounter more often while(true) in the source codes. for(;;) is less often used and harder to read.

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-11 13:03

There is no difference in bytecode between while(true) and for(;;) but I prefer while(true) since it is less confusing (especially for someone new to Java).

You can check it with this code example

void test1(){
    for (;;){
        System.out.println("hello");
    }
}
void test2(){
    while(true){
        System.out.println("world");
    }
}

When you use command javap -c ClassWithThoseMethods you will get

  void test1();
    Code:
       0: getstatic     #15                 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #21                 // String hello
       5: invokevirtual #23                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: goto          0

  void test2();
    Code:
       0: getstatic     #15                 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #31                 // String world
       5: invokevirtual #23                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: goto          0

which shows same structure (except "hello" vs "world" strings) .

查看更多
倾城 Initia
5楼-- · 2019-01-11 13:06

Ultimately, it is your choice. The following Java reference uses the for (;;) format: The for Statement.

However, while(true) is used more often in infinite loops in my experience.

查看更多
beautiful°
6楼-- · 2019-01-11 13:09

I prefer while(true), because I use while loops less often than for loops. For loops have better uses and while(true) is much cleaner and easy to read than for(;;)

查看更多
登录 后发表回答