DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 1: `while` Loop

When writing programs, we often need to execute the same block of code multiple times.

For example:

  • Reading records from a database
  • Processing files line by line
  • Displaying menu options until the user exits
  • Traversing collections
  • Waiting for a task to complete

Instead of writing the same code repeatedly, Java provides iterative statements, commonly known as loops.

In this article, we'll explore the while loop, understand how it works, learn its rules, and discuss common interview questions and beginner mistakes.


What Are Iterative Statements?

Iterative statements repeatedly execute a block of code as long as a specified condition remains true.

Java provides four looping constructs:

  • while
  • do-while
  • for
  • Enhanced for (for-each)

Each loop has its own use cases.

In this article, we'll focus on the while loop.


What Is the while Loop?

A while loop repeatedly executes a block of code as long as its condition evaluates to true.

It is most useful when the number of iterations is unknown beforehand.

Typical examples include:

  • Reading data until the end of a file
  • Processing database records
  • Traversing an iterator
  • Waiting for user input

Syntax

while (condition) {
    // loop body
}
Enter fullscreen mode Exit fullscreen mode

The condition is checked before each iteration.

If the condition is false initially, the loop body never executes.


How the while Loop Works

The execution flow is simple:

  1. Evaluate the condition.
  2. If it is true, execute the loop body.
  3. Return to step 1.
  4. If the condition becomes false, exit the loop.

Because the condition is checked first, a while loop may execute zero or more times.


Your First while Program

int count = 1;

while (count <= 5) {

    System.out.println(count);

    count++;

}
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Example: Printing Even Numbers

int number = 2;

while (number <= 10) {

    System.out.println(number);

    number += 2;

}
Enter fullscreen mode Exit fullscreen mode

Output

2
4
6
8
10
Enter fullscreen mode Exit fullscreen mode

Real-World Examples

The while loop is frequently used when working with APIs that continue until no more data is available.

Reading Database Records

while (resultSet.next()) {

    // Process one record

}
Enter fullscreen mode Exit fullscreen mode

Using an Iterator

while (iterator.hasNext()) {

    Object value = iterator.next();

}
Enter fullscreen mode Exit fullscreen mode

Reading an Enumeration

while (enumeration.hasMoreElements()) {

    Object value = enumeration.nextElement();

}
Enter fullscreen mode Exit fullscreen mode

These are common patterns you'll see in enterprise Java applications.


Rule 1: The Condition Must Be boolean

The expression inside a while loop must evaluate to a boolean value.

Correct

int count = 1;

while (count <= 5) {

    count++;

}
Enter fullscreen mode Exit fullscreen mode

The expression

count <= 5
Enter fullscreen mode Exit fullscreen mode

returns either true or false.


Incorrect

while (1) {

}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

incompatible types:
int cannot be converted to boolean
Enter fullscreen mode Exit fullscreen mode

Unlike C or C++, Java does not treat non-zero values as true.


Rule 2: Curly Braces Are Optional

If the loop body contains only one statement, braces may be omitted.

int count = 1;

while (count <= 3)

    System.out.println(count++);
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
Enter fullscreen mode Exit fullscreen mode

Although valid, using braces is generally recommended for better readability.


Multiple Statements Require Braces

Incorrect

int count = 1;

while (count <= 3)

    System.out.println(count);

    count++;
Enter fullscreen mode Exit fullscreen mode

The loop becomes infinite because only the first statement belongs to the loop.

Correct

int count = 1;

while (count <= 3) {

    System.out.println(count);

    count++;

}
Enter fullscreen mode Exit fullscreen mode

Variable Declarations Need Braces

Incorrect

while (true)

    int number = 10;
Enter fullscreen mode Exit fullscreen mode

Compile-time error

variable declaration not allowed here
Enter fullscreen mode Exit fullscreen mode

Correct

while (true) {

    int number = 10;

    break;

}
Enter fullscreen mode Exit fullscreen mode

Empty Statement (;)

A semicolon by itself is a valid statement.

while (true);

System.out.println("Hello");
Enter fullscreen mode Exit fullscreen mode

The loop never ends.

Therefore,

System.out.println("Hello");
Enter fullscreen mode Exit fullscreen mode

is never reached.


Infinite Loops

A loop whose condition never becomes false is called an infinite loop.

Example

while (true) {

    System.out.println("Running...");

}
Enter fullscreen mode Exit fullscreen mode

This loop continues forever unless the program terminates externally.

Infinite loops are useful for:

  • Server applications
  • Event listeners
  • Message consumers
  • Game loops

Understanding the Unreachable Statement Rule

One of the most interesting Java interview topics is the unreachable statement rule.

Java's compiler reports an error whenever it can prove that a statement can never execute.


Case 1

while (true) {

}

System.out.println("Done");
Enter fullscreen mode Exit fullscreen mode

Compile-time error

unreachable statement
Enter fullscreen mode Exit fullscreen mode

The compiler knows the loop never exits.


Case 2

while (false) {

    System.out.println("Hello");

}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

unreachable statement
Enter fullscreen mode Exit fullscreen mode

Since the condition is always false, the loop body can never execute.


Case 3

int start = 10;
int end = 20;

while (start < end) {

}

System.out.println("Finished");
Enter fullscreen mode Exit fullscreen mode

This compiles successfully.

Why?

The compiler cannot determine the values of start and end at compile time.

Although the program runs forever, the compiler doesn't know that.


The Effect of final

Now consider the same example using final.

final int start = 10;
final int end = 20;

while (start < end) {

}

System.out.println("Finished");
Enter fullscreen mode Exit fullscreen mode

Compile-time error

unreachable statement
Enter fullscreen mode Exit fullscreen mode

Why Does final Change Everything?

A final variable initialized with a constant becomes a compile-time constant.

The compiler effectively sees

while (10 < 20) {

}
Enter fullscreen mode Exit fullscreen mode

which becomes

while (true) {

}
Enter fullscreen mode Exit fullscreen mode

Since the compiler now knows the loop never ends, it reports the unreachable statement.


Execution Trace

int count = 1;

while (count <= 3) {

    System.out.println(count);

    count++;

}
Enter fullscreen mode Exit fullscreen mode
Iteration count before Condition Output count after
1 1 true 1 2
2 2 true 2 3
3 3 true 3 4
4 4 false

Common Beginner Mistakes

Forgetting to Update the Loop Variable

Incorrect

int count = 1;

while (count <= 5) {

    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode

The condition never changes.

Result:

Infinite loop.


Using Assignment Instead of Comparison

Incorrect

boolean running = false;

while (running = true) {

}
Enter fullscreen mode Exit fullscreen mode

The assignment returns true, causing an infinite loop.


Accidentally Writing an Empty Loop

while (count <= 5);

System.out.println("Done");
Enter fullscreen mode Exit fullscreen mode

The semicolon creates an empty loop.

The println() is outside the loop.


Using a Non-Boolean Condition

Incorrect

while (100) {

}
Enter fullscreen mode Exit fullscreen mode

Only boolean expressions are allowed.


Best Practices

  • Use a while loop when the number of iterations is unknown.
  • Always ensure the loop condition eventually becomes false.
  • Prefer meaningful variable names such as count, index, or remainingItems.
  • Use braces even for a single statement.
  • Avoid writing complex conditions.
  • Be careful not to accidentally place a semicolon after the while condition.

Interview Questions

What is the difference between while and do-while?

A while loop checks the condition before executing the body.

A do-while loop checks the condition after executing the body.


Can a while loop execute zero times?

Yes.

If the condition is initially false, the loop body never executes.


Why does while (1) fail in Java?

Because Java requires a boolean expression.

Unlike C or C++, integers cannot be used as boolean values.


Why does adding final sometimes cause an unreachable statement error?

Because final variables initialized with constants become compile-time constants, allowing the compiler to determine that the loop is infinite.


Quick Memory Trick 🧠

Remember the word WHILE:

  • W → Wait until the condition becomes false
  • H → Header contains a boolean condition
  • I → Iterates zero or more times
  • L → Loop variable must change
  • E → Exit when the condition becomes false

Key Takeaways

  • A while loop repeats as long as its condition is true.
  • The condition is evaluated before each iteration.
  • The loop may execute zero or more times.
  • The condition must evaluate to a boolean value.
  • Curly braces are optional for a single statement but recommended.
  • A misplaced semicolon creates an empty loop.
  • Java detects unreachable statements during compilation.
  • final variables can change compile-time behavior by allowing the compiler to evaluate loop conditions.

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)