Lesson 24 of 50 – Java While Loop
48%

Java While Loop

A while loop in Java repeatedly executes a block of code as long as a specified condition is true. It is useful when the number of repetitions is not known in advance.

1. What Is a While Loop?

Suppose you want to print numbers from 1 to 5. You can use a while loop instead of writing five separate print statements.

int i = 1;

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

Output:

1
2
3
4
5
The loop continues while i <= 5 is true. When i becomes 6, the loop stops.
2. Syntax of a While Loop
while (condition) {
    // Code to execute repeatedly
}

A while loop has two important parts:

  • Condition: Determines whether the loop should run.
  • Loop body: Contains the statements to execute.

Example:

int number = 1;

while (number <= 3) {
    System.out.println("Hello Java");
    number++;
}

This program prints "Hello Java" three times.

3. How Does a While Loop Work?

Consider this example:

int i = 1;

while (i <= 3) {
    System.out.println(i);
    i++;
}
Iteration Value of i Condition Action
1 1 1 <= 3 (true) Print 1
2 2 2 <= 3 (true) Print 2
3 3 3 <= 3 (true) Print 3
4 4 4 <= 3 (false) Stop the loop
4. Print Numbers from 1 to 10
public class Main {
    public static void main(String[] args) {

        int i = 1;

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

Output:

1
2
3
4
5
6
7
8
9
10
5. Print Numbers in Reverse Order

Use the decrement operator -- to count backward.

int i = 10;

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

Output:

10
9
8
7
6
5
4
3
2
1

The variable starts at 10 and decreases by 1 after each iteration.

6. Print Even Numbers

Print even numbers from 2 to 20.

int i = 2;

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

Output:

2
4
6
8
10
12
14
16
18
20

The statement i += 2 increases i by 2.

7. Calculate the Sum of Numbers

Calculate the sum of numbers from 1 to 10.

public class Main {
    public static void main(String[] args) {

        int i = 1;
        int sum = 0;

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

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

Output:

Sum = 55

The variable sum stores the running total, while i controls the loop.

8. Multiplication Table Using While Loop

Print the multiplication table of 5.

public class Main {
    public static void main(String[] args) {

        int number = 5;
        int i = 1;

        while (i <= 10) {
            System.out.println(number + " x " + i
                    + " = " + (number * i));
            i++;
        }
    }
}

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
9. While Loop with an Array

Use a while loop to print all elements of an array.

public class Main {
    public static void main(String[] args) {

        String[] names = {"Amit", "Rahul", "Priya", "Neha"};
        int i = 0;

        while (i < names.length) {
            System.out.println(names[i]);
            i++;
        }
    }
}

Output:

Amit
Rahul
Priya
Neha
Array indexes start at 0. Use i < names.length to avoid accessing an index outside the array.
10. While Loop with User Input

The following program asks the user for a number and prints numbers from 1 up to that number.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a positive number: ");
        int limit = sc.nextInt();

        int i = 1;

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

        sc.close();
    }
}

Example input: 5

Output:

1
2
3
4
5

If the user enters zero or a negative number, the loop does not execute.

11. Infinite While Loop

An infinite loop occurs when the condition remains true and the loop has no effective way to stop.

int i = 1;

while (i <= 5) {
    System.out.println(i);
    // i is never increased
}

The value of i remains 1, so the condition i <= 5 remains true forever.

Correct version:

int i = 1;

while (i <= 5) {
    System.out.println(i);
    i++;
}
Always check that your loop condition will eventually become false, unless you intentionally need an infinite loop.
12. Difference Between For Loop and While Loop
For Loop While Loop
Initialization, condition, and update appear in the loop header. Initialization and update are usually written separately.
Useful when the number of repetitions is known. Useful when repetition depends on a condition.
for (int i=1; i<=5; i++) while (i<=5)

Both loops can perform many of the same tasks.

For loop:

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

Equivalent while loop:

int i = 1;

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

Write Java programs to solve these beginner-level assignments.

  1. Print numbers from 1 to 20.
  2. Print numbers from 20 to 1.
  3. Print odd numbers from 1 to 30.
  4. Print even numbers from 1 to 50.
  5. Print the multiplication table of 8.
  6. Calculate the sum of numbers from 1 to 100.
  7. Calculate the factorial of a positive integer.
  8. Count how many digits are in a positive integer.
  9. Reverse the digits of a positive integer.
  10. Print all elements of an array using a while loop.
Tip: Before writing a while loop, initialize the variable, write the condition, and remember to update the variable inside the loop when necessary.

🧠 Quick Quiz

1. When does a while loop execute?




2. What is the purpose of i++ in a loop?




3. What happens if the while condition is false at the beginning?