Java While Loop - Understanding and Examples

Learn how the Java while loop works and how to use it to execute code repeatedly based on a condition. Master looping concepts for automating repetitive tasks in your Java programs.



Java While Loop

Loops in programming execute a block of code repeatedly as long as a specified condition is true. They are useful for automating repetitive tasks.

Syntax

Syntax

while (condition) {
// code block to be executed
}

Example

Example

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Output

0
1
2
3
4

Explanation: In this example, the while loop continues to execute the code block inside it as long as the variable i is less than 5. Each time the loop iterates, i is incremented by 1 until it reaches 5.

Note: It's important to ensure that the condition within the while loop eventually becomes false, otherwise the loop will continue indefinitely, resulting in an infinite loop.

Java While Loop Examples

Countdown Example

int countdown = 3;

while (countdown > 0) {
System.out.println(countdown);
countdown--;
}

System.out.println("Happy New Year 2023!!");
Output

3
2
1
Happy New Year 2023!!
Yatzy Example

int dice = 1;

while (dice <= 6) {
if (dice < 6) {
System.out.println("Sad.");
} else {
System.out.println("Hurray!");
}
dice = dice + 1;
}
Output

Sad.
Sad.
Sad.
Sad.
Sad.
Hurray!