← Back to Core Java Course | Chapter 4: Control Flow | Lesson 5 of 9

Java while Loop

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

java
public class Main {
	public static void main(String[] args) {
		int i = 0;
		while (i < 3) {
			System.out.println(i);
			i++;
		}
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		int count = 5;
		while (count > 0) {
			System.out.println(count);
			count--;
		}
	}
}

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

java
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;
			}
		}
	}
}

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

java
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
		}
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		int value = 1;
		while (value < 100) {
			System.out.println(value);
			value *= 2;
		}
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.