Java while Loop

Introduction

The Java while loop is one of the fundamental looping statements in Java that allows you to execute a block of code repeatedly as long as a specified condition remains true. It is particularly useful when the number of iterations is not known in advance and depends on a condition evaluated during program execution.

For example:

  • Read user input until the user enters a valid value.
  • Display a menu repeatedly until the user chooses to exit.

In this tutorial, you’ll learn everything about the Java while loop, including its syntax, working mechanism, examples, real-life applications, infinite loops, common mistakes, best practices, interview questions, and more.

What is Java while Loop?

The Java while loop is an entry-controlled loop that repeatedly executes a block of code as long as a specified condition evaluates to true.

The condition is checked before each iteration. If the condition is false initially, the loop body is never executed.

This makes the while loop ideal for situations where the number of repetitions is unknown.

How It Works

The execution process is:

  1. Evaluate the condition.
  2. If the condition is true, execute the loop body.
  3. Update the loop variable (if required).
  4. Repeat until the condition becomes false.
  5. Exit the loop and continue with the rest of the program.

Syntax


while (condition) {
    // Code to execute repeatedly
}

Explanation

  • while is a Java keyword.
  • condition must return a boolean value (true or false).
  • The loop body executes only if the condition is true.
  • Once the condition becomes false, the loop terminates.

Flow of Java while Loop

The execution flow is shown below:


        Start
          |
     Check Condition
          |
     ----------------
     |              |
   True          False
     |              |
Execute Loop      End Loop
     |
 Update Variable
     |
 --------------

The condition is evaluated before every iteration.

Example 1: Print Numbers from 1 to 5


public class Main {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println(i);
            i++;
        }
    }
}

Output

1
2
3
4
5

Explanation

  • The variable i starts with 1.
  • The loop executes while i <= 5.
  • After each iteration, i increases by 1.
  • When i becomes 6, the condition becomes false, and the loop ends.

Example 2: Print Even Numbers


int number = 2;
while (number <= 10) {
    System.out.println(number);
    number += 2;
}

Output

2
4
6
8
10

Example 3: Calculate Sum of Numbers


int i = 1;
int sum = 0;
while (i <= 5) {
    sum += i;
    i++;
}
System.out.println("Sum = " + sum);

Output

Sum = 15

Example 4: Reverse Counting


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

Output

10
9
8
7
6
5
4
3
2
1

Example 5: User Login Attempts


int attempts = 1;
while (attempts <= 3) {
    System.out.println("Login Attempt: " + attempts);
    attempts++;
}

Output

Login Attempt: 1
Login Attempt: 2
Login Attempt: 3

This example simulates three login attempts.

Infinite while Loop

If the condition never becomes false, the loop runs forever.


while (true) {
    System.out.println("Running...");
}

When Is It Used?

Infinite loops are useful in:

  • Game engines
  • Web servers
  • Chat applications
  • Monitoring systems
  • Event listeners

Always ensure there is a way to terminate the loop if necessary.

Real-life Examples

1. ATM Menu


int option = 1;
while (option != 4) 
    System.out.println("Displaying ATM Menu");
    optin++;
}

The menu continues until the user selects the exit option.

2. Countdown Timer


int seconds = 5;
while (seconds > 0) {
    System.out.println(seconds);
    seconds--;
}

3. Reading Employee Records


int employee = 1;
while (employee <= 5) {
    System.out.println("Employee ID: " + employee);
    employee++;
}

4. Product Inventory


int stock = 10;
while (stock > 0) {
    System.out.println("Remaining Stock: " + stock);
    stock--
}

5. Password Validation


boolean passwordCorrect = false;
int attempts = 0;
while (!passwordCorrect && attempts < 3) {
    System.out.println("Enter Password");
    attempts++;
}

The loop continues until the password is correct or the maximum number of attempts is reached.

Java while Loop vs for Loop

Feature while Loop for Loop
Best For Unknown number of iterations Known number of iterations
Initialization Outside the loop Inside the loop
Update Inside the loop body In the loop declaration
Condition Check Before each iteration Before each iteration
Common Usage User input, menus, file reading Counting, arrays, tables

Advantages of Java while Loop

  • Ideal when the number of iterations is unknown.
  • Easy to understand and implement.
  • Reduces repetitive code.
  • Suitable for menu-driven programs.
  • Frequently used in file processing and database operations.
  • Works well with user input and validation.
  • Supports complex conditions.

Common Mistakes

1. Forgetting to Update the Loop Variable

Incorrect:


int i = 1;
while (i <= 5) {
    System.out.println(i);
}

This results in an infinite loop because i never changes.

Correct:


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

2. Wrong Loop Condition

Incorrect:


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

The condition is false initially, so the loop never executes.

3. Missing Braces

Incorrect:


while (i <= 5)
    System.out.println(i);
    i++;

Only the first statement belongs to the loop.

Correct:


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

4. Using Assignment Instead of Comparison

Incorrect:


while (flag = true) {
}

Correct:


while (flag) {
}

Or simply:


while (flag == true) {
}

5. Creating Unnecessary Infinite Loops

Avoid using:


while (true) {
}

unless your application specifically requires an infinite loop.

Best Practices

📖
Best Practices:
  • Always ensure the loop condition eventually becomes false.
  • Use meaningful variable names.
  • Keep the loop body short and readable.
  • Avoid deeply nested loops.
  • Use braces {} even for a single statement.
  • Prefer a for loop when the number of iterations is known.
  • Test boundary conditions carefully.

while Loop vs do-while Loop

Feature while Loop do-while Loop
Condition Check Before execution After execution
Minimum Executions Zero One
Use Case Unknown iterations At least one execution required

Conclusion

The Java while loop is one of the most important looping constructs in Java, allowing programs to execute a block of code repeatedly as long as a specified condition remains true. Because it checks the condition before each iteration, it is an excellent choice for situations where the number of repetitions is unknown or depends on user input, file data, or runtime conditions.

Java While loop – Interview Questions

Q 1: What is while loop in Java?
Ans: A loop that executes while a condition remains true.
Q 2: Is while loop entry-controlled?
Ans: Yes, condition is checked before execution.
Q 3: What happens if condition is false initially?
Ans: The loop body will not execute.
Q 4: Can while loop run infinitely?
Ans: Yes, if condition never becomes false.
Q 5: When to use while loop?
Ans: When iterations are not predetermined.

Java While Loop – Objective Questions (MCQs)

Q1. Which of the following is the correct syntax for a while loop in Java?






Q2. What will be the output of the following code?

int i = 1;
while (i <= 3) {
System.out.print(i + ' ');
i++;
}






Q3. What will happen if the condition in a while loop never becomes false?






Q4. What is the output of the following code?

int count = 5;
while (count > 0) {
System.out.println('Hello');
count--;
}






Q5. What will be the output of this code?

int x = 10;
while (x < 5) {
System.out.println('Inside Loop');
x++;
}
System.out.println('Outside Loop');






Related Java Tutorials