Where can we use while loop?
A common practice when writing software is the need to do the same task some number of times.
Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
The while statement
Like all repetition control structures, it has a termination condition, implemented as a boolean expression, that will continue as long as the expression evaluates to true.
Syntax
The syntax of a while loop is
while(condition) {
// body of loop
}
Java while loop example
Here is a simple java while loop example to print numbers from 1 to 7.
package com.yuriyni.java.controlstatements;
public class WhileDemo {
public static void main(String[] args) {
int count = 1;
while (count <= 7) {
System.out.println("Day of the week: " + count);
count++;
}
}
}
Output:
Day of the week: 1
Day of the week: 2
Day of the week: 3
Day of the week: 4
Day of the week: 5
Day of the week: 6
Day of the week: 7
The do/while statement
The do-while
loop is similar to while loop. Unlike a while loop, though, a do/while loop guarantees that the statement or block will be executed at least once.
Whereas a while loop is executed zero or more times, a do/while loop is executed one or more times.
Syntax
The syntax of a while loop is
do {
// loop body
}
while (condition);
Java do-while loop example
package com.yuriyni.java.controlstatements;
public class DoWhileDemo {
public static void main(String[] args) {
int count = 8;
do {
//However, the body of do...while loop is executed once before the test
//expression is checked.
System.out.println("not checked:" + count);
count++;
}while (count <= 7);
}
}
Output:
not checked:8