HelloUniversity Icon HelloUniversity

While Looping Statement in Java

Published on: 1 October 2025 by Henson M. Sagorsor



Introduction to Office Suites

While Looping Statement

A while loop in Java is a control structure that lets your program repeat actions as long as a condition is true. It is called a pre-test loop because the condition is checked first before anything inside the loop happens.

Think of it like waiting in line at the cafeteria: you stay in line while there are people ahead of you. When the line is empty, you stop waiting. That’s exactly how the while loop works.

How It Works

  • The program checks the condition first.
  • If the condition is true, the loop body runs.
  • After running, the condition is checked again.
  • The loop continues until the condition is false.

Flowchart Representation

While loop flowchart

Notice that the condition is tested before the body runs. If it is false right away, the loop will never execute.

General Syntax

while (condition) {
    // statements to repeat
}
  

Examples

Example 1: Counting Numbers

int x = 0;
while (x < 5) {
    System.out.println("Number: " + x);
    x++;
}
  

This prints numbers 0 through 4. Notice the x++ inside the loop — without it, the loop would never end.

Example 2: Infinite Loop

while (true) {
    System.out.println("This never stops!");
}
  

Since the condition is always true, this loop never ends. Be careful with infinite loops unless they are intentional.

Example 3: Loop That Never Runs

while (false) {
    System.out.println("You will never see this.");
}
  

The loop body is skipped entirely because the condition is false from the start.

When to Use While Loops

  • When you don’t know in advance how many times something will repeat.
  • Asking for input until the user types “quit.”
  • Processing data until the end of a file is reached.
  • Repeating an action until a certain condition is met.

Key Points to Remember

  • A while loop checks the condition first before running.
  • If the condition is false at the start, the loop never runs.
  • Always update something inside the loop to avoid infinite loops.
  • Think of it as repeating a task until the situation changes.

Try It Yourself

  1. Write a while loop that prints numbers from 1 to 10.
  2. Create a while loop that asks the user for a password until they type the correct one.
  3. Predict: what happens if you forget to update the loop variable inside the loop?


quiz Mandatory Assessment

All students must complete the assessment for this lesson. Your submission is required for course completion.

assignment_turned_in Take Assessment

warning Don’t miss this! Assessment link is required for all students.


Expand Your Knowledge

Dive deeper into technology and productivity with these related articles:






We'd Like to Hear Your Feedback

Comments

No comments yet. Be the first to share your thoughts!