Java While Loop
A Java while loop repeatedly executes a block of statements while a boolean condition remains true. It is useful when the number of iterations is not known before the loop starts, such as reading input until a sentinel value appears or repeating an operation until a state changes.
The condition is checked before every iteration. Therefore, a while loop may execute zero times when its condition is false initially.
Java While Loop Syntax
Following is the syntax of while loop.
while(condition) {
statement(s)
}
while is the keyword, and condition must be an expression that evaluates to either true or false.
- Java evaluates the condition before entering the loop body.
- If the condition is
true, Java executes the statements inside the loop. - After the loop body finishes, Java evaluates the condition again.
- When the condition becomes
false, execution continues with the first statement after the loop.
Unlike a Java for loop, initialization and updates are normally written as separate statements. Any variable that affects the condition must be updated correctly, or the loop may never terminate.
Java While Loop Flow
A typical counter-controlled while loop has three parts: initialize the counter before the loop, test it in the condition, and update it inside the loop body.
int counter = 1; // initialization
while (counter <= limit) { // condition
// statements
counter++; // update
}
The update does not have to be an increment. A loop may decrement a value, read a new value, remove an item from a collection, or change any other state used by the condition.
Print Numbers Using a Java While Loop
In this example java program, we have a while loop. And this while loop prints numbers from 1 to 5.
Example.java
public class Example {
public static void main(String[] args) {
//initialization
int i=1;
while(i<6) {
System.out.println(i);
//update
i++;
}
}
}
The variable i starts at 1. Each iteration prints its current value and then increments it. The loop stops when i becomes 6.
Output
1
2
3
4
5
Infinite While Loop in Java
In this example java program, we have a while loop. And this while loop prints numbers from 1 to and so on. The while loop is going to run forever. Because we gave true for condition in the while loop. As the condition never evaluates to false, the while loop runs indefinitely.
Example.java
public class Example {
public static void main(String[] args) {
//initialization
int i=1;
while(true) {
System.out.println(i);
//update
i++;
}
}
}
The following is only the beginning of the output. The program continues until it is stopped externally, an exception occurs, or a terminating statement such as break is introduced.
Output
1
2
3
4
5
An intentional infinite loop can be useful in servers, event loops, or menu-driven programs, but it should contain a clear exit path when termination is required.
Exit a Java While Loop with Break
We can break a while loop using break statement. This breaks the loop even before the while condition evaluates to false.
In this example java program, we have a while loop. And this while loop breaks when i is 4.
Example.java
public class Example {
public static void main(String[] args) {
//initialization
int i=1;
while(i<6) {
if(i==4) {
break;
}
System.out.println(i);
//update
i++;
}
}
}
When i becomes 4, the break statement immediately terminates the nearest enclosing loop. Therefore, 4 is not printed.
1
2
3
Skip an Iteration with Continue in a Java While Loop
You can skip the remaining statements in the current iteration by using the continue statement. Java then evaluates the while condition for the next iteration.
Make sure that variables controlling the loop are updated before continue executes. In the following example, i is incremented before continue; otherwise, the loop would remain stuck at i == 4.
Example.java
public class Example {
public static void main(String[] args) {
//initialization
int i=1;
while(i<6) {
if(i==4) {
i++;
continue;
}
System.out.println(i);
//update
i++;
}
}
}
At i == 4, Java increments i, skips the print statement, and starts the next condition check.
Output
1
2
3
5
Find a Factorial with a Java While Loop
In the following java program, we shall find the factorial of a number.
Example.java
public class JavaTutorial {
public static void main(String[] args) {
int n=6;
//initialization
int factorial = 1;
int i = 1;
while(i<=n) {
factorial = factorial*i;
i++;
}
System.out.println("Factorial of "+n+" is : "+factorial);
}
}
The loop multiplies factorial by every integer from 1 through n. For larger values, use long or BigInteger because an int overflows after relatively small factorials.
Output
Factorial of 6 is : 720
Traverse an Array with a Java While Loop
In this example java program, we shall use while loop to traverse through an array.
Example.java
public class JavaTutorial {
public static void main(String[] args) {
String[] phones = {"Apple", "Android", "Xiaomi", "Lenovo"};
//initialization
int i = 0;
while(i<phones.length) {
System.out.println("I have "+phones[i] + " smartphone.");
i++;
}
}
}
The index starts at 0 and remains valid while it is less than phones.length. Accessing an index equal to the array length would cause an ArrayIndexOutOfBoundsException.
Output
I have Apple smartphone.
I have Android smartphone.
I have Xiaomi smartphone.
I have Lenovo smartphone.
Read Input Until a Sentinel Value
A while loop is commonly used when a program must continue until the user enters a specific value. The following example adds integers until the user enters 0.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
System.out.print("Enter a number (0 to stop): ");
int number = scanner.nextInt();
while (number != 0) {
sum += number;
System.out.print("Enter a number (0 to stop): ");
number = scanner.nextInt();
}
System.out.println("Sum: " + sum);
scanner.close();
}
}
Here, 0 is the sentinel value. It ends the loop but is not added to the sum.
Nested While Loops in Java
A while loop can appear inside another while loop. The inner loop completes all its iterations for each iteration of the outer loop.
public class Example {
public static void main(String[] args) {
int row = 1;
while (row <= 3) {
int column = 1;
while (column <= 3) {
System.out.print(row * column + " ");
column++;
}
System.out.println();
row++;
}
}
}
Output
1 2 3
2 4 6
3 6 9
Java While Loop vs Do-While Loop
| Behavior | while loop | do-while loop |
|---|---|---|
| Condition check | Before the loop body | After the loop body |
| Minimum executions | Zero | One |
| Typical use | Run only while a condition is already true | Run once before deciding whether to repeat |
Choose while when the loop body should not run unless the initial condition is true. Choose do-while when one execution is required before the first condition check.
Common Java While Loop Mistakes
- Missing the update: If a counter or state variable never changes, the condition may remain true forever.
- Updating in the wrong direction: Incrementing a value when the condition requires it to decrease can create an infinite loop.
- Using an incorrect boundary: Confusing
<with<=can produce an off-by-one error. - Adding a stray semicolon: Writing
while (condition);creates an empty loop body. - Skipping an update before continue: A
continuestatement may bypass the update and prevent termination.
Java While Loop Frequently Asked Questions
Can a Java while loop execute zero times?
Yes. Java checks the condition before the first iteration. If it is false, the loop body is skipped.
How do you stop an infinite while loop in Java?
Make the loop condition become false, execute a break statement, return from the method, or stop the running program externally. A normal loop should have a clear and reachable termination condition.
When should you use a while loop instead of a for loop?
Use a while loop when the number of iterations depends on a condition that changes during execution and is not conveniently expressed as a counter. Use a for loop when initialization, condition, and update naturally belong together.
What is the difference between break and continue in a while loop?
break terminates the loop completely. continue skips the remaining statements in the current iteration and starts the next condition check.
Java While Loop Summary
In this Java Tutorial, we learned how a Java while loop checks its condition before each iteration, how to manage initialization and updates, and how to use break, continue, arrays, sentinel input, and nested loops. Ensure that every non-infinite loop has a reachable condition that eventually becomes false.
TutorialKart.com