Java While Loop - Syntax, Flowchart and Examples

⏱️ 7 min read • Beginner Level • Lesson 26

Lesson 26 of 124 of Java Tutorial
You have completed this lesson

Completed on . You can revise this lesson or continue to the next topic.

The while loop in Java is used to execute a block of code repeatedly as long as a given condition remains true. It is an entry-controlled loop, which means the condition is checked before the loop body executes.

Before learning the while loop, you should understand Java if statement, Java operators, and Java variables.


What is While Loop in Java?

A while loop is a looping statement that repeats a block of code while the condition is true. If the condition is false at the beginning, the loop body will not execute even once.

  • The condition is checked before every iteration.

  • The loop body executes only when the condition is true.

  • A proper update statement is usually required to avoid an infinite loop.

Syntax of while Loop

A while loop usually has three important parts: initialization, condition, and update.

WhileLoopSyntax.java
Copy Download
initialization;

while (condition) {
    // loop body
    update;
}
Note: The condition inside while must be a boolean expression. For example, i <= 5, count > 0, or isRunning == true.

Flowchart of while Loop

The following diagram shows how a while loop works. Java checks the condition first. If the condition is true, the loop body executes. After that, the condition is checked again.

Java while loop flow diagram

How does it work?

  • Java first checks the condition inside the while statement.
  • If the condition is true, the loop body executes.
  • After the loop body executes, the update statement changes the loop variable.
  • Java checks the condition again before the next iteration.
  • If the condition becomes false, the loop stops.

Real-World Uses of while Loop

  • Reading user input until a valid value is entered.
  • ATM menu systems.
  • Game loops.
  • Processing files and records.
  • Repeating tasks until a condition becomes false.

Java while Loop Example

The following program prints Hello five times using a while loop.

WhileDemo.java
Copy Try Download
public class WhileDemo {
    public static void main(String[] args) {
        int i = 1;

        while (i <= 5) {
            System.out.println(i + ". Hello");
            i++;
        }
    }
}

Output:

1. Hello
2. Hello
3. Hello
4. Hello
5. Hello

Explanation

  1. The variable i is initialized with value 1.
  2. The condition i <= 5 is checked before every iteration.
  3. If the condition is true, the loop body prints the value of i with Hello.
  4. The statement i++ increases the value of i by 1.
  5. When i becomes 6, the condition becomes false and the loop stops.

Example: Sum of First 5 Numbers

This example calculates the sum of numbers from 1 to 5.

SumWhileLoop.java
Copy Try Download
public class SumWhileLoop {
    public static void main(String[] args) {
        int i = 1;
        int sum = 0;

        while (i <= 5) {
            sum = sum + i;
            i++;
        }

        System.out.println("Sum = " + sum);
    }
}

Output:

Sum = 15

Example: Reverse Counting using while Loop

A while loop can also be used to count backward.

ReverseWhileLoop.java
Copy Try Download
public class ReverseWhileLoop {
    public static void main(String[] args) {
        int i = 5;

        while (i >= 1) {
            System.out.println(i);
            i--;
        }
    }
}

Output:

5
4
3
2
1

Infinite while Loop

An infinite loop happens when the condition never becomes false. This usually happens when the update statement is missing or incorrect.

InfiniteWhileLoop.java
Copy Download
public class InfiniteWhileLoop {
    public static void main(String[] args) {
        int i = 1;

        while (i <= 5) {
            System.out.println(i);
            // i++ is missing, so this loop never ends
        }
    }
}
Important: Always make sure that the loop condition will eventually become false. Otherwise, the while loop may run forever.

Difference Between while Loop and for Loop

while Loop for Loop
Used when the number of iterations is not always known. Used when the number of iterations is usually known.
Initialization, condition, and update are written separately. Initialization, condition, and update are usually written in one line.
Good for condition-based repetition. Good for counter-based repetition.

Common Mistakes in while Loop

  • Forgetting to update the loop variable.
  • Writing a condition that never becomes false.
  • Using = instead of == in conditions.
  • Adding an unwanted semicolon after the while condition.
  • Changing the loop variable incorrectly inside the loop.
Summary:
  • The while loop repeats code while the condition is true.
  • It is an entry-controlled loop because the condition is checked first.
  • If the condition is false initially, the loop body does not execute.
  • The loop should include a proper update to avoid infinite loops.
  • while loop is useful when the number of iterations is not fixed in advance.

Interview Questions ⭐

A while loop in Java is used to execute a block of code repeatedly as long as the given condition is true.

The while loop is an entry-controlled loop because the condition is checked before the loop body executes.

Yes, if the condition is false at the beginning, the while loop body will not execute even once.

An infinite while loop occurs when the loop condition never becomes false, often because the update statement is missing or incorrect.

A while loop is commonly used when the number of iterations is not known, while a for loop is commonly used when the number of iterations is known.

Next step: Learn Java Do-While Loop

?? Continue to Java Do-While Loop ?

?? Test your understanding with a quick quiz



🚀 Quick Knowledge Check

Topic: While-loop | Language: Java

Question 1 of 10
Q1. When is the condition checked in a while loop?
Q2. What will be the output?
int i = 5;
while (i >= 1) {
    System.out.println(i);
    i--;
}
Q3. Which statement usually prevents an infinite while loop?
Q4. What is the main purpose of a while loop in Java?
Q5. Which of the following is true about a while loop?
Q6. Which loop is usually preferred when the number of iterations is not known in advance?
Q7. What will be the output of this code?
int i = 1;
while (i <= 3) {
    System.out.println(i);
    i++;
}
Q8. What will happen in this code?
int i = 1;
while (i <= 5) {
    System.out.println(i);
}
Q9. Which keyword is used to write a while loop in Java?
Q10. Can a while loop execute zero times?

?? Great job! Continue learning Java step by step.

Discussion

Ask questions, share suggestions, or discuss this lesson.

Please login or create an account to join the discussion and save your learning activity.

Loading comments...

Have you completed this lesson?

Mark this lesson as completed to track your learning progress. To keep track across devices, please login and save your learning progress.

Not completed yet.