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.

Answer from Michael Berry on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_while_loop.asp
Java While Loop
Loops can execute a block of code as long as a specified condition is true. Loops are handy because they save time, reduce errors, and they make code more readable. The while loop repeats a block of code as long as the specified condition is true:
🌐
Oracle
docs.oracle.com › javase › tutorial › java › nutsandbolts › while.html
The while and do-while Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)
You can implement an infinite loop using the while statement as follows: while (true){ // your code goes here } The Java programming language also provides a do-while statement, which can be expressed as follows: do { statement(s) } while (expression); The difference between do-while and while ...
🌐
DataCamp
datacamp.com › doc › java › java-while-loop
Java While Loop
This example demonstrates an infinite while loop, where the condition is always true. The break statement is used here to exit the loop, preventing it from running indefinitely. import java.util.Scanner; public class InputValidationExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number; System.out.println("Enter a number between 1 and 10:"); number = scanner.nextInt(); while (number < 1 || number > 10) { System.out.println("Invalid input.
Top answer
1 of 16
231

I wouldn't say it's bad - but equally I would normally at least look for an alternative.

In situations where it's the first thing I write, I almost always at least try to refactor it into something clearer. Sometimes it can't be helped (or the alternative is to have a bool variable which does nothing meaningful except indicate the end of the loop, less clearly than a break statement) but it's worth at least trying.

As an example of where it's clearer to use break than a flag, consider:

while (true)
{
    doStuffNeededAtStartOfLoop();
    int input = getSomeInput();
    if (testCondition(input))
    {
        break;
    }
    actOnInput(input);
}

Now let's force it to use a flag:

boolean running = true;
while (running)
{
    doStuffNeededAtStartOfLoop();
    int input = getSomeInput();
    if (testCondition(input))
    {
        running = false;
    }
    else
    {
        actOnInput(input);
    }
}

I view the latter as more complicated to read: it's got an extra else block, the actOnInput is more indented, and if you're trying to work out what happens when testCondition returns true, you need to look carefully through the rest of the block to check that there isn't something after the else block which would occur whether running has been set to false or not.

The break statement communicates the intent more clearly, and lets the rest of the block get on with what it needs to do without worrying about earlier conditions.

Note that this is exactly the same sort of argument that people have about multiple return statements in a method. For example, if I can work out the result of a method within the first few lines (e.g. because some input is null, or empty, or zero) I find it clearer to return that answer directly than to have a variable to store the result, then a whole block of other code, and finally a return statement.

2 of 16
103

AFAIK nothing, really. Teachers are just allergic to goto, because they heard somewhere it's really bad. Otherwise you would just write:

bool guard = true;
do
{
   getInput();
   if (something)
     guard = false;
} while (guard)

Which is almost the same thing.

Maybe this is cleaner (because all the looping info is contained at the top of the block):

for (bool endLoop = false; !endLoop;)
{

}
🌐
Tutorialspoint
tutorialspoint.com › java › java_while_loop.htm
Java - while Loop
Java while loop statement repeatedly executes a code block as long as a given condition is true. The while loop is an entry control loop, where conditions are checked before executing the loop's body.
🌐
DataCamp
datacamp.com › doc › java › while
while Keyword in Java: Usage & Examples
The while keyword in Java is used to create a loop that executes a block of code as long as a specified condition is true.
Find elsewhere
🌐
Coderanch
coderanch.com › t › 592208 › java › Meaning-true
Meaning of while (true) (Beginning Java forum at Coderanch)
September 11, 2012 - "while (true)" is a kludgy way of saying that the test that exits the loop is either going to be made within the loop (via a "break" statement, return, Exception, or whatever) or if all else fails, because the application is forcibly cancelled either from the OS or actually pulling the plug ...
🌐
BeginnersBook
beginnersbook.com › 2015 › 03 › while-loop-in-java-with-examples
While loop in Java with examples
First of all….. The initialization done with i=0 Then goto while loop and check the condition i<4(i=0) It is true goto the loop body execute the looping statement i.e., args[0] Then increment the i value by 1 After incrementing again check the while loop condition …….
🌐
Sololearn
sololearn.com › en › Discuss › 898551 › what-does-this-actually-mean-while-true-in-while-loop
What does this actually mean "while True:" in while loop? | Sololearn: Learn to code for FREE!
December 3, 2017 - I probably have you more than you asked for - hope this helped in any case. 😉 ... basically it's saying that the code in that loop is to be executed as long as the condition evaluates to true.
🌐
HWS
math.hws.edu › eck › cs124 › javanotes6 › c3 › s3.html
Javanotes 6.0, Section 3.3 -- The while and do..while Statements
It's called the break statement, which takes the form ... When the computer executes a break statement in a loop, it will immediately jump out of the loop. It then continues on to whatever follows the loop in the program. Consider for example: while (true) { // looks like it will run forever!
🌐
Jenkov
jenkov.com › tutorials › java › while.html
Java while Loops
May 9, 2024 - The Java while loop is similar to the for loop. The while loop enables your Java program to repeat a set of operations while a certain conditions is true.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-do-while-loop
Java do while loop | DigitalOcean
August 3, 2022 - Java do-while loop is used to execute a block of statements continuously until the given condition is true.
🌐
W3Schools
w3schools.com › java › java_while_loop_do.asp
Java Do/While Loop
Java Examples Java Videos Java ... Java Study Plan Java Interview Q&A Java Certificate ... The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true....
🌐
Reddit
reddit.com › r/learnprogramming › [java]how does the `while(true)` loop work?
r/learnprogramming on Reddit: [java]How does the `while(true)` loop work?
October 22, 2015 - ... One instance of this being used would be a program that monitors a network. As long as the program is running, it wants to do the same thing over and over. The while(true) ensures the program will never end unless closed by the user.
🌐
iO Flood
ioflood.com › blog › while-loop-java
While Loop Java: The Basics and Beyond
February 20, 2024 - An infinite loop occurs when the condition in your while loop never becomes false. This causes the loop to run indefinitely, which can cause your program to become unresponsive. Here’s an example of an infinite loop: while(true) { ...
🌐
CodingNomads
codingnomads.com › what-is-while-loop-java
What is the While Loop in Java? Java While Loop Syntax.
A while loop will only execute its code if the condition evaluates to true at least once
🌐
Coderanch
coderanch.com › t › 593730 › java › true-loop-threads
Is using While(true) loop better way to keep threads on? (Threads forum at Coderanch)
Still i got an idea that while(true) is not bad practice here It's fine, as long as you're doing actual processing in the loop. If you're just using it as a delay, that's wrong. ... Azrael Noor wrote: No, don't do that. Only sleep if you actually want the thread to pause for a fixed amount of time. If you're waiting for some other event in the system, use wait() or join() or the higher level tools in java.util.concurrent.
🌐
Sololearn
sololearn.com › en › Discuss › 64971 › what-is-use-of-while-false-whiletrue-and-how-to-use-it
What is use of while (false) while(true) and how to use it? | Sololearn: Learn to code for FREE!
while loops use only Boolean expression and when it is true. So when it gets true it'll execute until it gets false. while(false) means the condition is false which will end the loop.