+91 81900 98289

Java While Loop

while checks the condition before each pass. If the condition is false at the start, the body never runs. Something inside the body must change the values used in the test, or the loop never ends.

do while runs the body once before the test. Use it when you always need one pass, such as asking for input and then deciding whether to ask again.

Example

The loop prints n, then adds 1. After 3 is printed, n becomes 4 and the test fails.

public class Count { public static void main(String[] args) { int n = 1; while (n <= 3) { System.out.println(n); n = n + 1; } } }
If you forget n = n + 1, the condition stays true and the program does not finish. When you practice, keep the limit small so a mistake is obvious.