Core Java Fundamentals ยท Loops
Learn about the do-while loop, a post-test (or exit-controlled) loop that guarantees the loop body is executed at least once.
public class DoWhileDemo {
public static void main(String[] args) {
// Condition is initially false
int count = 5;
System.out.println("The loop will execute at least once.");
do {
System.out.println("Count is: " + count);
count++;
} while (count < 5);
System.out.println("Loop finished. Final count: " + count);
}
}count and initialize it to 5. Notice that the loop condition count < 5 is already false.do block. This happens without checking any condition. This is the key feature of a do-while loop.count (5) is printed.count variable is incremented. Its value changes from 5 to 6.count < 5 is checked for the first time. Since 6 < 5 is false, the loop will not repeat.count.