Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program to demonstrate While Loop?

A while loop in Java is an entry-controlled control flow statement that repeats a block of code as long as a Boolean condition stays true. The condition is checked before every iteration, so if it is false the first time, the body never runs. As soon as the condition becomes false, the loop ends and execution continues with the statement after the loop. The short program below uses a while loop to print the numbers 1 to 5.

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

Output:

1
2
3
4
5

Syntax of the while Loop in Java

The while loop has a single Boolean condition followed by a body enclosed in braces.

while (condition) {
  // statements to run while the condition is true
  // update the loop variable here
}
  • condition: any expression that evaluates to a boolean. The loop continues while it is true and stops the moment it is false.
  • body: the statements that run on each pass. Without braces, only the next single statement is treated as the body, which is a frequent source of bugs.
  • update: a statement inside the body that moves the loop variable toward the value that ends the loop. Forgetting it leaves you with an infinite loop.

How the while Loop Executes

The execution follows a fixed cycle every time the loop runs.

  • Control reaches the while statement and the condition is evaluated.
  • If the condition is true, the body of the loop runs.
  • The update statement changes the loop variable.
  • Control returns to the top and the condition is evaluated again.
  • When the condition becomes false, the loop is skipped and execution moves to the statement that follows it.

Example: Sum of the First N Numbers

A while loop is a natural fit for accumulating a running total. Here it adds the numbers 1 through 10.

class SumDemo {
  public static void main(String[] args) {
    int i = 1, sum = 0;
    while (i <= 10) {
      sum += i;
      i++;
    }
    System.out.println("Sum of 1 to 10 = " + sum);
  }
}

Output:

Sum of 1 to 10 = 55

Example: Factorial Using a while Loop

Counting down toward the value that ends the loop works just as well as counting up. This program multiplies down from a number to compute its factorial.

class FactorialDemo {
  public static void main(String[] args) {
    int n = 5;
    long factorial = 1;
    while (n > 0) {
      factorial *= n;
      n--;
    }
    System.out.println("Factorial of 5 = " + factorial);
  }
}

Output:

Factorial of 5 = 120

while vs do-while

The do-while loop is the exit-controlled cousin of the while loop. It runs the body first and checks the condition afterward, so the body always executes at least once even when the condition is false from the start. Note the semicolon after the closing while.

class DoWhileDemo {
  public static void main(String[] args) {
    int x = 10;
    do {
      System.out.println("Executed once even though 10 > 5 is false");
    } while (x < 5);
  }
}

Output:

Executed once even though 10 > 5 is false

The table below summarizes how the two loops differ.

Aspectwhiledo-while
Condition checkBefore the body (entry-controlled)After the body (exit-controlled)
Minimum runsZero, if the condition starts falseOne, always
Best forLooping that may not run at allWork that must happen before validation, like menus

Infinite Loops and break

Writing while(true) creates a deliberate infinite loop. To make it terminate, you place a break statement inside it, which immediately exits the nearest enclosing loop when a stop condition is met.

class BreakDemo {
  public static void main(String[] args) {
    int i = 1;
    while (true) {
      if (i == 4) {
        System.out.println("Stopped at 4");
        break;
      }
      System.out.println(i);
      i++;
    }
  }
}

Output:

1
2
3
Stopped at 4

Skipping Iterations with continue

The continue statement skips the rest of the current iteration and jumps back to the condition test. The program below prints only the odd numbers from 1 to 10 by continuing past the even ones. Notice that the loop variable is incremented before continue, otherwise the loop would stall.

class ContinueDemo {
  public static void main(String[] args) {
    int i = 0;
    while (i < 10) {
      i++;
      if (i % 2 == 0) {
        continue;
      }
      System.out.println(i);
    }
  }
}

Output:

1
3
5
7
9

When to Use while vs for

  • Use a for loop when the number of iterations is known in advance. Its header keeps the initialization, condition, and update in one place, which is ideal for counting through a fixed range or an array.
  • Use a while loop when the number of iterations is unknown and depends on a runtime condition, such as reading input until a sentinel value, polling until a flag is set, or processing a stream until it ends.

Reading Input Until a Sentinel with Scanner

A common real-world use of the while loop is reading values until the user enters a stop value. The program below keeps adding numbers until it reads -1, the sentinel.

import java.util.Scanner;

class SentinelDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int total = 0;
    int value = sc.nextInt();
    while (value != -1) {
      total += value;
      value = sc.nextInt();
    }
    System.out.println("Total = " + total);
  }
}

Input: 5 10 15 -1

Output:

Total = 30

Common Pitfalls

  • Forgetting the update: if the loop variable is never changed inside the body, the condition stays true forever and the loop never ends.
  • Off-by-one errors: mixing up < and <= changes how many times the loop runs. Decide whether the boundary value should be included and pick the operator that matches.
  • Wrong update direction: incrementing when the condition expects a decrement, or vice versa, pushes the variable away from the exit value and creates an infinite loop.
  • Stray semicolon: writing while (condition); gives the loop an empty body, so it spins forever without running the statements you intended.
  • continue before the update: if continue jumps past the statement that changes the loop variable, the loop can get stuck repeating the same iteration.

Once your loop-driven Java logic is correct, you can run the Selenium or unit tests that depend on it across thousands of real browser and OS combinations on the Selenium Automation, so behaviour stays consistent everywhere your code runs.

Frequently Asked Questions

When is the condition of a while loop checked in Java?

The while loop is entry-controlled, so the Boolean condition is evaluated before every iteration, including the very first one. If the condition is false when the loop is reached, the body never runs even once.

What is the difference between a while loop and a do-while loop?

A while loop checks the condition before the body, so it can run zero times. A do-while loop checks the condition after the body, so it always runs the body at least once. Use do-while when the work must happen first, such as showing a menu before validating the user's choice.

Why does my Java while loop run forever?

An infinite while loop usually means the variable in the condition is never updated, is updated in the wrong direction, or a stray semicolon after while(condition) created an empty body. Make sure each iteration moves the loop variable toward the value that makes the condition false.

When should I use a while loop instead of a for loop?

Use a for loop when you know the number of iterations in advance, since its header keeps the initialization, condition, and update together. Use a while loop when the number of iterations is unknown and depends on a runtime condition, such as reading input until a sentinel value or a stop flag is set.

What do break and continue do inside a while loop?

break immediately exits the nearest enclosing loop, so control jumps to the statement after the loop. continue skips the rest of the current iteration and jumps straight back to the condition test for the next iteration.

Can a while loop body run without curly braces?

Yes. If you omit the braces, only the single statement immediately after while(condition) is treated as the loop body. This is a common source of bugs, so it is safer to always wrap the body in braces.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests