Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Basics Perfecting the Prototype Looping until the value passes

Do While loops

I am not so great right now with do- while loops, can I please have assistance with this lesson.

// I have initialized a java.io.Console for you. It is in a variable named console.

2 Answers

do-while-loops are very similar to while-loops; both check a condition to see if it is "true" or "false" and continue to loop while it is "true".

The only difference between do-while and while is that a do-while will do the stuff inside the brackets at least once before checking the condition. Another way to say it is: "the condition check happens at the end of the do-while vs. the beginning in a while".

More videos on loops: https://teamtreehouse.com/library/feeling-loopy-with-java

Daniel Maia
Daniel Maia
6,228 Points

While loops are very similar to do-while loops. Easy way to remember is that when you use a while loop it will continue to run through as long as the statement is true. With a do-while loop any statements ran between the brackets is run first, always. Then it uses the while section followed with nothing but it needs to be true for it to be used again.

You would normally want to use this when you may want to display an alert dialog box to get the user to enter his name or something then in between the while brackets its checks if the user is "John" (example name)

Below is another example:

do { System.out.println("Count is: " + count); count++; } while (count < 11);

It prints out Count is: 0 (or whatever the initial count value is) which then goes to the while(count < 11) and checks if the count is less than 11 if it is then continue through the loop and check again if then then the count is greater than 11 it stops the loop.

Basically, 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.

I hope this helps you understand, if not please do let me know.