Java While Loop

Su Suriya Ravichandran Updated 14 Nov 2026
6 min read ·Lesson 19 of 306

A loop repeats a block of code. The while loop repeats it as long as a condition remains true, checking the condition before each repetition. It is the natural choice when the number of repetitions is not known in advance: read until the input ends, retry until a request succeeds, keep running until the user quits.

Syntax

while (condition) {
    // body: runs repeatedly while condition is true
}
int count = 1;

while (count <= 5) {
    System.out.println("Count: " + count);
    count++;
}
System.out.println("Done");

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done

Step by step

  1. count starts at 1.
  2. The condition count <= 5 is checked. It is true, so the body runs: it prints and increments count to 2.
  3. Control returns to the condition. Steps 2–3 repeat for 2, 3, 4, and 5.
  4. After printing 5, count becomes 6. The condition 6 <= 5 is false, so the loop ends and execution continues with Done.

Every working while loop has three parts:

PartHerePurpose
Initializationint count = 1;Sets up the state the condition depends on
Conditioncount <= 5Decides whether to run the body again
Updatecount++Changes the state so the condition will eventually become false

Zero Iterations

The condition is checked before the first run. If it is false at the start, the body never executes:

int stock = 0;
while (stock > 0) {
    System.out.println("Selling one item");
    stock--;
}
// prints nothing

This is a feature: a while loop handles the empty case automatically, without a separate if.

Infinite Loops

If nothing in the body ever makes the condition false, the loop never ends:

int i = 1;
while (i <= 5) {
    System.out.println(i);
    // missing i++: prints 1 forever
}

Other common causes are updating the wrong variable, or updating in the wrong direction (i-- when the condition expects i to grow). If a program hangs or floods the console, check the update step first. Press Ctrl+C in the terminal to stop it.

A loop that is meant to run indefinitely is written while (true) and exits through break or return:

Scanner sc = new Scanner(System.in);
while (true) {
    System.out.print("> ");
    String line = sc.nextLine().strip();
    if (line.equals("exit")) {
        break;
    }
    System.out.println("You typed: " + line);
}

This pattern fits when the exit decision is made in the middle of the body, after reading input, rather than at the top. Servers, game loops, and command shells are built this way.

Condition-Driven Loops

The strength of while is looping on a condition that is not a simple counter.

Repeating until a result is reached

int number = 1234;
int digits = 0;

while (number != 0) {
    number /= 10;
    digits++;
}
System.out.println(digits);   // 4

Each iteration removes the last digit by integer division. The loop runs as many times as there are digits, a number not known before starting. (For an input of 0 this returns 0, an edge case the caller should handle.)

Retrying with a limit

int attempts = 0;
boolean connected = false;

while (!connected && attempts < 3) {
    attempts++;
    System.out.println("Connecting, attempt " + attempts);
    connected = tryConnect();
}

if (!connected) {
    System.out.println("Giving up after " + attempts + " attempts");
}

Two conditions combine: stop on success or after three tries. Bounding a retry loop guarantees it ends even if the operation never succeeds.

Processing until input ends

Scanner sc = new Scanner(System.in);
double sum = 0;
int n = 0;

while (sc.hasNextDouble()) {
    sum += sc.nextDouble();
    n++;
}
if (n > 0) {
    System.out.printf("Average of %d values: %.2f%n", n, sum / n);
}

hasNextDouble() returns false when the input ends or the next token is not a number, so the loop processes exactly the values available.

The do-while Loop

A do-while loop checks its condition after the body, so the body always runs at least once:

do {
    // body
} while (condition);

Note the semicolon after the condition; it is required here.

int x = 10;

while (x < 5) {
    System.out.println("while: " + x);    // never runs
}

do {
    System.out.println("do-while: " + x); // runs once
} while (x < 5);

Output:

do-while: 10

The classic use is input that must be requested before it can be validated:

Scanner sc = new Scanner(System.in);
int choice;

do {
    System.out.print("Choose 1-3: ");
    choice = sc.nextInt();
} while (choice < 1 || choice > 3);

System.out.println("You chose " + choice);

The prompt must appear at least once, and repeats only if the answer is invalid. With a plain while, choice would need a dummy starting value to enter the loop.

whiledo-while
Condition checkedBefore each iterationAfter each iteration
Minimum iterations01
Typical useLoop may legitimately not run at allFirst pass is always needed (menus, prompts)

while Versus for

Any for loop can be written as a while loop, and the reverse. The difference is clarity:

// for: counter-based, all loop control in one line
for (int i = 0; i < 10; i++) { ... }

// while: same behavior, control spread across three places
int i = 0;
while (i < 10) {
    ...
    i++;
}

Use for when iterating a known range or collection. Use while when the loop depends on a condition that changes for reasons other than a simple counter. A while loop's counter variable also stays in scope after the loop, which is sometimes needed and sometimes a source of accidental reuse.

Practical Example: Number Guessing Game

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class GuessGame {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int secret = ThreadLocalRandom.current().nextInt(1, 101);
        int maxTries = 7;
        int tries = 0;
        boolean won = false;

        System.out.println("Guess a number between 1 and 100.");

        while (!won && tries < maxTries) {
            System.out.print("Guess #" + (tries + 1) + ": ");
            if (!sc.hasNextInt()) {
                System.out.println("Enter a whole number.");
                sc.next();               // discard invalid token
                continue;                // does not count as a try
            }
            int guess = sc.nextInt();
            tries++;

            if (guess == secret) {
                won = true;
            } else if (guess < secret) {
                System.out.println("Higher.");
            } else {
                System.out.println("Lower.");
            }
        }

        if (won) {
            System.out.println("Correct in " + tries + " tries!");
        } else {
            System.out.println("Out of tries. The number was " + secret + ".");
        }
    }
}

The loop condition !won && tries < maxTries captures both ways the game can end. Invalid input is discarded and continue jumps back to the condition without incrementing tries. Seven tries is enough to always win with a halving strategy, since 2⁷ = 128 > 100. After the loop, the program checks why it ended, which is a common need after a loop with more than one exit condition.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java While Loop and get answers drawn from it.

Signed-in readers only.