Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Infinite Loop Convention [closed]

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.

like image 536
Justin Avatar asked Apr 13 '13 15:04

Justin


People also ask

How do you stop an infinite loop in java?

You can break any loop using break; . If your program is already listening for keyboard input, you just need to put that break command inside a conditional statement that checks for the desired input.

Which is an infinite loop java?

What is an Infinite Loop? An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.

How do you stop an infinite loop?

You can press Ctrl + C .

Can you get stuck in an infinite loop?

In multi-threaded programs some threads can be executing inside infinite loops without causing the entire program to be stuck in an infinite loop. If the main thread exits all threads of the process are forcefully stopped thus all execution ends and the process/program terminates.


2 Answers

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

like image 95
Pshemo Avatar answered Sep 22 '22 15:09

Pshemo


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(;;)

like image 38
06needhamt Avatar answered Sep 21 '22 15:09

06needhamt