Java Tutorial
Java While Loop
while repeats as long as a condition stays true. Check that the condition can become false.
while
The condition is checked before each pass. If it starts false, the body never runs. Something inside the body must change the condition, or the loop never ends.
Example
public class Main {
public static void main(String[] args) {
int n = 3;
while (n > 0) {
System.out.println(n);
n--;
}
}
}do while
do { ... } while (condition); runs the body once, then checks. Use it when the body must run at least once.
Example
public class Main {
public static void main(String[] args) {
int n = 0;
do {
n++;
} while (n < 3);
System.out.println(n);
}
}Euclid gcd
A remainder loop is a classic while: you do not know the step count in advance.
Example
public class Main {
public static void main(String[] args) {
int a = 48, b = 18;
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
System.out.println(a); // 6 (greatest common divisor)
}
}The infinite-loop trap
A while loop keeps going until its condition turns false. If nothing inside the body moves toward that, the loop never stops and the program hangs. Every while needs a line that changes the thing being tested.
Example — this never ends
int n = 5;
while (n > 0) {
System.out.println(n);
// forgot n--; so n stays 5 forever
}If your program freezes, a runaway while is the usual cause. Check that the counter really changes each pass and that the condition can actually become false.
Try It Yourself
Exercise: Starting from int n = 100, keep halving it with integer division (n = n / 2) and print each value until it reaches 0. How many lines print?
Show solution
int n = 100;
while (n > 0) {
System.out.println(n);
n = n / 2;
}
// prints 100, 50, 25, 12, 6, 3, 1 -> 7 linesInteger division drops the fraction, so 25 halves to 12, not 12.5. Eventually 1 / 2 is 0 and the loop stops.
Key Takeaways
whilechecks its condition before each pass; a starting-false condition runs zero times.do ... whileruns the body once before the first check.- Something in the body must move the condition toward false, or the loop never ends.
- Reach for
whilewhen you do not know the number of passes up front.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.
Maths
Euclid gcd
Euclid’s algorithm replaces the larger number with a remainder until the remainder is 0. while is the natural loop: you do not know the step count in advance.
gcd(a, b) = gcd(b, a mod b)
Example
public class Main {
public static void main(String[] args) {
int a = 48, b = 18;
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
System.out.println(a);
}
}