Careeroza
while Loop
Syntax
A while loop repeats a block as long as its condition is true. The condition is checked before each round.
while (condition) {
// repeated code
}Example
Example
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Round " + i);
i++;
}
// digits of a number
int n = 9042;
int digits = 0;
while (n > 0) {
n = n / 10;
digits++;
}
System.out.println("Digits: " + digits);
}
}Output
Round 1 Round 2 Round 3 Round 4 Round 5 Digits: 4
Note: Always change something inside the loop that makes the condition false eventually. Forgetting i++ creates an infinite loop.
When to Use while
Use while when you do not know in advance how many times to loop, for example "keep retrying until success" or "read until there is no more data".
Example
public class Main {
public static void main(String[] args) {
double savings = 10000;
int years = 0;
while (savings < 20000) {
savings = savings * 1.08; // 8% yearly growth
years++;
}
System.out.printf("Doubled in %d years (Rs. %.2f)%n", years, savings);
}
}Output
Doubled in 10 years (Rs. 21589.25)