What they're doing there is for each iteration of i, they're multiplying the result by 2, i times.

The walkthrough would be

i = 0, e = 0, result not multiplied, output 2 to the power of 0 is 1

i = 1, e = 1, result multiplied one time by 2, 2 to the power of 1 is 2

etc

They're decrementing e there to "count i backwards" down to 0. E is reset each time, and will always enter the while loop on iterations after the first one, and will always exit the while loop once it counts down to zero.

Answer from dbillz on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_while_loop.asp
Java 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 ... 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:
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-while-loop-with-examples
Java while Loop - GeeksforGeeks
Explanation: In the above example, the while loop runs until "i" is less than 6 and prints "Hello World" 5 times. Example: Calculating the Sum of Numbers from 1 to 10 with Java while Loop
Published   1 week ago
Discussions

While loop condition in java - Stack Overflow
I am working my way through "Java - A beginners guide by Herbert Schildt". I hope this question is not way too ridiculous. It is about a while loop condition, where the while loop is located inside a for loop. The code example is this one: More on stackoverflow.com
🌐 stackoverflow.com
JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100 - Stack Overflow
As the title states, I have trouble understanding loops and have come up with a way to do a simple 1 through 100 sum, but like I said, the loops are causing me some confusion. I think I have the FO... More on stackoverflow.com
🌐 stackoverflow.com
arrays - Java programming Beginner While-Loop - Stack Overflow
Second, when i enter exterminate, the program finishes the while loop without breaking after the user inserts exterminate in. Please don't make it complex because im new to java and don't know multi-dimensional arrays or do-while loops etc. More on stackoverflow.com
🌐 stackoverflow.com
do while loop - Java Basic
Tanguy Muffat is having issues with: Hi guys, I would need you support. I'm stucked under challenge 2/3 where I'm being asked: "Now continually prompt the user in a do whil... More on teamtreehouse.com
🌐 teamtreehouse.com
2
November 20, 2017
🌐
Tutorialspoint
tutorialspoint.com › java › java_while_loop.htm
Java - while Loop
The following diagram shows the flow diagram (execution process) of a while loop in Java - Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. In this example, we're showing the use of a while loop to print numbers starting from 10 to 19.
🌐
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)
Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program: class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); } }
🌐
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.
Find elsewhere
🌐
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 - Here is a simple java do-while loop example to print numbers from 5 to 10.
🌐
Tutorialspoint
tutorialspoint.com › java › java_do_while_loop.htm
Java - do...while Loop
The following diagram shows the flow diagram (execution process) of a do while loop in Java - In this example, we're showing the use of a while loop to print numbers starting from 10 to 19.
🌐
DataCamp
datacamp.com › doc › java › while
while Keyword in Java: Usage & Examples
This example demonstrates using a while loop to read user input until the user types "exit". The loop continues to prompt the user for input until the condition !input.equals("exit") becomes false.
🌐
IONOS
ionos.com › digital guide › websites › web development › while-loop java
How to use the while-loop in Java - IONOS
September 26, 2022 - A simple example of a while-loop in Java is a counter that counts up to a certain value. It does this exactly until the specified value (the ter­mi­na­tion condition) is reached.
🌐
BeginnersBook
beginnersbook.com › 2015 › 03 › while-loop-in-java-with-examples
While loop in Java with examples
September 11, 2022 - Fourth iteration: value of i is 3, fourth element of the array represented by arr[3] is printed. After fourth iteration: value of i is 4, the condition i<4 returns false so the loop ends and the code inside body of while loop doesn’t execute. Practice the following java programs related to while loop:
Top answer
1 of 3
7

- First to me Iterating and Looping are 2 different things.

Eg: Increment a variable till 5 is Looping.

    int count = 0;

    for (int i=0 ; i<5 ; i++){

        count = count + 1;

   }

Eg: Iterate over the Array to print out its values, is about Iteration

    int[] arr = {5,10,15,20,25};

    for (int i=0 ; i<arr.length ; i++){

        System.out.println(arr[i]);

   }

Now about all the Loops:

- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

For Loop :

int sum = 0; 

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

  sum += i; 

}

 System.out.println("The sum is " + sum);

The Difference between While and Do-While is as Follows :

- While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

- Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

While Loop :

int sum = 0; 
int i = 0;       // i is 0 Here

    while (i<100) {

      sum += i; 
      i++;

    }

  System.out.println("The sum is " + sum);

do-While :

int sum = 0; 
int i = 0;      // i is 0 Here

    do{ 

      sum += i; 
       i++
    }while(i < 100; );

     System.out.println("The sum is " + sum);

From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

ArrayList<String> arr = new ArrayList<String>();

arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");

for (String str : arr){         // str represents the value in each index of arr

    System.out.println(str);     

 }
2 of 3
5

Your for loop looks good.

A possible while loop to accomplish the same thing:

int sum = 0;
int i = 1;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("The sum is " + sum);

A possible do while loop to accomplish the same thing:

int sum = 0;
int i = 1;
do {
    sum += i;
    i++;
} while (i <= 100);
System.out.println("The sum is " + sum);

The difference between the while and the do while is that, with the do while, at least one iteration is sure to occur.

🌐
Stack Overflow
stackoverflow.com › questions › 33700062 › java-programming-beginner-while-loop
arrays - Java programming Beginner While-Loop - Stack Overflow
ArrayList<String> animals = new ArrayList<String>(); while(!animalname.equals("exterminate")) { animalname = JOptionPane.showInputDialog("Name an animal"); animals.add(animalname); ... } ... Sign up to request clarification or add additional ...
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.
🌐
DEV Community
dev.to › satyam_gupta_0d1ff2152dcc › master-the-java-while-loop-a-beginners-guide-with-examples-best-practices-1371
Master the Java While Loop: A Beginner's Guide with Examples & Best Practices - DEV Community
October 13, 2025 - As a beginner in programming, one of the first mind-blowing concepts you encounter is the ability to make a computer do the same task over and over again, without complaining. It’s the very essence of what makes computers powerful. In Java, one of the most fundamental tools for achieving this repetition is the humble while loop.
🌐
Reddit
reddit.com › r/learnprogramming › java: when to use a while loop?
r/learnprogramming on Reddit: Java: When to use a While Loop?
November 21, 2015 -

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.
🌐
SitePoint
sitepoint.com › blog › java › java’s while and do-while loops in five minutes
Java's While and Do-While Loops in Five Minutes — SitePoint
November 5, 2024 - A while loop is a control flow statement that allows us to run a piece of code multiple times. Like loops in general, a while loop can be used to repeat an action as long as a condition is met. The structure of Java’s while loop is very similar to an if statement in the sense that they both check a boolean expression and maybe execute some code.
Top answer
1 of 12
7

If you want to read data from a network socket until a character sequence is found, you first need to read the data and then check the data for the escape sequence.

do
{ 
   // read data
} while ( /* data is not escape sequence */ );
2 of 12
7

The while statement continually executes a block of statements while a particular condition is true

while (expression) {
     statement(s)
}

do-while evaluates its expression at the bottom of the loop, and therefore, the statements within the do block are always executed at least once.

do {
     statement(s)
} while (expression);

Now will talk about functional difference,

while-loops consist of a conditional branch instructions such as if_icmpge or if_icmplt and a goto statement. The conditional instruction branches the execution to the instruction immediately after the loop and therefore terminates the loop if the condition is not met. The final instruction in the loop is a goto that branches the byte code back to the beginning of the loop ensuring the byte code keeps looping until the conditional branch is met.

A Do-while-loops are also very similar to for-loops and while-loops except that they do not require the goto instruction as the conditional branch is the last instruction and is be used to loop back to the beginning A do-while loop always runs the loop body at least once - it skips the initial condition check. Since it skips first check, one branch will be less and one less condition to be evaluated.

By using do-while you may gain performance if the expression/condition is complex, since it is ensured to loop atleast once. In that casedo-while could call for performance gain

Very Impressive findings here, http://blog.jamesdbloom.com/JavaCodeToByteCode_PartOne.html#while_loop

Top answer
1 of 7
6

If I'm interpreting your question correctly you'd like real life examples that translate to code. Maybe something like the following.

  • You want to drive or ride your bike to the ice-cream shop a few miles away. You don't know how far it is exactly but you will recognize it when you get there (while), VS You want to ride your bike 15 miles out and then return and you have an odometer on the bike (for)

  • You want to shoot baskets until you have made 100 attempts (for) VS You want to shoot baskets until you have made 50 successful shots (while). Outside the US, substitute free kicks.

  • You want to write a 15 page paper on looping in Java (for) VS You want to work on your "looping in Java" paper until you are satisfied with the result (while).

  • You want to boil potatoes until a fork can be easily inserted (while) VS You want to boil potatoes for 11 minutes (for).

To translate these into code you need some imagined functions for the actual activities (void boilPotatoes()).

For some of them it is useful to discuss the empty case: you are already at the ice-cream shop, etc. For others, a discussion of "at least one iteration" might be useful to have.

If you want to include foreach in the game:

  • You want to polish all of your mom's teacups (foreach) VS You want to polish her ten most valuable teacups (for) VS You want to polish teacups until you run out of polish (while).
2 of 7
1

You would know beforehand when the for loop would terminate, this is not clear in a while loop. I basically tell my students "if you know when it ends, it's a for". (Sure, one can construct pathological cases and there is always this for (;;), but for basic understanding this issue is the crucial difference between for and while.)

As for examples:

  • print all elements of this array is a for,
  • play so many rounds of tic-tac-toe until the human player quits: while.

You might want to force them to convert for to while in an exercise and demostrate that the converse is not always possible.