In general, use break inside a while loop is considered a bad practice. You should have something like this

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int number;
    int minimum = 5;
    int maximum = 15;

    do{
        System.out.print("Enter a number between" + " " + minimum + " " + "and" + " " + maximum + ":" );
        number = input.nextInt();
        if (number < minimum || number > maximum) 
            System.out.print("Sorry, invalid");
    } while (number < minimum || number > maximum); 

}
Answer from alseether on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_while_loop_do.asp
Java Do/While Loop
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... The do/while loop is a variant of the while loop. This loop will execute ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-do-while-loop-with-examples
Java Do While Loop - GeeksforGeeks
The do block executes first and prints "Hello World", ensuring the loop runs at least once. After printing, c is incremented using c++. The loop continues as long as the condition c < 6 is true, resulting in the message being printed 5 times. ... import java.io.*; class GFG { public static void main(String[] args) { int c = 1; do { // Only single statement in do block System.out.println("Hello GFG!"); } // This condition is false, so the loop will execute only once while (c >= 3); } }
Published   3 weeks ago
Discussions

java - do-while and while comparison - Stack Overflow
I am learning about do-while vs ... above java fragment (already declared and initialized) using a while instead. Are the below rewritten codes correct way to do so: ... The difference is when the condition check occurs, of course. In a do-while, the body is always executed at least once. Otherwise, there really is nothing to say. ... while is an entry check loop, whereas do-while ... More on stackoverflow.com
🌐 stackoverflow.com
Java: When to use a While Loop?
Imagine you have a collection of 1,000,000 songs. You want to search for one song specifically, and return that song (or, if the song doesn't exist in the collection, tell you it wasn't found). A for or for-each loop could accomplish that, but it's going to loop 1,000,000 times even if the song is the very first record checked, which is a huge waste of time and power. If you write a while loop and then have it stop when a matching record is found, it runs exactly as much as is necessary and no more. Another example -- imagine a simple text-based console app that reads input from a user and then prints it out on the screen, but then closes when they type "quit". If you put the steps of your program - asking the user for input, assigning it to a variable, and then printing it out - in a for/for-each loop, how do you know how many times to run it? A while loop that stops running when the user types "quit" lets the user flexibly quit whenever they want, whether on 0 entries or 200. There's a lot of other applications but hopefully these are useful to conceptualize at least. More on reddit.com
🌐 r/learnprogramming
19
13
March 29, 2016
Loops in Java
Use them when you want to repeat work. Some rules of thumb: If you know how many iterations you want, e.g. looping over a range, use a for loop. If you don't know the above exactly, but you do know when you want to stop, use a while loop. If the above, but you want the loop body to run at least once before the check, use do...while. Practically they all just conditionally branch. You really only need one language construct (e.g. while) to do all branching and iteration, but languages provide if, for, while, do...while etc. More on reddit.com
🌐 r/learnprogramming
5
1
February 23, 2025
A very simple java do...while loop - Stack Overflow
I am learning JAVA and typed the following DO...WHILE example. The program will quit if I type 'q'. It runs but why I get three rows of "Please a key followed by ENTER:"? class DWDemo { public More on stackoverflow.com
🌐 stackoverflow.com
🌐
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)
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:
🌐
Tutorialspoint
tutorialspoint.com › java › java_do_while_loop.htm
Java - do...while Loop
Java do while loop is similar to a while loop, except that a do while loop is guaranteed to execute at least one time. The do-while loop is an exit control loop where the condition is checked after executing the loop's body.
Top answer
1 of 4
20

The difference between a do-while and a while is when the comparison is done. With a do-while, you'll compare at the end and hence do at least one iteration.

Equivalent code for your example

do
{ 
    i++; 
    ++j;
    System.out.println( i * j );

}
while ((i < 10) && (j*j != 25));

is equivalent to:

i++; 
++j;
System.out.println( i * j );
while ((i < 10) && (j*j != 25)) {
    i++; 
    ++j;
    System.out.println( i * j );
}

General comprehension

A do-while loop is an exit controlled loop which means that it exits at the end. A while loop is an entry controlled loop which means that the condition is tested at the beginning and as a consequence, the code inside the loop might not even be executed.

do {
    <block>
} while (<condition>);

is equivalent to:

<block>
while (<condition>) {
    <block>
};

Use case

A typical use case for a do-while is the following: you ask the user something and you want do repeat the operation while the input is not correct.

do {
   // Ask something
} while (input is not correct);

In that case, you want to ask at least once and it's usually more elegant than using a while which would require either to duplicate code, or to add an extra condition or setting an arbitrary value to force entering the loop the first time.

At the opposite, while loops are much more commons and can easily replace a do-while (not all languages have both loops).

2 of 4
3

The key difference between do-while and while, with do-while you are guaranteed at least one run of your code before the checks.

*It does not need to get anymore complicated than that.

Find elsewhere
🌐
Reddit
reddit.com › r/learnprogramming › java: when to use a while loop?
r/learnprogramming on Reddit: Java: When to use a While Loop?
March 29, 2016 -

My Intro to programming class has covered how to use both for and while loops. As for the code I am good to go with it but I am having a little trouble understanding them.

When would I use a while loop? Why would that be the better choice for the loop over a for loop?

Though I know how to code them I do not quite have a full comprehension on determining which to use and why one would be better than the other.

Any examples and/or like laymen's break down would be much appreciated!

Top answer
1 of 5
11
Imagine you have a collection of 1,000,000 songs. You want to search for one song specifically, and return that song (or, if the song doesn't exist in the collection, tell you it wasn't found). A for or for-each loop could accomplish that, but it's going to loop 1,000,000 times even if the song is the very first record checked, which is a huge waste of time and power. If you write a while loop and then have it stop when a matching record is found, it runs exactly as much as is necessary and no more. Another example -- imagine a simple text-based console app that reads input from a user and then prints it out on the screen, but then closes when they type "quit". If you put the steps of your program - asking the user for input, assigning it to a variable, and then printing it out - in a for/for-each loop, how do you know how many times to run it? A while loop that stops running when the user types "quit" lets the user flexibly quit whenever they want, whether on 0 entries or 200. There's a lot of other applications but hopefully these are useful to conceptualize at least.
2 of 5
10
There's actually 4 types of loops in Java. A normal for loop (for(int i = 0; etc), a while loop, a do-while loop and a for-each (or enhanced for loop). Examples: For loop: for(int i = 0;i < someNumber;i++) { //Do something } While loop: while(expression) { //Do something } Do-while: do { //Do something } while(expression); Enhanced for: for(Element e : collectionOfElements) { //Do something with E. } In essence they all do the exact same thing: repeat the inner block based on a condition. When and how the condition is checked differs between them and you use each depending on what you need to do. A very rough guideline is: For: when you know beforehand you have to do something N number of times For-each: when you need to iterate over a collection, iterable or array While: when you need to loop an unknown number of times and need to check the condition to continue before the code block. Do-while: when you need to loop an unknown number of times and need to check the condition after the code block. Also keep in mind that break (break out of the loop) and continue (skip the rest of the code and go directly to the next iteration) are all control statements that work for all loops. So it's very possible to use a while as a for loop or vice versa.
🌐
Programiz
programiz.com › java-programming › do-while-loop
Java while and do...while Loop
In this tutorial, we will learn how to use while and do while loop in Java with the help of examples.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-do-while-loop
Java do while loop | DigitalOcean
August 3, 2022 - The do-while loop in Java is similar to while loop except that the condition is checked after the statements are executed, so do while loop guarantees the loop execution at least once.
🌐
IONOS
ionos.com › digital guide › websites › web development › java do-while loop
How to use the Java do-while loop - IONOS
January 3, 2025 - The do-while loop is used in Java to execute and repeat an in­struc­tion until a defined ter­mi­na­tion condition is fulfilled (i.e., true). Similar loops exist in most pro­gram­ming languages and are used to execute certain blocks of code multiple times.
Top answer
1 of 2
3
Hi Tanguy, I have seen this problem come up a lot. You do not actually need a boolean to run your do while loop, and you can simplify it a lot by having the loop depend on the response directly. java // I have initialized a java.io.Console for you. It is in a variable named console. String response; do{ response = console.readLine("Do you understand do while loops?"); }while(response.equalsIgnoreCase("no")); You may also include your print statement that you included using if(response.equalsIgnoreCase("no")). HOWEVER, with all that being said, what you did actually works fine! You just made a typo in your code. You wrote invalidReponse not invalidReSponse, as declared outside your loop. You can see these errors easily if you check the compiler error (You would see a symbol not found error point to that variable) Hope that helps!
2 of 2
0
I think i'm very unfamiliar with this kind of Java syntax. Using the console.printf() instead of System.out.println() and console.readLine() instead of scanner.nextLine(). I still don't understand why Tanguy Muffat's program works after fixing the syntax error. I don't understand how having the [while(response.equalsIgnoreCase("no"));] at the bottom works. Normally i would expect it to look more like : do{ while(response.equalsIgnoreCase("no")) { console.printf("Sorry you cannot continue the training. Train harder to understand the concept. \n"); }} I would think that a while condition with no brackets under it and nothing inside of it wouldn't work. In Tanguy Muffat's program it looks like the while loop is completely outside of the do loop.
🌐
GeeksforGeeks
geeksforgeeks.org › java › loops-in-java
Java Loops - GeeksforGeeks
The do-while loop ensures that the code block executes at least once before checking the condition. Example: The below Java program demonstrates a do-while loop that prints numbers from 0 to 10 in a single line.
Published   August 10, 2025
🌐
Reddit
reddit.com › r/learnjava › do while loop help
r/learnjava on Reddit: Do While Loop Help
September 16, 2021 -

New to Java and trying to get more familiar with loops. I am trying to make a do while loop to do a simple loan calculation (user inputs amount of loan, yearly interest, monthly payment). The problem is, I want to use the new number after the equation is run the first time as the starting number for the next time the program runs the equation(x+y=z, use z as the starting point for z+y=a, so on and so forth) and I can’t figure it out. Suggestions?

🌐
W3Schools
w3schools.com › java › java_for_loop.asp
Java For Loop
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:
🌐
Reddit
reddit.com › r/learnprogramming › is it me, or is java for loops and while loops pretty much the same thing(java)
r/learnprogramming on Reddit: Is it me, or is java for loops and while loops pretty much the same thing(Java)
April 18, 2021 -

So i am in the middle of learning Java, and today i worked on loops. Specifically for and while loops. However, when i was given this problem to solve on codeacdemy, i noticed this.

While Loop

Examples 2:

class Coffee {

public static void main(String[] args) {

// initialize cupsOfCoffee

int cupsOfCoffee = 1;

// add while loop with counter

while(cupsOfCoffee <= 100) {

System.out.println("Fry drinks cup of coffee #" +cupsOfCoffee );

cupsOfCoffee ++;

}

}

}

Compared to:

For Loops:

class Coffee {

public static void main(String[] args) {

for (int cupsOfCoffee = 1;cupsOfCoffee <= 100;cupsOfCoffee++) {

System.out.println("Fry drinks cup of coffee #" + cupsOfCoffee);

}

}

}

For some reason, even though they pretty much resulted in the same output, for loops and while loops do pretty much the same thing, but for loops feel a tiny bit more simple(imo).

🌐
W3Schools
w3schools.com › java › ref_keyword_do.asp
Java do Keyword
How Tos Add Two Numbers Swap Two ... Loop Loop Through an Enum ... assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String ...