Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Real-Life Examples

Real-Life Examples

To illustrate a practical example of the while loop, we’ve developed a straightforward “countdown” program.

Example

int countdown = 3;
while (countdown > 0) {
  System.out.println(countdown);
  countdown--;
}
System.out.println("Happy New Year!!");

To showcase a practical example of combining the while loop with an if-else statement, let’s consider playing a game of Yatzy.

Example

Output “Yatzy!” when the dice number equals 6.

int dice = 1;

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

When the loop iterates through values 1 to 5, it prints “No Yatzy”. However, when it encounters the value 6, it prints “Yatzy!”.