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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
for(;;)
sucks, it is completely unintuitive to read for rookies. Please usewhile(true)
instead.It's up to you. I don't think there is a convention for such a thing. You can either use
while(true)
orfor(;;)
I would say I encounter more often
while(true)
in the source codes.for(;;)
is less often used and harder to read.There is no difference in bytecode between
while(true)
andfor(;;)
but I preferwhile(true)
since it is less confusing (especially for someone new to Java).You can check it with this code example
When you use command
javap -c ClassWithThoseMethods
you will getwhich shows same structure (except "hello" vs "world" strings) .
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.I prefer
while(true)
, because I use while loops less often than for loops. For loops have better uses andwhile(true)
is much cleaner and easy to read thanfor(;;)