I do no understand why anybody would use
while(true) {
//do something
}
instead of
boolean condition = true;
while(condition == true) {
//do something
}
The latter is super easy to understand, whilst the former is not.
So, what condition does while(true) check? When is while(true) true, and when is it false?
When is while(true) true, and when is it false?
It's always true, it's never false.
Some people use while(true)
loops and then use break
to exit them when a certain condition is true, but it's generally quite sloppy practice and not recommended. Without the use of break
, return
, System.exit()
, or some other such mechanism, it will keep looping forever.
Though we never know when we encounter a situation where we need it. We can also have infinite for loop.
for(;;) {//Code here}
condition == true
is also going to return a boolean which is 'true'.So using that directly instead of all that.
while(true)
loop will of course always iterate. You've to manually break out of it using break
, or System.exit()
, or may be return
.
while(condition == true)
will be true while condition
is true
. You can make that false by setting condition = false
.
I would never ever use while(condition == true)
at least. Instead just use while (condition)
. That would suffice.
while(true) is always true. Loop statements are executed all the time. If you have to break the loop, we have to use break statement.
while(true)
is used to for infinite loops. They will loop forever because true
is ALWAYS true
They are generally used when you have to do something until a certain condition is met. You then exit with the break
statement
while(true) {
//attempt to satisfy some condition
if (satisfied) {
break;
}
}
- List item
while(True): statement if(condition): break This is only work in python In java you can write like that for same purpose
while(1==1) { Ststements... }
来源:https://stackoverflow.com/questions/22512830/what-condition-does-whiletrue-test-when-is-it-true-and-false