Iteration statements
Iteration statements are as fundamental for Java programming as selection statements. There is a good chance you will see and use them very often, too. Each iteration statement can be one of three forms: while, do...while, or for.
while
The while statement executes a Boolean expression and a statement or a block repeatedly until the value of the expression evaluates as false:
while (Boolean expression){
//do something
}There are two things to note:
- Braces
{}are not necessary when only one statement has to be repeatedly executed, but are recommended for consistency and better code understanding - The statement may not be executed at all (when the very first expression evaluation returns
false)
Let's look at some examples. The following loop executes the printing statement five times:
int i = 0;
while(i++ < 5){
System.out.print(i + " "); //prints: 1 2 3 4 5
}Notice a different method used for printing: print() instead of println(). The latter adds an escape sequence ...