Java While Loop


In Java, loops are used to execute a block of code repeatedly until a certain condition is met. Among all loop types, the while loop is one of the most commonly used because it checks the condition before executing the loop body. This means that if the condition is false from the beginning, the loop body will never execute.

The while loop is useful when you don’t know beforehand how many times a statement or block of code should run — for example, when taking input until the user enters a specific value.

Syntax of While Loop

The basic syntax of the while loop is simple and easy to remember:

while (condition) {
    // code block to be executed
}

Here’s how it works:

  1. The condition inside the parentheses is checked first.

  2. If the condition is true, the statements inside the loop body run.

  3. After executing the loop body, the condition is checked again.

  4. If it’s still true, the loop continues.

  5. When the condition becomes false, the loop stops.

Example: Printing Numbers from 1 to 5

Let’s start with a simple example:

int i = 1;

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

Output:

1  
2  
3  
4  
5

In this example, the variable i starts from 1 and keeps increasing by 1 until it reaches 5. Once i becomes 6, the condition i <= 5 becomes false, and the loop stops.

Flow of While Loop Execution

Here’s how Java executes a while loop step by step:

  1. The condition is evaluated.

  2. If the condition is true, the code inside the loop runs.

  3. After executing the block, control goes back to the condition.

  4. This process repeats until the condition becomes false.

  5. When the condition turns false, the loop terminates, and control moves to the next statement after the loop.

This structure is what makes the while loop known as an entry-controlled loop, because the condition is checked before entering the loop.

Example: Printing Even Numbers

Let’s look at another example that prints even numbers from 2 to 10.

int num = 2;

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

Output:

2  
4  
6  
8  
10

Here, the variable num starts from 2 and keeps increasing by 2 in each iteration until it exceeds 10.

Infinite While Loop

A while loop can easily become an infinite loop if the condition never becomes false. For example:

int i = 1;

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

In this case, since i is never incremented, the condition i <= 5 always remains true. As a result, the program keeps printing 1 forever and never stops. Infinite loops can cause your program to freeze or crash, so it’s important to ensure that the loop’s condition will eventually turn false.

Using While Loop with User Input

The while loop is often used when working with user input, especially when the number of iterations isn’t known in advance.
Example:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = 0;

        while (num >= 0) {
            System.out.print("Enter a number (negative to stop): ");
            num = sc.nextInt();
        }

        System.out.println("You entered a negative number. Loop ended.");
    }
}

Here, the program keeps asking the user for a number until a negative value is entered. The loop ends only when the condition becomes false.

Nested While Loops

A nested while loop means having one while loop inside another. This is useful for working with patterns, matrices, or combinations.
Example:

int i = 1;

while (i <= 3) {
    int j = 1;
    while (j <= 3) {
        System.out.print("(" + i + "," + j + ") ");
        j++;
    }
    System.out.println();
    i++;
}

Output:

(1,1) (1,2) (1,3)  
(2,1) (2,2) (2,3)  
(3,1) (3,2) (3,3)

The outer loop runs three times, and for each iteration, the inner loop also runs three times, printing all coordinate pairs.

Example: Sum of Natural Numbers

Another common use of while loops is calculating the sum of numbers.

int i = 1;
int sum = 0;

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

Output:

Sum = 15

This code adds numbers from 1 to 5 and stores the result in the sum variable.

Difference Between While and Do-While Loop

Both while and do-while loops perform repetitive tasks, but there’s one key difference.

Feature While Loop Do-While Loop
Condition Check Before executing the loop body After executing the loop body
Execution May not execute if the condition is false initially Executes at least once
Type Entry-controlled loop Exit-controlled loop

Example of do-while for comparison:

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

Even if the condition is false, this loop executes the body once before checking the condition.

Common Mistakes in While Loops

  1. Forgetting to update the loop variable can lead to an infinite loop.

  2. Using incorrect conditions, such as <= instead of <, may result in an extra iteration.

  3. Declaring the loop variable incorrectly inside the loop may reset its value each time.

Summary of the Tutorial

The while loop in Java is ideal when you need to repeat a block of code an unknown number of times, as long as a condition remains true. It’s simple yet powerful and widely used in input handling, calculations, and control-based programs. Always ensure the condition will eventually become false to avoid infinite loops.


Practice Questions

  1. Write a Java program using a while loop to print numbers from 1 to 20 on separate lines. Make sure the loop stops automatically when the number exceeds 20.

  2. Create a program that prints all even numbers between 1 and 50 using a while loop. Start with 2 and keep increasing the counter by 2 each time.

  3. Write a program using a while loop that calculates and prints the sum of the first 10 natural numbers.

  4. Develop a Java program that asks the user to enter positive numbers repeatedly and stops when the user enters a negative number. After stopping, print the total count of numbers entered.

  5. Create a program that prints the multiplication table of a given number using a while loop. The program should display results from 1 to 10.

  6. Write a Java program that reverses a given number using a while loop. For example, if the input is 1234, the output should be 4321.

  7. Develop a program using a while loop that checks whether a number entered by the user is a palindrome or not.

  8. Write a program that prints the factorial of a given number using a while loop. For example, if the input is 5, the output should be 120.

  9. Create a Java program using a while loop to count the digits in a given number. For example, if the number is 9852, it should print “4 digits.”

  10. Write a program that generates the Fibonacci series up to a given number of terms using a while loop. For instance, if the user enters 8, it should display the first 8 Fibonacci numbers.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top