Java while Loop
In this page:
Simple while Loop
A while loop checks its condition immediately, before running the body even once -- if the condition starts out false, the loop body never executes at all.
Example: Simple while Loop
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 3) {
System.out.println(i);
i++;
}
}
}
Login to try C/C++/Java/PHP code in the editor
Decrementing Loop Counters
Subtracting from a counter each pass through the loop, like count--, lets you count down toward zero (or any target) instead of the more common upward counting pattern.
Example: Decrementing Loop Counters
public class Main {
public static void main(String[] args) {
int count = 5;
while (count > 0) {
System.out.println(count);
count--;
}
}
}
Login to try C/C++/Java/PHP code in the editor
Loops with Boolean Flags
A boolean flag variable in the condition, like while (running), lets code inside the loop body itself decide when to stop by setting that flag to false, which is useful when the stopping condition is complex or event-driven.
Example: Loops with Boolean Flags
public class Main {
public static void main(String[] args) {
boolean running = true;
int i = 0;
while (running) {
System.out.println(i);
i++;
if (i == 3) {
running = false;
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
Avoiding Infinite Loops
If nothing inside the loop body ever changes the value(s) the condition depends on, the condition stays true forever and the loop runs indefinitely -- always double-check that your loop variable is actually being updated.
Example: Avoiding Infinite Loops
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 3) {
System.out.println(i);
i++; // removing this line would make the loop run forever
}
}
}
Login to try C/C++/Java/PHP code in the editor
Mathematical Growth Loops
Multiplying or dividing a loop variable each iteration (rather than adding or subtracting a fixed amount) produces exponential growth or decay, useful for algorithms like binary search that need logarithmic-scale steps.
Example: Mathematical Growth Loops
public class Main {
public static void main(String[] args) {
int value = 1;
while (value < 100) {
System.out.println(value);
value *= 2;
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: