This is a really beginner question. I am currently reading "Java: A beginner's guide" and it says the do-while always at least executes once. Can someone please explain to me why this loop always executes once? The book's explanation is "do-while loop checks its condition at the bottom of the loop. This means that a do-while loop will always executes at least once." It does not make sense to me why it would always executes once if it checks the condition at the bottom rather than the top.
Asked
Active
Viewed 1,731 times
0
-
1code in java is run sequentially. so the code that appears first, is executed first. since `do` is followed by `while`, the code in `do` is executed before `while`. also a suggestion, if you are starting to learn java, use the documents and tutorials provided by oracle. – Rahul Sharma Aug 19 '16 at 16:05
-
Rough translation is "Do this thing. And then, while the specified condition remains true, keep doing it." As opposed to a plain old `while` loop, which is: "While the specified condition remains true, keep doing this thing." – sparc_spread Aug 19 '16 at 16:07
3 Answers
4
The code at the top is executed before than the code at the bottom. Therefore, when the condition is checked, the body has already been executed once.

Andres
- 10,561
- 4
- 45
- 63
0
A normal while loop
looks something like:
- If condition is false, go to step 4
- Execute loop body
- Go to step 1
- Continue into rest of program
A do-while
loop is like:
- Execute loop body.
- If condition is true, go go step 1
- Continue into rest of program.
Do you see how nomatter what, the do-while
version will always have at least one execution of the loop body?

Edward Peters
- 3,623
- 2
- 16
- 39
-
I understand now, thank you. I thought the book was staying that the do-while looks at the code from the bottom up, first (the condition), which is why I was confused about why it always executes at least once. I understand the loop now. It goes from the top down but the statement is before the the condition. – Lawleyenda Aug 19 '16 at 16:12
0
The do
statement is defined in JLS Sec 14.13:
The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false.
DoStatement: do Statement while ( Expression ) ;
A do statement is executed by first executing the
Statement
. Then there is a choice:
- If execution of the Statement completes normally, then the Expression is evaluated.
(snip)
Executing a do statement always executes the contained Statement at least once.
Hence, it executes at least once by specification.

Community
- 1
- 1

Andy Turner
- 137,514
- 11
- 162
- 243