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?
If the condition evaluates to True , then the loop will run the code within the loop's body and continue to run the code while the condition remains True . It will keep executing the desired set of code statements until that condition is no longer True .
This is the basic logic of the break statement:The while loop starts only if the condition evaluates to True . If a break statement is found at any point during the execution of the loop, the loop stops immediately.
while(false) means the condition is false which will end the loop. while(True) means the condition is True which will continue the loop.
The while() loop If the condition is false the body of the loop never executes at all.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With