Java While Loop — Syntax, Flow, Do-While & Best Practices
Everything you need to know about Java While Loop — syntax, flow diagram, do-while loop, break, continue, infinite loops, nested loops, labeled statements, while vs for loop comparison, anti-patterns, and real-world production code examples.
Last Updated
March 2026
Read Time
22 min
Level
Beginner to Intermediate
Chapter
7 of 35
What is a While Loop in Java?
A while loop in Java is a control flow statement that repeatedly executes a block of code as long as a given boolean condition remains true. It belongs to the family of entry-controlled loops — the condition is checked before each iteration. If the condition is false on the very first evaluation, the loop body never executes.
While loops are ideal when the number of iterations is not known in advance — for example, reading user input until a valid value is entered, processing records until end-of-file, or waiting for a network response. When the iteration count is fixed, a for loop is usually more readable; when it depends on a runtime condition, while is the natural choice.
Java provides three loop types: for (known count), while (condition-based, check first), and do-while (condition-based, execute first). Understanding when to use each — and mastering break, continue, and labeled statements — is essential for writing clean, correct, and performant Java code.
While Loop — Syntax & Execution Flow
The while loop has the simplest syntax of all Java loops. It consists of the keyword while, a boolean condition in parentheses, and a body in curly braces. The condition is evaluated first — if true, the body executes; if false, the loop ends.
while (condition) { // body — executes as long as condition is true // IMPORTANT: something inside must eventually make condition false } Three components are essential: (1) Initialization — set up the loop variable before the while. (2) Condition — boolean expression checked before each iteration. (3) Update — modify the variable inside the body so the condition eventually becomes false.
Step 1: Initialize loop variable (before the loop). Step 2: Evaluate the condition. Step 3: If condition is TRUE — execute the loop body, then go to Step 4. If condition is FALSE — exit the loop, continue with the next statement. Step 4: Execute the update statement (inside body). Step 5: Go back to Step 2. This cycle continues until the condition becomes false or break is encountered.
Every while loop must have three things to work correctly: (1) Initialization — a variable that controls the loop, set before entering the while. (2) Condition — the boolean expression tested before each iteration; must eventually become false. (3) Update — statement inside the body that changes the control variable toward making the condition false. Missing any one of these leads to a bug: missing initialization causes undefined behavior, missing condition update causes an infinite loop.
public class WhileLoopSyntax {
public static void main(String[] args) {
// ✅ Basic while loop — print 1 to 5
int i = 1; // Step 1: Initialization
while (i <= 5) { // Step 2: Condition check
System.out.println("Count: " + i); // Step 3: Body
i++; // Step 4: Update (i = i + 1)
}
// Output: Count: 1, Count: 2, Count: 3, Count: 4, Count: 5
System.out.println("Loop ended. i = " + i); // i = 6
// ✅ Condition false from the start — body never executes
int j = 10;
while (j < 5) { // false immediately
System.out.println("This never prints");
}
System.out.println("j = " + j); // j = 10 — unchanged
// ✅ Decrementing while loop
int count = 5;
while (count > 0) {
System.out.println("Countdown: " + count);
count--; // count decreases: 5, 4, 3, 2, 1
}
System.out.println("Liftoff!");
// ✅ While loop with step of 2
int num = 0;
while (num <= 10) {
System.out.print(num + " "); // 0 2 4 6 8 10
num += 2;
}
System.out.println();
}
}While Loop Examples — Common Patterns
These examples cover the most common while loop patterns in Java — from sum calculations and digit reversal to input validation and string processing. Each pattern appears frequently in both interview questions and real-world code.
public class WhileLoopExamples {
public static void main(String[] args) {
// ✅ Example 1: Sum of digits of a number
int number = 12345;
int sum = 0;
int temp = number;
while (temp != 0) {
sum += temp % 10; // Extract last digit
temp /= 10; // Remove last digit
}
System.out.println("Sum of digits of " + number + " = " + sum); // 15
// ✅ Example 2: Reverse a number
int original = 5678;
int reversed = 0;
int n = original;
while (n != 0) {
int digit = n % 10;
reversed = reversed * 10 + digit;
n /= 10;
}
System.out.println("Reverse of " + original + " = " + reversed); // 8765
// ✅ Example 3: Count digits in a number
int value = 987654;
int digitCount = 0;
int v = value;
while (v != 0) {
digitCount++;
v /= 10;
}
System.out.println("Digits in " + value + ": " + digitCount); // 6
// ✅ Example 4: Find factorial using while loop
int factNum = 6;
long factorial = 1;
int f = factNum;
while (f > 1) {
factorial *= f;
f--;
}
System.out.println(factNum + "! = " + factorial); // 6! = 720
// ✅ Example 5: Check if a number is a palindrome
int num2 = 1221;
int rev = 0, copy = num2;
while (copy != 0) {
rev = rev * 10 + copy % 10;
copy /= 10;
}
System.out.println(num2 + " is palindrome: " + (num2 == rev)); // true
// ✅ Example 6: Print multiplication table
int table = 7;
int multiplier = 1;
System.out.println("--- Multiplication Table of " + table + " ---");
while (multiplier <= 10) {
System.out.printf("%d x %2d = %d%n", table, multiplier, table * multiplier);
multiplier++;
}
// ✅ Example 7: GCD using Euclidean algorithm
int a = 56, b = 98;
while (b != 0) {
int remainder = a % b;
a = b;
b = remainder;
}
System.out.println("GCD = " + a); // 14
}
}Do-While Loop — Execute First, Check Later
The do-while loop is Java's exit-controlled loop — the body executes first, then the condition is checked. This guarantees the body runs at least once, regardless of whether the condition is initially true or false. It is ideal for scenarios where you must perform an action before you can evaluate whether to continue — like showing a menu and then validating the user's choice.
do { // body — executes at least once // update variable here } while (condition); // ← semicolon required! Key rules: (1) The closing while(condition) MUST be followed by a semicolon — forgetting it is a compile error. (2) The body always executes at least once — even if the condition is initially false. (3) After each body execution, the condition is evaluated; if true, the loop repeats; if false, it exits.
Do-while is the natural fit for menu-driven programs: show the menu → accept choice → process → check if user wants to continue. With a while loop, you would have to show the menu before the loop AND inside the loop (duplication). Do-while eliminates this duplication: the menu shows once at the start of each iteration, and the loop continues only if the user chooses to. Any scenario where 'do something first, then decide to repeat' is required — use do-while.
Do-while is perfect for input validation loops: keep asking for input until valid data is received. Pattern: do { read input } while (input is invalid). The Scanner reads input at least once (which is always needed), then checks if it was valid. If invalid, asks again. This avoids the awkward 'prime read before while' pattern required with a standard while loop for the same task.
import java.util.Scanner;
public class DoWhileLoop {
public static void main(String[] args) {
// ✅ Basic do-while — body runs at least once
int i = 1;
do {
System.out.println("Value: " + i);
i++;
} while (i <= 5);
// Output: Value: 1 through Value: 5
// ✅ Condition false from start — body still runs ONCE
int j = 10;
do {
System.out.println("This prints ONCE even though j > 5: j = " + j);
j++;
} while (j < 5); // false, but body already ran
// ✅ Menu-driven program with do-while
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- MENU ---");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Exit");
System.out.print("Enter choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1 -> System.out.println("Addition selected");
case 2 -> System.out.println("Subtraction selected");
case 3 -> System.out.println("Exiting...");
default -> System.out.println("Invalid! Enter 1-3.");
}
} while (choice != 3); // Repeat until user exits
// ✅ Input validation with do-while
Scanner sc = new Scanner(System.in);
int age;
do {
System.out.print("Enter your age (1-120): ");
age = sc.nextInt();
if (age < 1 || age > 120) {
System.out.println("Invalid age. Please try again.");
}
} while (age < 1 || age > 120);
System.out.println("Valid age entered: " + age);
// ✅ Sum of digits using do-while
int num = 4567;
int digitSum = 0;
do {
digitSum += num % 10;
num /= 10;
} while (num != 0);
System.out.println("Digit sum: " + digitSum); // 22
}
}While vs Do-While — Key Differences
Choosing between while and do-while depends on whether the loop body must execute at least once. The table below summarizes every important distinction.
public class WhileVsDoWhile {
public static void main(String[] args) {
// ✅ while — condition FALSE initially → body never runs
int a = 10;
while (a < 5) {
System.out.println("while body: " + a); // Never prints
a++;
}
System.out.println("After while: a = " + a); // a = 10
// ✅ do-while — condition FALSE initially → body runs ONCE
int b = 10;
do {
System.out.println("do-while body: " + b); // Prints once: 10
b++;
} while (b < 5);
System.out.println("After do-while: b = " + b); // b = 11
// ✅ Equivalent when condition is initially TRUE
int x = 1;
while (x <= 3) {
System.out.print("while: " + x + " ");
x++;
}
System.out.println();
int y = 1;
do {
System.out.print("do-while: " + y + " ");
y++;
} while (y <= 3);
System.out.println();
// Both print: 1 2 3 — identical when condition is initially true
}
}Break and Continue — Loop Control Statements
break and continue are Java's loop control statements. They give you fine-grained control over loop execution — break terminates the loop entirely, while continue skips the rest of the current iteration and moves to the next. Both work with while, do-while, and for loops.
When break is encountered inside a loop, the loop terminates immediately — no more iterations, no condition check. Execution resumes at the first statement after the loop. Use break when: a search target is found (no need to continue scanning), an error condition is detected, the user requests cancellation, or a maximum iteration limit is reached as a safety guard. break also exits switch statements. In nested loops, break exits only the innermost loop containing it — use labeled break to exit outer loops.
When continue is encountered inside a loop, the rest of the current iteration's body is skipped — execution jumps back to the condition check (while loop) or the update expression (for loop). Use continue when: processing a list and you want to skip items that don't meet a filter, skipping null or invalid values, skipping specific indexes or values without complex if-else nesting. continue makes code more readable by avoiding deep nesting — instead of if(valid) { ... } you write if(!valid) continue; followed by the main logic.
Ask: 'Do I want to stop the loop entirely, or just skip this one iteration?' Stop entirely → break. Skip this iteration, continue looping → continue. Example: searching for a name in a list. When found → break (done searching). When name doesn't match → continue (check next name). Both can be used in the same loop for different conditions.
public class BreakContinue {
public static void main(String[] args) {
// ✅ break — stop loop when target found
int[] numbers = {3, 7, 1, 9, 4, 6, 2, 8};
int target = 4;
int foundIndex = -1;
int idx = 0;
while (idx < numbers.length) {
if (numbers[idx] == target) {
foundIndex = idx;
break; // Found — no need to search further
}
idx++;
}
System.out.println(target + " found at index: " + foundIndex); // 4
// ✅ continue — skip even numbers, print only odd
int n = 1;
System.out.print("Odd numbers: ");
while (n <= 20) {
if (n % 2 == 0) {
n++;
continue; // Skip even numbers
}
System.out.print(n + " "); // 1 3 5 7 9 11 13 15 17 19
n++;
}
System.out.println();
// ✅ break with safety guard — prevent infinite loop
int attempts = 0;
int maxAttempts = 100;
int counter = 0;
while (true) {
counter++;
attempts++;
if (counter == 42) break; // Found target
if (attempts >= maxAttempts) {
System.out.println("Max attempts reached!");
break; // Safety exit
}
}
System.out.println("Counter stopped at: " + counter);
// ✅ continue — skip null/invalid values
String[] names = {"Alice", null, "Bob", "", "Charlie", null};
System.out.println("Valid names:");
int k = 0;
while (k < names.length) {
if (names[k] == null || names[k].isBlank()) {
k++;
continue; // Skip null and blank
}
System.out.println(" " + names[k]);
k++;
}
// Prints: Alice, Bob, Charlie
// ✅ break in do-while
int val = 0;
do {
val++;
if (val == 3) break; // Exit when val reaches 3
System.out.println("val = " + val);
} while (val < 10);
System.out.println("Exited at val = " + val); // val = 3
}
}Infinite Loop — When & How to Use while(true)
An infinite loop is a loop that runs forever because its condition never becomes false. While accidental infinite loops are bugs, intentional infinite loops using while(true) are a legitimate and common pattern in Java for server loops, event processing, background tasks, and game loops. The key is always pairing them with a proper break or return exit condition.
while(true) { ... break; } is a clean idiom for: server loops that process incoming requests indefinitely, game loops that run every frame until the game ends, background threads polling a queue or sensor, retry loops that attempt an operation until success. Always include a break, return, or System.exit() as the exit condition. Using while(true) is more explicit than while(someFlag) when the exit logic is complex — the break inside the loop makes the exit condition visible exactly where it matters.
Causes of unintentional infinite loops: (1) Forgetting to update the loop variable — while(i < 10) without i++ inside the body. (2) Wrong update direction — while(i > 0) with i++ instead of i--. (3) Updating the wrong variable — using a different variable name inside the body. (4) Condition that can never become false — while(x != 7) but x is incremented by 2 from an even start (never hits 7). (5) Off-by-one in condition — while(i <= 10) when the update causes i to skip over 10. Always trace through your first few iterations mentally before running.
Signs of an infinite loop: program hangs, CPU spikes to 100%, no output (or repeating output). Fixes: (1) Add a print statement inside the loop to trace variable values. (2) Add a counter and break after a maximum iteration count. (3) Use a debugger to step through iterations. (4) Review the condition and update logic carefully. (5) Add Thread.sleep() in tight loops to reduce CPU burn while debugging. In production code, always add a maximum iteration guard even to loops you believe are correct.
public class InfiniteLoop {
public static void main(String[] args) {
// ✅ Intentional infinite loop — exit with break
int count = 0;
while (true) {
count++;
System.out.println("Processing item: " + count);
if (count >= 5) {
System.out.println("Done processing.");
break; // Exit the loop
}
}
// ✅ Retry pattern — attempt until success
int attempt = 0;
boolean success = false;
while (true) {
attempt++;
System.out.println("Attempt #" + attempt);
// Simulate success on 3rd attempt
if (attempt == 3) {
success = true;
break;
}
}
System.out.println("Success after " + attempt + " attempts: " + success);
// ❌ Accidental infinite loop — NEVER run this!
// int x = 0;
// while (x < 10) {
// System.out.println(x); // ❌ x never updated — runs forever
// }
// ❌ Wrong update direction — NEVER run this!
// int y = 10;
// while (y > 0) {
// System.out.println(y);
// y++; // ❌ y grows, never reaches 0 — infinite loop
// }
// ✅ Safe infinite loop with max guard
int iterations = 0;
int MAX_ITERATIONS = 1000; // Safety guard
while (true) {
iterations++;
// ... do work ...
if (/* exit condition */ iterations % 7 == 0) break;
if (iterations >= MAX_ITERATIONS) {
System.out.println("Safety limit reached!");
break;
}
}
System.out.println("Completed in " + iterations + " iterations");
}
}Nested While Loops — Loops Inside Loops
A nested while loop is a while loop placed inside another while loop. The inner loop executes completely for each iteration of the outer loop. Nested loops are used for 2D patterns, matrix operations, combination generation, and multi-level data traversal. Be mindful of time complexity — two nested loops each running n times produce O(n²) operations.
public class NestedWhileLoop {
public static void main(String[] args) {
// ✅ Example 1: Multiplication table grid
int row = 1;
while (row <= 5) {
int col = 1;
while (col <= 5) {
System.out.printf("%4d", row * col);
col++;
}
System.out.println(); // New line after each row
row++;
}
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15
// 4 8 12 16 20
// 5 10 15 20 25
// ✅ Example 2: Star pattern — right triangle
int r = 1;
while (r <= 5) {
int star = 1;
while (star <= r) {
System.out.print("* ");
star++;
}
System.out.println();
r++;
}
// *
// * *
// * * *
// * * * *
// * * * * *
// ✅ Example 3: Inverted triangle
int i = 5;
while (i >= 1) {
int s = 1;
while (s <= i) {
System.out.print("* ");
s++;
}
System.out.println();
i--;
}
// ✅ Example 4: Print pairs where sum equals target
int[] arr = {1, 4, 3, 7, 2, 6};
int targetSum = 7;
System.out.println("Pairs with sum " + targetSum + ":");
int p = 0;
while (p < arr.length) {
int q = p + 1;
while (q < arr.length) {
if (arr[p] + arr[q] == targetSum) {
System.out.println(" (" + arr[p] + ", " + arr[q] + ")");
}
q++;
}
p++;
}
}
}Labeled Break & Continue — Exiting Nested Loops
Java supports labeled break and labeled continue for controlling nested loops. A label is an identifier followed by a colon, placed before the outer loop. break labelName exits the labeled (outer) loop entirely, while continue labelName skips to the next iteration of the labeled (outer) loop. These are useful when you need to exit multiple levels of nesting at once.
public class LabeledBreakContinue {
public static void main(String[] args) {
// ✅ Labeled break — exit OUTER loop from inner loop
System.out.println("--- Labeled Break ---");
outer: // Label for the outer loop
while (true) {
int i = 0;
while (i < 5) {
if (i == 3) {
System.out.println("Breaking outer loop at i = " + i);
break outer; // Exits the outer while loop
}
System.out.println("i = " + i);
i++;
}
}
System.out.println("After outer loop");
// Output: i = 0, i = 1, i = 2, Breaking outer loop at i = 3
// ✅ Labeled continue — skip outer loop iteration
System.out.println("--- Labeled Continue ---");
int row = 0;
rowLoop:
while (row < 4) {
int col = 0;
while (col < 4) {
if (col == 2) {
row++;
continue rowLoop; // Skip rest of outer iteration
}
System.out.println("row=" + row + ", col=" + col);
col++;
}
row++;
}
// ✅ Practical example: search in 2D array
System.out.println("--- 2D Search with Labeled Break ---");
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int searchTarget = 5;
int foundRow = -1, foundCol = -1;
search:
int r = 0;
while (r < matrix.length) {
int c = 0;
while (c < matrix[r].length) {
if (matrix[r][c] == searchTarget) {
foundRow = r;
foundCol = c;
break search; // Exit both loops immediately
}
c++;
}
r++;
}
System.out.println(searchTarget + " found at [" + foundRow + "][" + foundCol + "]");
// Output: 5 found at [1][2]
}
}While Loop vs For Loop — When to Use Which
Both while and for loops can technically perform the same tasks — any for loop can be rewritten as a while loop and vice versa. The difference is readability and intent. Choosing the right loop type makes your code self-documenting.
public class WhileVsFor {
public static void main(String[] args) {
// ✅ For loop — best for known count / range
for (int i = 1; i <= 5; i++) {
System.out.print(i + " "); // 1 2 3 4 5
}
System.out.println();
// ✅ Equivalent while loop — more verbose for fixed range
int i = 1;
while (i <= 5) {
System.out.print(i + " "); // 1 2 3 4 5
i++;
}
System.out.println();
// ✅ While loop — best for unknown count / condition-driven
// Read digits until non-digit found
String input = "12345abc";
int pos = 0;
while (pos < input.length() && Character.isDigit(input.charAt(pos))) {
pos++;
}
System.out.println("Digits end at index: " + pos); // 5
System.out.println("Numeric part: " + input.substring(0, pos)); // 12345
// ✅ While — processing until sentinel value
int[] data = {5, 12, 3, -1, 8, 7}; // -1 is sentinel
int idx = 0;
int total = 0;
while (idx < data.length && data[idx] != -1) {
total += data[idx];
idx++;
}
System.out.println("Sum before sentinel: " + total); // 20
// ✅ For loop — cleaner for array traversal
int[] arr = {10, 20, 30, 40, 50};
for (int x : arr) {
System.out.print(x + " "); // 10 20 30 40 50
}
System.out.println();
}
}Common Mistakes & Pitfalls — Bugs That Fool Everyone
These are the most common while loop mistakes in Java — from accidentally creating infinite loops to off-by-one errors and misusing break and continue.
// ❌ MISTAKE 1: Forgetting to update the loop variable (infinite loop)
int i = 0;
while (i < 10) {
System.out.println(i); // ❌ i never changes — infinite loop!
}
// ✅ Fix: add i++ inside the body
while (i < 10) {
System.out.println(i);
i++; // ✅ Update i each iteration
}
// ❌ MISTAKE 2: Wrong update direction (infinite loop)
int j = 10;
while (j > 0) {
System.out.println(j);
j++; // ❌ j increases, never reaches 0 — infinite loop!
}
// ✅ Fix: decrement j
while (j > 0) {
System.out.println(j);
j--; // ✅
}
// ❌ MISTAKE 3: Semicolon after while condition (empty loop body)
int k = 0;
while (k < 5); // ❌ Semicolon makes the body empty — infinite loop!
{
System.out.println(k); // This block runs ONCE after the loop (if ever)
k++;
}
// ✅ Fix: remove the semicolon
while (k < 5) {
System.out.println(k);
k++;
}
// ❌ MISTAKE 4: Off-by-one error — wrong boundary condition
int[] arr = {10, 20, 30, 40, 50};
int idx = 0;
while (idx <= arr.length) { // ❌ <= causes ArrayIndexOutOfBoundsException!
System.out.println(arr[idx]);
idx++;
}
// ✅ Fix: use < not <=
while (idx < arr.length) { // ✅ correct boundary
System.out.println(arr[idx]);
idx++;
}
// ❌ MISTAKE 5: Modifying loop variable incorrectly after continue
int n = 0;
while (n < 10) {
if (n % 2 == 0) {
continue; // ❌ n never incremented for even values — infinite loop!
}
System.out.println(n);
n++;
}
// ✅ Fix: increment BEFORE continue
while (n < 10) {
n++; // ✅ Always increment first
if (n % 2 == 0) continue;
System.out.println(n);
}
// ❌ MISTAKE 6: Missing semicolon in do-while (compile error)
// do {
// System.out.println("hi");
// } while (true) // ❌ Missing semicolon — compile error!
// ✅ Fix:
// do { ... } while (true); // ✅ Semicolon required after do-whileBad Practices & Anti-Patterns — What Senior Developers Reject
These anti-patterns represent common misuses of while loops in professional Java code. Each one either causes bugs, hurts performance, or makes code harder to read and maintain.
A while(true) loop without a maximum iteration guard or timeout is a reliability risk. If the exit condition has a bug, the loop runs forever, pegging the CPU at 100% and starving other threads. In production code, always add a counter check (if iterations > MAX_LIMIT break) or a time-based exit (if System.currentTimeMillis() > deadline break). This is especially critical in server applications, scheduled jobs, and background threads where a runaway loop can take down the entire service.
Writing int i = 0; while(i < n) { ... i++; } when a for(int i = 0; i < n; i++) { ... } would be clearer is an anti-pattern. The for loop encapsulates initialization, condition, and update in one line — making the loop's intent immediately obvious. The while version spreads these three concerns across multiple lines and leaves the update variable (i) accessible outside the loop (where it may not belong). Use the loop type that best expresses your intent — for for known counts, while for unknown conditions.
Writing while(condition) singleStatement; without curly braces is legal in Java but dangerous. Adding a second line below it looks like it's inside the loop but is actually outside — a classic maintenance bug that static analysis tools flag universally. Always use curly braces { } for all loop bodies, even single-statement ones. The saved typing of two characters is not worth the maintenance risk. All major Java style guides (Google, Oracle, Airbnb) mandate braces.
Three or more levels of nested while loops produces code that is almost impossible to read, debug, and maintain. If you find yourself writing a third nested loop, it is a strong signal to refactor: extract the inner loops into separate methods, use data structures (HashMap, Set) to reduce the need for nested searching, or find an algorithm with better complexity. Deep nesting is both a code smell and a performance red flag — triple-nested loops over n elements are O(n³).
Multiple break and continue statements scattered throughout a loop body usually indicate that the loop condition itself is wrong or the logic needs restructuring. One break at the end of a search loop is fine. Five break statements with complex conditions throughout the body is a design problem. Refactor by: simplifying the loop condition, extracting complex logic into boolean-returning methods, splitting one complex loop into two simpler ones, or using Stream API filters and operations instead of imperative loops.
Declaring the loop control variable before the loop when it is only needed inside the loop unnecessarily pollutes the enclosing scope, making the variable accessible after the loop where it may contain a stale or meaningless value. For while loops, this is sometimes unavoidable (unlike for loops which scope the variable to the header). When using while, minimize the scope of all related variables by declaring them as close to use as possible and not reusing loop control variables for unrelated purposes after the loop.
Real-World Production Code Examples — While Loops in Context
The following examples show idiomatic, production-grade Java while loop usage — patterns seen in real Spring Boot applications, file processors, and enterprise Java codebases.
package com.techsustainify.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileProcessor {
// ✅ Classic while loop pattern: read until end of file
public List<String> readLines(String filePath) throws IOException {
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
// readLine() returns null at end of file — perfect while condition
while ((line = reader.readLine()) != null) {
if (line.isBlank()) continue; // Skip blank lines
if (line.startsWith("#")) continue; // Skip comments
lines.add(line.strip());
}
}
return lines;
}
// ✅ Processing CSV data with while loop
public List<String[]> parseCSV(String filePath) throws IOException {
List<String[]> records = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
boolean isHeader = true;
while ((line = reader.readLine()) != null) {
if (isHeader) {
isHeader = false; // Skip header row
continue;
}
String[] fields = line.split(",");
if (fields.length < 3) continue; // Skip malformed rows
records.add(fields);
}
}
return records;
}
// ✅ Retry logic with while loop — network/DB call with backoff
public String fetchWithRetry(String url, int maxRetries) {
int attempt = 0;
while (attempt < maxRetries) {
attempt++;
try {
System.out.println("Attempt " + attempt + " for: " + url);
// Simulate HTTP call
String result = callExternalService(url);
return result; // Success — exit loop
} catch (Exception e) {
System.out.println("Attempt " + attempt + " failed: " + e.getMessage());
if (attempt < maxRetries) {
try {
// Exponential backoff: 1s, 2s, 4s...
Thread.sleep(1000L * (long) Math.pow(2, attempt - 1));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
}
throw new RuntimeException("All " + maxRetries + " attempts failed for: " + url);
}
private String callExternalService(String url) {
// Simulated service call
return "Response from " + url;
}
}package com.techsustainify.service;
import java.util.ArrayList;
import java.util.List;
public class PaginationService {
// ✅ While loop for paginated data processing
// Pattern: fetch page → process → check if more pages → repeat
public List<String> fetchAllUsers() {
List<String> allUsers = new ArrayList<>();
int page = 1;
int pageSize = 100;
boolean hasMore = true;
while (hasMore) {
List<String> pageData = fetchPage(page, pageSize);
allUsers.addAll(pageData);
System.out.println("Fetched page " + page + ": " + pageData.size() + " records");
// If fewer records than page size, we've reached the last page
hasMore = (pageData.size() == pageSize);
page++;
}
System.out.println("Total users fetched: " + allUsers.size());
return allUsers;
}
private List<String> fetchPage(int page, int size) {
// Simulated DB/API page fetch
List<String> result = new ArrayList<>();
// Simulate 250 total records across 3 pages
int totalRecords = 250;
int start = (page - 1) * size;
int end = Math.min(start + size, totalRecords);
for (int i = start; i < end; i++) {
result.add("User_" + (i + 1));
}
return result;
}
// ✅ Queue draining with while loop
public void processQueue(java.util.Queue<String> taskQueue) {
System.out.println("Processing " + taskQueue.size() + " tasks...");
int processed = 0;
while (!taskQueue.isEmpty()) {
String task = taskQueue.poll(); // Remove and retrieve head
System.out.println("Processing: " + task);
processed++;
}
System.out.println("Done. Processed " + processed + " tasks.");
}
}While Loop Flow Diagram — Visualizing Execution
This flowchart shows the complete execution flow of both the while loop and do-while loop — highlighting the critical difference in when the condition is evaluated relative to the body.
Code Execution Flow — from source to output
Java While Loop Interview Questions — Beginner to Advanced
While loop questions test your understanding of loop control flow, edge cases, condition evaluation, and the ability to trace code output. These appear frequently in Java interviews at all levels.
Practice Questions — Test Your While Loop Knowledge
Challenge yourself with these practice questions. Attempt each independently before reading the answer — active recall significantly improves retention compared to passive reading.
1. What is the output? int i = 1; while (i <= 5) { if (i == 3) { i++; continue; } System.out.print(i + " "); i++; }
Easy2. Trace the output: int n = 100; while (n > 1) { if (n % 2 == 0) { n /= 2; } else { n = 3 * n + 1; } System.out.print(n + " "); }
Medium3. Write a while loop program to print all prime numbers between 2 and 50.
Medium4. What is the output? Explain why. int x = 0; do { x++; } while (x < 0); System.out.println(x);
Easy5. Write a while loop to find the LCM (Least Common Multiple) of two numbers without using any built-in methods.
Medium6. Identify the bug and fix it: int i = 1; while (i < 10); { System.out.println(i); i++; }
Medium7. Write a program using a nested while loop to print the following pattern: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Easy8. What is the output? int a = 1, b = 1; while (a <= 100) { int c = a + b; a = b; b = c; } System.out.println(a);
HardConclusion — While Loops: The Foundation of Conditional Repetition
The while loop is one of the most fundamental building blocks in Java programming. While it may seem simpler than the for loop, mastering it — especially understanding when to use while vs for, how to avoid infinite loops, when to reach for break and continue, and how to use do-while correctly — separates confident Java developers from beginners.
In real-world Java applications, while loops power file reading, paginated API fetching, retry logic, queue processing, server event loops, and algorithm implementations. The difference between good and bad while loop code is visible in whether loops have proper update statements, appropriate guards against infinite execution, and clear, readable conditions. Mastering loops is mastering algorithmic thinking.
Your next step: Java Arrays — where while loops become the backbone of array traversal, searching, sorting, and processing. Arrays and loops are inseparable — and everything you've learned about while loops will be applied immediately. ☕