What condition does while(true) test? When is it true and 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}

Here's a real world example. The while loop will iterate while the user input can't be parsed to an int. When the user input is parsed to int the loop exits by returning the number entered by the user.

private int getNumber(String message) {
    while (true) {  
        System.out.print(message);
        String userInput = scanner.nextLine();
        try {
            return Integer.parseInt(userInput);
        } catch (Exception ignored) {
            System.out.printf("%s isn't a number!%n", userInput);
        }
    }
}

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.