Java While Loop

Real-Life Examples

Java While Loop Examples

We have made a basic “countdown” program to show how the while loop works in practice:

Example

				
					int countdown = 3;

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

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

Let’s imagine we play a game of Yatzy to show how the while loop and an if else statement work in practice:

Example

Put “Yatzy!” in print. Should the dice yield a six:

				
					int dice = 1;

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

The loop outputs “No Yatzy” if it receives values between 1 and 5. It prints “Yatzy!” each time the value of 6 is exceeded.

Share this Doc

Real-Life Examples

Or copy link

Explore Topic