Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What condition does while(true) test? When is it true and false?

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?

like image 312
Gregg1989 Avatar asked Mar 19 '14 16:03

Gregg1989


People also ask

What is a true condition in a while loop?

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 .

Does a while loop occur if the condition is true or false?

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.

How do you use true and false in a while loop?

while(false) means the condition is false which will end the loop. while(True) means the condition is True which will continue the loop.

What happens when the condition is false in while loop?

The while() loop If the condition is false the body of the loop never executes at all.


1 Answers

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.

like image 52
Michael Berry Avatar answered Nov 15 '22 19:11

Michael Berry