While Literal Boolean Simplify

ID

java.while_literal_boolean_simplify

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code smell

Language

Java

Tags

code-style

Description

Reports while and do-while loops whose condition is a boolean literal (true or false).

Rationale

while(false) produces dead code that will never execute. while(true) creates an infinite loop that conventionally should be written as for(;;) or refactored to use an explicit termination condition. do { …​ } while(true) and do { …​ } while(false) are similarly confusing: the false variant executes the body exactly once (use a plain block instead), and the true variant should use for(;;) or an explicit break condition.

// Bad - boolean literal condition
while (true) {
    process();
    if (done()) break;
}

// Bad - dead code
while (false) {
    neverExecuted();
}

Remediation

For infinite loops, prefer for(;;) or refactor with an explicit condition. Remove dead while(false) blocks entirely. Replace do { …​ } while(false) with a plain block:

// Good - idiomatic infinite loop
for (;;) {
    process();
    if (done()) break;
}

// Good - explicit condition
while (!done()) {
    process();
}