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:
🌐
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;)
{

}
🌐
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 ...
🌐
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 ...
🌐
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.
Find elsewhere
🌐
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.
🌐
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 …….
🌐
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.
🌐
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!
🌐
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 - If you have an infinite loop, you must (or should) have a break statement. Like so: while True: a += 1 This code will execute forever, adding 1 to a to infinity. Well, that's no good!
🌐
iO Flood
ioflood.com › blog › while-loop-java
While Loop Java: The Basics and Beyond
September 29, 2016 - 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) { ...
🌐
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 -

I'm taking my first programming course. It's an accelerated Java class so we are skipping through stuff pretty quickly. Basically just getting exposed to one topic then moving to the next.

I've been keeping up fairly well, but encountered something in today's reading that has me stumped. It's this while(true) loop. I can't figure out how it is working.

while (true) {
    Socket socket = serverSocket.accept(); // Connect to a client 
    Thread thread = new ThreadClass(socket);
    thread.start();
}

We are discussing networking and the above loop is supposed to open a new thread for each connection.

How does it work? The while loop runs while true. While what's true? What makes it go false? I don't understand how this is working because every other while loop we have done has checked some condition.

...but while(true) ??? What's the condition that 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....
🌐
Quora
quora.com › Is-there-anything-bad-about-using-a-while-true-loop-and-exiting-it-using-a-break-statement
Is there anything bad about using a while (true) loop and exiting it using a break statement? - Quora
A loop statement is used to execute a set of statements continuously as long as a given condition is true. Now different languages have different syntax but here is an example in Java.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-while-loop-with-examples
Java while Loop - GeeksforGeeks
Control enters the while loop. The condition is tested. If true, execute the body of the loop. If false, exit the loop. After executing the body, update the loop variable. Repeat from step-2 until the condition is false.
Published   1 week ago
🌐
IONOS
ionos.com › digital guide › websites › web development › while-loop java
How to use the while-loop in Java - IONOS
September 26, 2022 - The while-loop provides Java users with the ability to execute any number of state­ments as long as a pre­vi­ous­ly defined condition is true.