Do-While loop in java is a loop that will execute at least once even when the loop condition is false initially.
public class Main {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 5);
}
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
In this example, the count
is 1
initially, which satisfies the loop condition count<= 5
. This program will execute like it was a normal while loop.
Now we change the initial value for count
to 6
, makes it no longer satisfy the loop condition.
public class Main {
public static void main(String[] args) {
int count = 6;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 5);
}
}
Count is: 6
This time, even the loop condition is not satisfied, the loop is executed once.
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_Development Programming_Languages Java Do-While_Loop